xref: /freebsd/sys/cam/ctl/ctl.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
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/mutex.h>
56 #include <sys/condvar.h>
57 #include <sys/malloc.h>
58 #include <sys/conf.h>
59 #include <sys/ioccom.h>
60 #include <sys/queue.h>
61 #include <sys/sbuf.h>
62 #include <sys/endian.h>
63 #include <sys/sysctl.h>
64 
65 #include <cam/cam.h>
66 #include <cam/scsi/scsi_all.h>
67 #include <cam/scsi/scsi_da.h>
68 #include <cam/ctl/ctl_io.h>
69 #include <cam/ctl/ctl.h>
70 #include <cam/ctl/ctl_frontend.h>
71 #include <cam/ctl/ctl_frontend_internal.h>
72 #include <cam/ctl/ctl_util.h>
73 #include <cam/ctl/ctl_backend.h>
74 #include <cam/ctl/ctl_ioctl.h>
75 #include <cam/ctl/ctl_ha.h>
76 #include <cam/ctl/ctl_private.h>
77 #include <cam/ctl/ctl_debug.h>
78 #include <cam/ctl/ctl_scsi_all.h>
79 #include <cam/ctl/ctl_error.h>
80 
81 struct ctl_softc *control_softc = NULL;
82 
83 /*
84  * The default is to run with CTL_DONE_THREAD turned on.  Completed
85  * transactions are queued for processing by the CTL work thread.  When
86  * CTL_DONE_THREAD is not defined, completed transactions are processed in
87  * the caller's context.
88  */
89 #define CTL_DONE_THREAD
90 
91 /*
92  *  * Use the serial number and device ID provided by the backend, rather than
93  *   * making up our own.
94  *    */
95 #define CTL_USE_BACKEND_SN
96 
97 /*
98  * Size and alignment macros needed for Copan-specific HA hardware.  These
99  * can go away when the HA code is re-written, and uses busdma for any
100  * hardware.
101  */
102 #define	CTL_ALIGN_8B(target, source, type)				\
103 	if (((uint32_t)source & 0x7) != 0)				\
104 		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
105 	else								\
106 		target = (type)source;
107 
108 #define	CTL_SIZE_8B(target, size)					\
109 	if ((size & 0x7) != 0)						\
110 		target = size + (0x8 - (size & 0x7));			\
111 	else								\
112 		target = size;
113 
114 #define CTL_ALIGN_8B_MARGIN	16
115 
116 /*
117  * Template mode pages.
118  */
119 
120 /*
121  * Note that these are default values only.  The actual values will be
122  * filled in when the user does a mode sense.
123  */
124 static struct copan_power_subpage power_page_default = {
125 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
126 	/*subpage*/ PWR_SUBPAGE_CODE,
127 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
128 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
129 	/*page_version*/ PWR_VERSION,
130 	/* total_luns */ 26,
131 	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
132 	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
133 		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
134 		      0, 0, 0, 0, 0, 0}
135 };
136 
137 static struct copan_power_subpage power_page_changeable = {
138 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
139 	/*subpage*/ PWR_SUBPAGE_CODE,
140 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
141 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
142 	/*page_version*/ 0,
143 	/* total_luns */ 0,
144 	/* max_active_luns*/ 0,
145 	/*reserved*/ {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, 0}
148 };
149 
150 static struct copan_aps_subpage aps_page_default = {
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 	APS_VERSION, //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_aps_subpage aps_page_changeable = {
163 	APS_PAGE_CODE | SMPH_SPF, //page_code
164 	APS_SUBPAGE_CODE, //subpage
165 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
166 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
167 	0, //page_version
168 	0, //lock_active
169 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
170 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
171 	0, 0, 0, 0, 0} //reserved
172 };
173 
174 static struct copan_debugconf_subpage debugconf_page_default = {
175 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
176 	DBGCNF_SUBPAGE_CODE,		/* subpage */
177 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
178 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
179 	DBGCNF_VERSION,			/* page_version */
180 	{CTL_TIME_IO_DEFAULT_SECS>>8,
181 	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
182 };
183 
184 static struct copan_debugconf_subpage debugconf_page_changeable = {
185 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
186 	DBGCNF_SUBPAGE_CODE,		/* subpage */
187 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
188 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
189 	0,				/* page_version */
190 	{0xff,0xff},			/* ctl_time_io_secs */
191 };
192 
193 static struct scsi_format_page format_page_default = {
194 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
195 	/*page_length*/sizeof(struct scsi_format_page) - 2,
196 	/*tracks_per_zone*/ {0, 0},
197 	/*alt_sectors_per_zone*/ {0, 0},
198 	/*alt_tracks_per_zone*/ {0, 0},
199 	/*alt_tracks_per_lun*/ {0, 0},
200 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
201 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
202 	/*bytes_per_sector*/ {0, 0},
203 	/*interleave*/ {0, 0},
204 	/*track_skew*/ {0, 0},
205 	/*cylinder_skew*/ {0, 0},
206 	/*flags*/ SFP_HSEC,
207 	/*reserved*/ {0, 0, 0}
208 };
209 
210 static struct scsi_format_page format_page_changeable = {
211 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
212 	/*page_length*/sizeof(struct scsi_format_page) - 2,
213 	/*tracks_per_zone*/ {0, 0},
214 	/*alt_sectors_per_zone*/ {0, 0},
215 	/*alt_tracks_per_zone*/ {0, 0},
216 	/*alt_tracks_per_lun*/ {0, 0},
217 	/*sectors_per_track*/ {0, 0},
218 	/*bytes_per_sector*/ {0, 0},
219 	/*interleave*/ {0, 0},
220 	/*track_skew*/ {0, 0},
221 	/*cylinder_skew*/ {0, 0},
222 	/*flags*/ 0,
223 	/*reserved*/ {0, 0, 0}
224 };
225 
226 static struct scsi_rigid_disk_page rigid_disk_page_default = {
227 	/*page_code*/SMS_RIGID_DISK_PAGE,
228 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
229 	/*cylinders*/ {0, 0, 0},
230 	/*heads*/ CTL_DEFAULT_HEADS,
231 	/*start_write_precomp*/ {0, 0, 0},
232 	/*start_reduced_current*/ {0, 0, 0},
233 	/*step_rate*/ {0, 0},
234 	/*landing_zone_cylinder*/ {0, 0, 0},
235 	/*rpl*/ SRDP_RPL_DISABLED,
236 	/*rotational_offset*/ 0,
237 	/*reserved1*/ 0,
238 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
239 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
240 	/*reserved2*/ {0, 0}
241 };
242 
243 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
244 	/*page_code*/SMS_RIGID_DISK_PAGE,
245 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
246 	/*cylinders*/ {0, 0, 0},
247 	/*heads*/ 0,
248 	/*start_write_precomp*/ {0, 0, 0},
249 	/*start_reduced_current*/ {0, 0, 0},
250 	/*step_rate*/ {0, 0},
251 	/*landing_zone_cylinder*/ {0, 0, 0},
252 	/*rpl*/ 0,
253 	/*rotational_offset*/ 0,
254 	/*reserved1*/ 0,
255 	/*rotation_rate*/ {0, 0},
256 	/*reserved2*/ {0, 0}
257 };
258 
259 static struct scsi_caching_page caching_page_default = {
260 	/*page_code*/SMS_CACHING_PAGE,
261 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
262 	/*flags1*/ SCP_DISC | SCP_WCE,
263 	/*ret_priority*/ 0,
264 	/*disable_pf_transfer_len*/ {0xff, 0xff},
265 	/*min_prefetch*/ {0, 0},
266 	/*max_prefetch*/ {0xff, 0xff},
267 	/*max_pf_ceiling*/ {0xff, 0xff},
268 	/*flags2*/ 0,
269 	/*cache_segments*/ 0,
270 	/*cache_seg_size*/ {0, 0},
271 	/*reserved*/ 0,
272 	/*non_cache_seg_size*/ {0, 0, 0}
273 };
274 
275 static struct scsi_caching_page caching_page_changeable = {
276 	/*page_code*/SMS_CACHING_PAGE,
277 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
278 	/*flags1*/ 0,
279 	/*ret_priority*/ 0,
280 	/*disable_pf_transfer_len*/ {0, 0},
281 	/*min_prefetch*/ {0, 0},
282 	/*max_prefetch*/ {0, 0},
283 	/*max_pf_ceiling*/ {0, 0},
284 	/*flags2*/ 0,
285 	/*cache_segments*/ 0,
286 	/*cache_seg_size*/ {0, 0},
287 	/*reserved*/ 0,
288 	/*non_cache_seg_size*/ {0, 0, 0}
289 };
290 
291 static struct scsi_control_page control_page_default = {
292 	/*page_code*/SMS_CONTROL_MODE_PAGE,
293 	/*page_length*/sizeof(struct scsi_control_page) - 2,
294 	/*rlec*/0,
295 	/*queue_flags*/0,
296 	/*eca_and_aen*/0,
297 	/*reserved*/0,
298 	/*aen_holdoff_period*/{0, 0}
299 };
300 
301 static struct scsi_control_page control_page_changeable = {
302 	/*page_code*/SMS_CONTROL_MODE_PAGE,
303 	/*page_length*/sizeof(struct scsi_control_page) - 2,
304 	/*rlec*/SCP_DSENSE,
305 	/*queue_flags*/0,
306 	/*eca_and_aen*/0,
307 	/*reserved*/0,
308 	/*aen_holdoff_period*/{0, 0}
309 };
310 
311 
312 /*
313  * XXX KDM move these into the softc.
314  */
315 static int rcv_sync_msg;
316 static int persis_offset;
317 static uint8_t ctl_pause_rtr;
318 static int     ctl_is_single;
319 static int     index_to_aps_page;
320 int	   ctl_disable = 0;
321 
322 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
323 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, disable, CTLFLAG_RDTUN, &ctl_disable, 0,
324 	   "Disable CTL");
325 TUNABLE_INT("kern.cam.ctl.disable", &ctl_disable);
326 
327 /*
328  * Serial number (0x80), device id (0x83), and supported pages (0x00)
329  */
330 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	3
331 
332 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
333 				  int param);
334 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
335 static void ctl_init(void);
336 void ctl_shutdown(void);
337 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
338 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
339 static void ctl_ioctl_online(void *arg);
340 static void ctl_ioctl_offline(void *arg);
341 static int ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id);
342 static int ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id);
343 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
344 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
345 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
346 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio, int have_lock);
347 static int ctl_ioctl_submit_wait(union ctl_io *io);
348 static void ctl_ioctl_datamove(union ctl_io *io);
349 static void ctl_ioctl_done(union ctl_io *io);
350 static void ctl_ioctl_hard_startstop_callback(void *arg,
351 					      struct cfi_metatask *metatask);
352 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
353 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
354 			      struct ctl_ooa *ooa_hdr);
355 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
356 		     struct thread *td);
357 uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
358 uint32_t ctl_port_idx(int port_num);
359 #ifdef unused
360 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
361 				   uint32_t targ_target, uint32_t targ_lun,
362 				   int can_wait);
363 static void ctl_kfree_io(union ctl_io *io);
364 #endif /* unused */
365 static void ctl_free_io_internal(union ctl_io *io, int have_lock);
366 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
367 			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
368 static int ctl_free_lun(struct ctl_lun *lun);
369 static void ctl_create_lun(struct ctl_be_lun *be_lun);
370 /**
371 static void ctl_failover_change_pages(struct ctl_softc *softc,
372 				      struct ctl_scsiio *ctsio, int master);
373 **/
374 
375 static int ctl_do_mode_select(union ctl_io *io);
376 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
377 			   uint64_t res_key, uint64_t sa_res_key,
378 			   uint8_t type, uint32_t residx,
379 			   struct ctl_scsiio *ctsio,
380 			   struct scsi_per_res_out *cdb,
381 			   struct scsi_per_res_out_parms* param);
382 static void ctl_pro_preempt_other(struct ctl_lun *lun,
383 				  union ctl_ha_msg *msg);
384 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
385 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
386 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
387 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
388 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
389 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
390 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
391 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
392 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
393 					 union ctl_io *ooa_io);
394 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
395 				union ctl_io *starting_io);
396 static int ctl_check_blocked(struct ctl_lun *lun);
397 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
398 				struct ctl_lun *lun,
399 				struct ctl_cmd_entry *entry,
400 				struct ctl_scsiio *ctsio);
401 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
402 static void ctl_failover(void);
403 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
404 			       struct ctl_scsiio *ctsio);
405 static int ctl_scsiio(struct ctl_scsiio *ctsio);
406 
407 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
408 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
409 			    ctl_ua_type ua_type);
410 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
411 			 ctl_ua_type ua_type);
412 static int ctl_abort_task(union ctl_io *io);
413 static void ctl_run_task_queue(struct ctl_softc *ctl_softc);
414 #ifdef CTL_IO_DELAY
415 static void ctl_datamove_timer_wakeup(void *arg);
416 static void ctl_done_timer_wakeup(void *arg);
417 #endif /* CTL_IO_DELAY */
418 
419 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
420 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
421 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
422 static void ctl_datamove_remote_write(union ctl_io *io);
423 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
424 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
425 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
426 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
427 				    ctl_ha_dt_cb callback);
428 static void ctl_datamove_remote_read(union ctl_io *io);
429 static void ctl_datamove_remote(union ctl_io *io);
430 static int ctl_process_done(union ctl_io *io, int have_lock);
431 static void ctl_work_thread(void *arg);
432 
433 /*
434  * Load the serialization table.  This isn't very pretty, but is probably
435  * the easiest way to do it.
436  */
437 #include "ctl_ser_table.c"
438 
439 /*
440  * We only need to define open, close and ioctl routines for this driver.
441  */
442 static struct cdevsw ctl_cdevsw = {
443 	.d_version =	D_VERSION,
444 	.d_flags =	0,
445 	.d_open =	ctl_open,
446 	.d_close =	ctl_close,
447 	.d_ioctl =	ctl_ioctl,
448 	.d_name =	"ctl",
449 };
450 
451 
452 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
453 
454 /*
455  * If we have the CAM SIM, we may or may not have another SIM that will
456  * cause CTL to get initialized.  If not, we need to initialize it.
457  */
458 SYSINIT(ctl_init, SI_SUB_CONFIGURE, SI_ORDER_THIRD, ctl_init, NULL);
459 
460 static void
461 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
462 			    union ctl_ha_msg *msg_info)
463 {
464 	struct ctl_scsiio *ctsio;
465 
466 	if (msg_info->hdr.original_sc == NULL) {
467 		printf("%s: original_sc == NULL!\n", __func__);
468 		/* XXX KDM now what? */
469 		return;
470 	}
471 
472 	ctsio = &msg_info->hdr.original_sc->scsiio;
473 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
474 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
475 	ctsio->io_hdr.status = msg_info->hdr.status;
476 	ctsio->scsi_status = msg_info->scsi.scsi_status;
477 	ctsio->sense_len = msg_info->scsi.sense_len;
478 	ctsio->sense_residual = msg_info->scsi.sense_residual;
479 	ctsio->residual = msg_info->scsi.residual;
480 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
481 	       sizeof(ctsio->sense_data));
482 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
483 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));;
484 	STAILQ_INSERT_TAIL(&ctl_softc->isc_queue, &ctsio->io_hdr, links);
485 	ctl_wakeup_thread();
486 }
487 
488 static void
489 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
490 				union ctl_ha_msg *msg_info)
491 {
492 	struct ctl_scsiio *ctsio;
493 
494 	if (msg_info->hdr.serializing_sc == NULL) {
495 		printf("%s: serializing_sc == NULL!\n", __func__);
496 		/* XXX KDM now what? */
497 		return;
498 	}
499 
500 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
501 #if 0
502 	/*
503 	 * Attempt to catch the situation where an I/O has
504 	 * been freed, and we're using it again.
505 	 */
506 	if (ctsio->io_hdr.io_type == 0xff) {
507 		union ctl_io *tmp_io;
508 		tmp_io = (union ctl_io *)ctsio;
509 		printf("%s: %p use after free!\n", __func__,
510 		       ctsio);
511 		printf("%s: type %d msg %d cdb %x iptl: "
512 		       "%d:%d:%d:%d tag 0x%04x "
513 		       "flag %#x status %x\n",
514 			__func__,
515 			tmp_io->io_hdr.io_type,
516 			tmp_io->io_hdr.msg_type,
517 			tmp_io->scsiio.cdb[0],
518 			tmp_io->io_hdr.nexus.initid.id,
519 			tmp_io->io_hdr.nexus.targ_port,
520 			tmp_io->io_hdr.nexus.targ_target.id,
521 			tmp_io->io_hdr.nexus.targ_lun,
522 			(tmp_io->io_hdr.io_type ==
523 			CTL_IO_TASK) ?
524 			tmp_io->taskio.tag_num :
525 			tmp_io->scsiio.tag_num,
526 		        tmp_io->io_hdr.flags,
527 			tmp_io->io_hdr.status);
528 	}
529 #endif
530 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
531 	STAILQ_INSERT_TAIL(&ctl_softc->isc_queue, &ctsio->io_hdr, links);
532 	ctl_wakeup_thread();
533 }
534 
535 /*
536  * ISC (Inter Shelf Communication) event handler.  Events from the HA
537  * subsystem come in here.
538  */
539 static void
540 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
541 {
542 	struct ctl_softc *ctl_softc;
543 	union ctl_io *io;
544 	struct ctl_prio *presio;
545 	ctl_ha_status isc_status;
546 
547 	ctl_softc = control_softc;
548 	io = NULL;
549 
550 
551 #if 0
552 	printf("CTL: Isc Msg event %d\n", event);
553 #endif
554 	if (event == CTL_HA_EVT_MSG_RECV) {
555 		union ctl_ha_msg msg_info;
556 
557 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
558 					     sizeof(msg_info), /*wait*/ 0);
559 #if 0
560 		printf("CTL: msg_type %d\n", msg_info.msg_type);
561 #endif
562 		if (isc_status != 0) {
563 			printf("Error receiving message, status = %d\n",
564 			       isc_status);
565 			return;
566 		}
567 		mtx_lock(&ctl_softc->ctl_lock);
568 
569 		switch (msg_info.hdr.msg_type) {
570 		case CTL_MSG_SERIALIZE:
571 #if 0
572 			printf("Serialize\n");
573 #endif
574 			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
575 			if (io == NULL) {
576 				printf("ctl_isc_event_handler: can't allocate "
577 				       "ctl_io!\n");
578 				/* Bad Juju */
579 				/* Need to set busy and send msg back */
580 				mtx_unlock(&ctl_softc->ctl_lock);
581 				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
582 				msg_info.hdr.status = CTL_SCSI_ERROR;
583 				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
584 				msg_info.scsi.sense_len = 0;
585 			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
586 				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
587 				}
588 				goto bailout;
589 			}
590 			ctl_zero_io(io);
591 			// populate ctsio from msg_info
592 			io->io_hdr.io_type = CTL_IO_SCSI;
593 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
594 			io->io_hdr.original_sc = msg_info.hdr.original_sc;
595 #if 0
596 			printf("pOrig %x\n", (int)msg_info.original_sc);
597 #endif
598 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
599 					    CTL_FLAG_IO_ACTIVE;
600 			/*
601 			 * If we're in serialization-only mode, we don't
602 			 * want to go through full done processing.  Thus
603 			 * the COPY flag.
604 			 *
605 			 * XXX KDM add another flag that is more specific.
606 			 */
607 			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
608 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
609 			io->io_hdr.nexus = msg_info.hdr.nexus;
610 #if 0
611 			printf("targ %d, port %d, iid %d, lun %d\n",
612 			       io->io_hdr.nexus.targ_target.id,
613 			       io->io_hdr.nexus.targ_port,
614 			       io->io_hdr.nexus.initid.id,
615 			       io->io_hdr.nexus.targ_lun);
616 #endif
617 			io->scsiio.tag_num = msg_info.scsi.tag_num;
618 			io->scsiio.tag_type = msg_info.scsi.tag_type;
619 			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
620 			       CTL_MAX_CDBLEN);
621 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
622 				struct ctl_cmd_entry *entry;
623 				uint8_t opcode;
624 
625 				opcode = io->scsiio.cdb[0];
626 				entry = &ctl_cmd_table[opcode];
627 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
628 				io->io_hdr.flags |=
629 					entry->flags & CTL_FLAG_DATA_MASK;
630 			}
631 			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
632 					   &io->io_hdr, links);
633 			ctl_wakeup_thread();
634 			break;
635 
636 		/* Performed on the Originating SC, XFER mode only */
637 		case CTL_MSG_DATAMOVE: {
638 			struct ctl_sg_entry *sgl;
639 			int i, j;
640 
641 			io = msg_info.hdr.original_sc;
642 			if (io == NULL) {
643 				printf("%s: original_sc == NULL!\n", __func__);
644 				/* XXX KDM do something here */
645 				break;
646 			}
647 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
648 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
649 			/*
650 			 * Keep track of this, we need to send it back over
651 			 * when the datamove is complete.
652 			 */
653 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
654 
655 			if (msg_info.dt.sg_sequence == 0) {
656 				/*
657 				 * XXX KDM we use the preallocated S/G list
658 				 * here, but we'll need to change this to
659 				 * dynamic allocation if we need larger S/G
660 				 * lists.
661 				 */
662 				if (msg_info.dt.kern_sg_entries >
663 				    sizeof(io->io_hdr.remote_sglist) /
664 				    sizeof(io->io_hdr.remote_sglist[0])) {
665 					printf("%s: number of S/G entries "
666 					    "needed %u > allocated num %zd\n",
667 					    __func__,
668 					    msg_info.dt.kern_sg_entries,
669 					    sizeof(io->io_hdr.remote_sglist)/
670 					    sizeof(io->io_hdr.remote_sglist[0]));
671 
672 					/*
673 					 * XXX KDM send a message back to
674 					 * the other side to shut down the
675 					 * DMA.  The error will come back
676 					 * through via the normal channel.
677 					 */
678 					break;
679 				}
680 				sgl = io->io_hdr.remote_sglist;
681 				memset(sgl, 0,
682 				       sizeof(io->io_hdr.remote_sglist));
683 
684 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
685 
686 				io->scsiio.kern_sg_entries =
687 					msg_info.dt.kern_sg_entries;
688 				io->scsiio.rem_sg_entries =
689 					msg_info.dt.kern_sg_entries;
690 				io->scsiio.kern_data_len =
691 					msg_info.dt.kern_data_len;
692 				io->scsiio.kern_total_len =
693 					msg_info.dt.kern_total_len;
694 				io->scsiio.kern_data_resid =
695 					msg_info.dt.kern_data_resid;
696 				io->scsiio.kern_rel_offset =
697 					msg_info.dt.kern_rel_offset;
698 				/*
699 				 * Clear out per-DMA flags.
700 				 */
701 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
702 				/*
703 				 * Add per-DMA flags that are set for this
704 				 * particular DMA request.
705 				 */
706 				io->io_hdr.flags |= msg_info.dt.flags &
707 						    CTL_FLAG_RDMA_MASK;
708 			} else
709 				sgl = (struct ctl_sg_entry *)
710 					io->scsiio.kern_data_ptr;
711 
712 			for (i = msg_info.dt.sent_sg_entries, j = 0;
713 			     i < (msg_info.dt.sent_sg_entries +
714 			     msg_info.dt.cur_sg_entries); i++, j++) {
715 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
716 				sgl[i].len = msg_info.dt.sg_list[j].len;
717 
718 #if 0
719 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
720 				       __func__,
721 				       msg_info.dt.sg_list[j].addr,
722 				       msg_info.dt.sg_list[j].len,
723 				       sgl[i].addr, sgl[i].len, j, i);
724 #endif
725 			}
726 #if 0
727 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
728 			       msg_info.dt.sg_list,
729 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
730 #endif
731 
732 			/*
733 			 * If this is the last piece of the I/O, we've got
734 			 * the full S/G list.  Queue processing in the thread.
735 			 * Otherwise wait for the next piece.
736 			 */
737 			if (msg_info.dt.sg_last != 0) {
738 				STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
739 						   &io->io_hdr, links);
740 				ctl_wakeup_thread();
741 			}
742 			break;
743 		}
744 		/* Performed on the Serializing (primary) SC, XFER mode only */
745 		case CTL_MSG_DATAMOVE_DONE: {
746 			if (msg_info.hdr.serializing_sc == NULL) {
747 				printf("%s: serializing_sc == NULL!\n",
748 				       __func__);
749 				/* XXX KDM now what? */
750 				break;
751 			}
752 			/*
753 			 * We grab the sense information here in case
754 			 * there was a failure, so we can return status
755 			 * back to the initiator.
756 			 */
757 			io = msg_info.hdr.serializing_sc;
758 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
759 			io->io_hdr.status = msg_info.hdr.status;
760 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
761 			io->scsiio.sense_len = msg_info.scsi.sense_len;
762 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
763 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
764 			io->scsiio.residual = msg_info.scsi.residual;
765 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
766 			       sizeof(io->scsiio.sense_data));
767 
768 			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
769 					   &io->io_hdr, links);
770 			ctl_wakeup_thread();
771 			break;
772 		}
773 
774 		/* Preformed on Originating SC, SER_ONLY mode */
775 		case CTL_MSG_R2R:
776 			io = msg_info.hdr.original_sc;
777 			if (io == NULL) {
778 				printf("%s: Major Bummer\n", __func__);
779 				mtx_unlock(&ctl_softc->ctl_lock);
780 				return;
781 			} else {
782 #if 0
783 				printf("pOrig %x\n",(int) ctsio);
784 #endif
785 			}
786 			io->io_hdr.msg_type = CTL_MSG_R2R;
787 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
788 			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
789 					   &io->io_hdr, links);
790 			ctl_wakeup_thread();
791 			break;
792 
793 		/*
794 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
795 		 * mode.
796 		 * Performed on the Originating (i.e. secondary) SC in XFER
797 		 * mode
798 		 */
799 		case CTL_MSG_FINISH_IO:
800 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
801 				ctl_isc_handler_finish_xfer(ctl_softc,
802 							    &msg_info);
803 			else
804 				ctl_isc_handler_finish_ser_only(ctl_softc,
805 								&msg_info);
806 			break;
807 
808 		/* Preformed on Originating SC */
809 		case CTL_MSG_BAD_JUJU:
810 			io = msg_info.hdr.original_sc;
811 			if (io == NULL) {
812 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
813 				       __func__);
814 				break;
815 			}
816 			ctl_copy_sense_data(&msg_info, io);
817 			/*
818 			 * IO should have already been cleaned up on other
819 			 * SC so clear this flag so we won't send a message
820 			 * back to finish the IO there.
821 			 */
822 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
823 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
824 
825 			/* io = msg_info.hdr.serializing_sc; */
826 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
827 		        STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
828 					   &io->io_hdr, links);
829 			ctl_wakeup_thread();
830 			break;
831 
832 		/* Handle resets sent from the other side */
833 		case CTL_MSG_MANAGE_TASKS: {
834 			struct ctl_taskio *taskio;
835 			taskio = (struct ctl_taskio *)ctl_alloc_io(
836 				(void *)ctl_softc->othersc_pool);
837 			if (taskio == NULL) {
838 				printf("ctl_isc_event_handler: can't allocate "
839 				       "ctl_io!\n");
840 				/* Bad Juju */
841 				/* should I just call the proper reset func
842 				   here??? */
843 				mtx_unlock(&ctl_softc->ctl_lock);
844 				goto bailout;
845 			}
846 			ctl_zero_io((union ctl_io *)taskio);
847 			taskio->io_hdr.io_type = CTL_IO_TASK;
848 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
849 			taskio->io_hdr.nexus = msg_info.hdr.nexus;
850 			taskio->task_action = msg_info.task.task_action;
851 			taskio->tag_num = msg_info.task.tag_num;
852 			taskio->tag_type = msg_info.task.tag_type;
853 #ifdef CTL_TIME_IO
854 			taskio->io_hdr.start_time = time_uptime;
855 			getbintime(&taskio->io_hdr.start_bt);
856 #if 0
857 			cs_prof_gettime(&taskio->io_hdr.start_ticks);
858 #endif
859 #endif /* CTL_TIME_IO */
860 		        STAILQ_INSERT_TAIL(&ctl_softc->task_queue,
861 					   &taskio->io_hdr, links);
862 			ctl_softc->flags |= CTL_FLAG_TASK_PENDING;
863 			ctl_wakeup_thread();
864 			break;
865 		}
866 		/* Persistent Reserve action which needs attention */
867 		case CTL_MSG_PERS_ACTION:
868 			presio = (struct ctl_prio *)ctl_alloc_io(
869 				(void *)ctl_softc->othersc_pool);
870 			if (presio == NULL) {
871 				printf("ctl_isc_event_handler: can't allocate "
872 				       "ctl_io!\n");
873 				/* Bad Juju */
874 				/* Need to set busy and send msg back */
875 				mtx_unlock(&ctl_softc->ctl_lock);
876 				goto bailout;
877 			}
878 			ctl_zero_io((union ctl_io *)presio);
879 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
880 			presio->pr_msg = msg_info.pr;
881 		        STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
882 					   &presio->io_hdr, links);
883 			ctl_wakeup_thread();
884 			break;
885 		case CTL_MSG_SYNC_FE:
886 			rcv_sync_msg = 1;
887 			break;
888 		case CTL_MSG_APS_LOCK: {
889 			// It's quicker to execute this then to
890 			// queue it.
891 			struct ctl_lun *lun;
892 			struct ctl_page_index *page_index;
893 			struct copan_aps_subpage *current_sp;
894 
895 			lun = ctl_softc->ctl_luns[msg_info.hdr.nexus.targ_lun];
896 			page_index = &lun->mode_pages.index[index_to_aps_page];
897 			current_sp = (struct copan_aps_subpage *)
898 				     (page_index->page_data +
899 				     (page_index->page_len * CTL_PAGE_CURRENT));
900 
901 			current_sp->lock_active = msg_info.aps.lock_flag;
902 		        break;
903 		}
904 		default:
905 		        printf("How did I get here?\n");
906 		}
907 		mtx_unlock(&ctl_softc->ctl_lock);
908 	} else if (event == CTL_HA_EVT_MSG_SENT) {
909 		if (param != CTL_HA_STATUS_SUCCESS) {
910 			printf("Bad status from ctl_ha_msg_send status %d\n",
911 			       param);
912 		}
913 		return;
914 	} else if (event == CTL_HA_EVT_DISCONNECT) {
915 		printf("CTL: Got a disconnect from Isc\n");
916 		return;
917 	} else {
918 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
919 		return;
920 	}
921 
922 bailout:
923 	return;
924 }
925 
926 static void
927 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
928 {
929 	struct scsi_sense_data *sense;
930 
931 	sense = &dest->scsiio.sense_data;
932 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
933 	dest->scsiio.scsi_status = src->scsi.scsi_status;
934 	dest->scsiio.sense_len = src->scsi.sense_len;
935 	dest->io_hdr.status = src->hdr.status;
936 }
937 
938 static void
939 ctl_init(void)
940 {
941 	struct ctl_softc *softc;
942 	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
943 	struct ctl_frontend *fe;
944 	struct ctl_lun *lun;
945         uint8_t sc_id =0;
946 #if 0
947 	int i;
948 #endif
949 	int retval;
950 	//int isc_retval;
951 
952 	retval = 0;
953 	ctl_pause_rtr = 0;
954         rcv_sync_msg = 0;
955 
956 	/* If we're disabled, don't initialize. */
957 	if (ctl_disable != 0)
958 		return;
959 
960 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF, M_WAITOK);
961 	softc = control_softc;
962 
963 	memset(softc, 0, sizeof(*softc));
964 
965 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
966 			      "cam/ctl");
967 
968 	softc->dev->si_drv1 = softc;
969 
970 	/*
971 	 * By default, return a "bad LUN" peripheral qualifier for unknown
972 	 * LUNs.  The user can override this default using the tunable or
973 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
974 	 */
975 	softc->inquiry_pq_no_lun = 1;
976 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
977 			  &softc->inquiry_pq_no_lun);
978 	sysctl_ctx_init(&softc->sysctl_ctx);
979 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
980 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
981 		CTLFLAG_RD, 0, "CAM Target Layer");
982 
983 	if (softc->sysctl_tree == NULL) {
984 		printf("%s: unable to allocate sysctl tree\n", __func__);
985 		destroy_dev(softc->dev);
986 		free(control_softc, M_DEVBUF);
987 		control_softc = NULL;
988 		return;
989 	}
990 
991 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
992 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
993 		       "inquiry_pq_no_lun", CTLFLAG_RW,
994 		       &softc->inquiry_pq_no_lun, 0,
995 		       "Report no lun possible for invalid LUNs");
996 
997 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
998 	softc->open_count = 0;
999 
1000 	/*
1001 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1002 	 * the drive.
1003 	 */
1004 	softc->flags = CTL_FLAG_REAL_SYNC;
1005 
1006 	/*
1007 	 * In Copan's HA scheme, the "master" and "slave" roles are
1008 	 * figured out through the slot the controller is in.  Although it
1009 	 * is an active/active system, someone has to be in charge.
1010  	 */
1011 #ifdef NEEDTOPORT
1012         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1013 #endif
1014 
1015         if (sc_id == 0) {
1016 		softc->flags |= CTL_FLAG_MASTER_SHELF;
1017 		persis_offset = 0;
1018 	} else
1019 		persis_offset = CTL_MAX_INITIATORS;
1020 
1021 	/*
1022 	 * XXX KDM need to figure out where we want to get our target ID
1023 	 * and WWID.  Is it different on each port?
1024 	 */
1025 	softc->target.id = 0;
1026 	softc->target.wwid[0] = 0x12345678;
1027 	softc->target.wwid[1] = 0x87654321;
1028 	STAILQ_INIT(&softc->lun_list);
1029 	STAILQ_INIT(&softc->pending_lun_queue);
1030 	STAILQ_INIT(&softc->task_queue);
1031 	STAILQ_INIT(&softc->incoming_queue);
1032 	STAILQ_INIT(&softc->rtr_queue);
1033 	STAILQ_INIT(&softc->done_queue);
1034 	STAILQ_INIT(&softc->isc_queue);
1035 	STAILQ_INIT(&softc->fe_list);
1036 	STAILQ_INIT(&softc->be_list);
1037 	STAILQ_INIT(&softc->io_pools);
1038 
1039 	lun = &softc->lun;
1040 
1041 	/*
1042 	 * We don't bother calling these with ctl_lock held here, because,
1043 	 * in theory, no one else can try to do anything while we're in our
1044 	 * module init routine.
1045 	 */
1046 	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1047 			    &internal_pool)!= 0){
1048 		printf("ctl: can't allocate %d entry internal pool, "
1049 		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1050 		return;
1051 	}
1052 
1053 	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1054 			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1055 		printf("ctl: can't allocate %d entry emergency pool, "
1056 		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1057 		ctl_pool_free(softc, internal_pool);
1058 		return;
1059 	}
1060 
1061 	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1062 	                    &other_pool) != 0)
1063 	{
1064 		printf("ctl: can't allocate %d entry other SC pool, "
1065 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1066 		ctl_pool_free(softc, internal_pool);
1067 		ctl_pool_free(softc, emergency_pool);
1068 		return;
1069 	}
1070 
1071 	softc->internal_pool = internal_pool;
1072 	softc->emergency_pool = emergency_pool;
1073 	softc->othersc_pool = other_pool;
1074 
1075 	ctl_pool_acquire(internal_pool);
1076 	ctl_pool_acquire(emergency_pool);
1077 	ctl_pool_acquire(other_pool);
1078 
1079 	/*
1080 	 * We used to allocate a processor LUN here.  The new scheme is to
1081 	 * just let the user allocate LUNs as he sees fit.
1082 	 */
1083 #if 0
1084 	mtx_lock(&softc->ctl_lock);
1085 	ctl_alloc_lun(softc, lun, /*be_lun*/NULL, /*target*/softc->target);
1086 	mtx_unlock(&softc->ctl_lock);
1087 #endif
1088 
1089 	if (kproc_create(ctl_work_thread, softc, &softc->work_thread, 0, 0,
1090 			 "ctl_thrd") != 0) {
1091 		printf("error creating CTL work thread!\n");
1092 		ctl_free_lun(lun);
1093 		ctl_pool_free(softc, internal_pool);
1094 		ctl_pool_free(softc, emergency_pool);
1095 		ctl_pool_free(softc, other_pool);
1096 		return;
1097 	}
1098 	printf("ctl: CAM Target Layer loaded\n");
1099 
1100 	/*
1101 	 * Initialize the initiator and portname mappings
1102 	 */
1103 	memset(softc->wwpn_iid, 0, sizeof(softc->wwpn_iid));
1104 
1105 	/*
1106 	 * Initialize the ioctl front end.
1107 	 */
1108 	fe = &softc->ioctl_info.fe;
1109 	sprintf(softc->ioctl_info.port_name, "CTL ioctl");
1110 	fe->port_type = CTL_PORT_IOCTL;
1111 	fe->num_requested_ctl_io = 100;
1112 	fe->port_name = softc->ioctl_info.port_name;
1113 	fe->port_online = ctl_ioctl_online;
1114 	fe->port_offline = ctl_ioctl_offline;
1115 	fe->onoff_arg = &softc->ioctl_info;
1116 	fe->targ_enable = ctl_ioctl_targ_enable;
1117 	fe->targ_disable = ctl_ioctl_targ_disable;
1118 	fe->lun_enable = ctl_ioctl_lun_enable;
1119 	fe->lun_disable = ctl_ioctl_lun_disable;
1120 	fe->targ_lun_arg = &softc->ioctl_info;
1121 	fe->fe_datamove = ctl_ioctl_datamove;
1122 	fe->fe_done = ctl_ioctl_done;
1123 	fe->max_targets = 15;
1124 	fe->max_target_id = 15;
1125 
1126 	if (ctl_frontend_register(&softc->ioctl_info.fe,
1127 	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1128 		printf("ctl: ioctl front end registration failed, will "
1129 		       "continue anyway\n");
1130 	}
1131 
1132 #ifdef CTL_IO_DELAY
1133 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1134 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1135 		       sizeof(struct callout), CTL_TIMER_BYTES);
1136 		return;
1137 	}
1138 #endif /* CTL_IO_DELAY */
1139 
1140 }
1141 
1142 void
1143 ctl_shutdown(void)
1144 {
1145 	struct ctl_softc *softc;
1146 	struct ctl_lun *lun, *next_lun;
1147 	struct ctl_io_pool *pool, *next_pool;
1148 
1149 	softc = (struct ctl_softc *)control_softc;
1150 
1151 	if (ctl_frontend_deregister(&softc->ioctl_info.fe) != 0)
1152 		printf("ctl: ioctl front end deregistration failed\n");
1153 
1154 	mtx_lock(&softc->ctl_lock);
1155 
1156 	/*
1157 	 * Free up each LUN.
1158 	 */
1159 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1160 		next_lun = STAILQ_NEXT(lun, links);
1161 		ctl_free_lun(lun);
1162 	}
1163 
1164 	/*
1165 	 * This will rip the rug out from under any FETDs or anyone else
1166 	 * that has a pool allocated.  Since we increment our module
1167 	 * refcount any time someone outside the main CTL module allocates
1168 	 * a pool, we shouldn't have any problems here.  The user won't be
1169 	 * able to unload the CTL module until client modules have
1170 	 * successfully unloaded.
1171 	 */
1172 	for (pool = STAILQ_FIRST(&softc->io_pools); pool != NULL;
1173 	     pool = next_pool) {
1174 		next_pool = STAILQ_NEXT(pool, links);
1175 		ctl_pool_free(softc, pool);
1176 	}
1177 
1178 	mtx_unlock(&softc->ctl_lock);
1179 
1180 #if 0
1181 	ctl_shutdown_thread(softc->work_thread);
1182 #endif
1183 
1184 	mtx_destroy(&softc->ctl_lock);
1185 
1186 	destroy_dev(softc->dev);
1187 
1188 	sysctl_ctx_free(&softc->sysctl_ctx);
1189 
1190 	free(control_softc, M_DEVBUF);
1191 	control_softc = NULL;
1192 
1193 	printf("ctl: CAM Target Layer unloaded\n");
1194 }
1195 
1196 /*
1197  * XXX KDM should we do some access checks here?  Bump a reference count to
1198  * prevent a CTL module from being unloaded while someone has it open?
1199  */
1200 static int
1201 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1202 {
1203 	return (0);
1204 }
1205 
1206 static int
1207 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1208 {
1209 	return (0);
1210 }
1211 
1212 int
1213 ctl_port_enable(ctl_port_type port_type)
1214 {
1215 	struct ctl_softc *softc;
1216 	struct ctl_frontend *fe;
1217 
1218 	if (ctl_is_single == 0) {
1219 		union ctl_ha_msg msg_info;
1220 		int isc_retval;
1221 
1222 #if 0
1223 		printf("%s: HA mode, synchronizing frontend enable\n",
1224 		        __func__);
1225 #endif
1226 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1227 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1228 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1229 			printf("Sync msg send error retval %d\n", isc_retval);
1230 		}
1231 		if (!rcv_sync_msg) {
1232 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1233 			        sizeof(msg_info), 1);
1234 		}
1235 #if 0
1236         	printf("CTL:Frontend Enable\n");
1237 	} else {
1238 		printf("%s: single mode, skipping frontend synchronization\n",
1239 		        __func__);
1240 #endif
1241 	}
1242 
1243 	softc = control_softc;
1244 
1245 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1246 		if (port_type & fe->port_type)
1247 		{
1248 #if 0
1249 			printf("port %d\n", fe->targ_port);
1250 #endif
1251 			ctl_frontend_online(fe);
1252 		}
1253 	}
1254 
1255 	return (0);
1256 }
1257 
1258 int
1259 ctl_port_disable(ctl_port_type port_type)
1260 {
1261 	struct ctl_softc *softc;
1262 	struct ctl_frontend *fe;
1263 
1264 	softc = control_softc;
1265 
1266 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1267 		if (port_type & fe->port_type)
1268 			ctl_frontend_offline(fe);
1269 	}
1270 
1271 	return (0);
1272 }
1273 
1274 /*
1275  * Returns 0 for success, 1 for failure.
1276  * Currently the only failure mode is if there aren't enough entries
1277  * allocated.  So, in case of a failure, look at num_entries_dropped,
1278  * reallocate and try again.
1279  */
1280 int
1281 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1282 	      int *num_entries_filled, int *num_entries_dropped,
1283 	      ctl_port_type port_type, int no_virtual)
1284 {
1285 	struct ctl_softc *softc;
1286 	struct ctl_frontend *fe;
1287 	int entries_dropped, entries_filled;
1288 	int retval;
1289 	int i;
1290 
1291 	softc = control_softc;
1292 
1293 	retval = 0;
1294 	entries_filled = 0;
1295 	entries_dropped = 0;
1296 
1297 	i = 0;
1298 	mtx_lock(&softc->ctl_lock);
1299 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1300 		struct ctl_port_entry *entry;
1301 
1302 		if ((fe->port_type & port_type) == 0)
1303 			continue;
1304 
1305 		if ((no_virtual != 0)
1306 		 && (fe->virtual_port != 0))
1307 			continue;
1308 
1309 		if (entries_filled >= num_entries_alloced) {
1310 			entries_dropped++;
1311 			continue;
1312 		}
1313 		entry = &entries[i];
1314 
1315 		entry->port_type = fe->port_type;
1316 		strlcpy(entry->port_name, fe->port_name,
1317 			sizeof(entry->port_name));
1318 		entry->physical_port = fe->physical_port;
1319 		entry->virtual_port = fe->virtual_port;
1320 		entry->wwnn = fe->wwnn;
1321 		entry->wwpn = fe->wwpn;
1322 
1323 		i++;
1324 		entries_filled++;
1325 	}
1326 
1327 	mtx_unlock(&softc->ctl_lock);
1328 
1329 	if (entries_dropped > 0)
1330 		retval = 1;
1331 
1332 	*num_entries_dropped = entries_dropped;
1333 	*num_entries_filled = entries_filled;
1334 
1335 	return (retval);
1336 }
1337 
1338 static void
1339 ctl_ioctl_online(void *arg)
1340 {
1341 	struct ctl_ioctl_info *ioctl_info;
1342 
1343 	ioctl_info = (struct ctl_ioctl_info *)arg;
1344 
1345 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1346 }
1347 
1348 static void
1349 ctl_ioctl_offline(void *arg)
1350 {
1351 	struct ctl_ioctl_info *ioctl_info;
1352 
1353 	ioctl_info = (struct ctl_ioctl_info *)arg;
1354 
1355 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1356 }
1357 
1358 /*
1359  * Remove an initiator by port number and initiator ID.
1360  * Returns 0 for success, 1 for failure.
1361  * Assumes the caller does NOT hold the CTL lock.
1362  */
1363 int
1364 ctl_remove_initiator(int32_t targ_port, uint32_t iid)
1365 {
1366 	struct ctl_softc *softc;
1367 
1368 	softc = control_softc;
1369 
1370 	if ((targ_port < 0)
1371 	 || (targ_port > CTL_MAX_PORTS)) {
1372 		printf("%s: invalid port number %d\n", __func__, targ_port);
1373 		return (1);
1374 	}
1375 	if (iid > CTL_MAX_INIT_PER_PORT) {
1376 		printf("%s: initiator ID %u > maximun %u!\n",
1377 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1378 		return (1);
1379 	}
1380 
1381 	mtx_lock(&softc->ctl_lock);
1382 
1383 	softc->wwpn_iid[targ_port][iid].in_use = 0;
1384 
1385 	mtx_unlock(&softc->ctl_lock);
1386 
1387 	return (0);
1388 }
1389 
1390 /*
1391  * Add an initiator to the initiator map.
1392  * Returns 0 for success, 1 for failure.
1393  * Assumes the caller does NOT hold the CTL lock.
1394  */
1395 int
1396 ctl_add_initiator(uint64_t wwpn, int32_t targ_port, uint32_t iid)
1397 {
1398 	struct ctl_softc *softc;
1399 	int retval;
1400 
1401 	softc = control_softc;
1402 
1403 	retval = 0;
1404 
1405 	if ((targ_port < 0)
1406 	 || (targ_port > CTL_MAX_PORTS)) {
1407 		printf("%s: invalid port number %d\n", __func__, targ_port);
1408 		return (1);
1409 	}
1410 	if (iid > CTL_MAX_INIT_PER_PORT) {
1411 		printf("%s: WWPN %#jx initiator ID %u > maximun %u!\n",
1412 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1413 		return (1);
1414 	}
1415 
1416 	mtx_lock(&softc->ctl_lock);
1417 
1418 	if (softc->wwpn_iid[targ_port][iid].in_use != 0) {
1419 		/*
1420 		 * We don't treat this as an error.
1421 		 */
1422 		if (softc->wwpn_iid[targ_port][iid].wwpn == wwpn) {
1423 			printf("%s: port %d iid %u WWPN %#jx arrived again?\n",
1424 			       __func__, targ_port, iid, (uintmax_t)wwpn);
1425 			goto bailout;
1426 		}
1427 
1428 		/*
1429 		 * This is an error, but what do we do about it?  The
1430 		 * driver is telling us we have a new WWPN for this
1431 		 * initiator ID, so we pretty much need to use it.
1432 		 */
1433 		printf("%s: port %d iid %u WWPN %#jx arrived, WWPN %#jx is "
1434 		       "still at that address\n", __func__, targ_port, iid,
1435 		       (uintmax_t)wwpn,
1436 		       (uintmax_t)softc->wwpn_iid[targ_port][iid].wwpn);
1437 
1438 		/*
1439 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1440 		 * this initiator.
1441 		 */
1442 	}
1443 	softc->wwpn_iid[targ_port][iid].in_use = 1;
1444 	softc->wwpn_iid[targ_port][iid].iid = iid;
1445 	softc->wwpn_iid[targ_port][iid].wwpn = wwpn;
1446 	softc->wwpn_iid[targ_port][iid].port = targ_port;
1447 
1448 bailout:
1449 
1450 	mtx_unlock(&softc->ctl_lock);
1451 
1452 	return (retval);
1453 }
1454 
1455 /*
1456  * XXX KDM should we pretend to do something in the target/lun
1457  * enable/disable functions?
1458  */
1459 static int
1460 ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id)
1461 {
1462 	return (0);
1463 }
1464 
1465 static int
1466 ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id)
1467 {
1468 	return (0);
1469 }
1470 
1471 static int
1472 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1473 {
1474 	return (0);
1475 }
1476 
1477 static int
1478 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1479 {
1480 	return (0);
1481 }
1482 
1483 /*
1484  * Data movement routine for the CTL ioctl frontend port.
1485  */
1486 static int
1487 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1488 {
1489 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1490 	struct ctl_sg_entry ext_entry, kern_entry;
1491 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1492 	int ext_sg_start, ext_offset;
1493 	int len_to_copy, len_copied;
1494 	int kern_watermark, ext_watermark;
1495 	int ext_sglist_malloced;
1496 	int i, j;
1497 
1498 	ext_sglist_malloced = 0;
1499 	ext_sg_start = 0;
1500 	ext_offset = 0;
1501 
1502 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1503 
1504 	/*
1505 	 * If this flag is set, fake the data transfer.
1506 	 */
1507 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1508 		ctsio->ext_data_filled = ctsio->ext_data_len;
1509 		goto bailout;
1510 	}
1511 
1512 	/*
1513 	 * To simplify things here, if we have a single buffer, stick it in
1514 	 * a S/G entry and just make it a single entry S/G list.
1515 	 */
1516 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1517 		int len_seen;
1518 
1519 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1520 
1521 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1522 							   M_WAITOK);
1523 		if (ext_sglist == NULL) {
1524 			ctl_set_internal_failure(ctsio,
1525 						 /*sks_valid*/ 0,
1526 						 /*retry_count*/ 0);
1527 			return (CTL_RETVAL_COMPLETE);
1528 		}
1529 		ext_sglist_malloced = 1;
1530 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1531 				   ext_sglen) != 0) {
1532 			ctl_set_internal_failure(ctsio,
1533 						 /*sks_valid*/ 0,
1534 						 /*retry_count*/ 0);
1535 			goto bailout;
1536 		}
1537 		ext_sg_entries = ctsio->ext_sg_entries;
1538 		len_seen = 0;
1539 		for (i = 0; i < ext_sg_entries; i++) {
1540 			if ((len_seen + ext_sglist[i].len) >=
1541 			     ctsio->ext_data_filled) {
1542 				ext_sg_start = i;
1543 				ext_offset = ctsio->ext_data_filled - len_seen;
1544 				break;
1545 			}
1546 			len_seen += ext_sglist[i].len;
1547 		}
1548 	} else {
1549 		ext_sglist = &ext_entry;
1550 		ext_sglist->addr = ctsio->ext_data_ptr;
1551 		ext_sglist->len = ctsio->ext_data_len;
1552 		ext_sg_entries = 1;
1553 		ext_sg_start = 0;
1554 		ext_offset = ctsio->ext_data_filled;
1555 	}
1556 
1557 	if (ctsio->kern_sg_entries > 0) {
1558 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1559 		kern_sg_entries = ctsio->kern_sg_entries;
1560 	} else {
1561 		kern_sglist = &kern_entry;
1562 		kern_sglist->addr = ctsio->kern_data_ptr;
1563 		kern_sglist->len = ctsio->kern_data_len;
1564 		kern_sg_entries = 1;
1565 	}
1566 
1567 
1568 	kern_watermark = 0;
1569 	ext_watermark = ext_offset;
1570 	len_copied = 0;
1571 	for (i = ext_sg_start, j = 0;
1572 	     i < ext_sg_entries && j < kern_sg_entries;) {
1573 		uint8_t *ext_ptr, *kern_ptr;
1574 
1575 		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1576 				      kern_sglist[j].len - kern_watermark);
1577 
1578 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1579 		ext_ptr = ext_ptr + ext_watermark;
1580 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1581 			/*
1582 			 * XXX KDM fix this!
1583 			 */
1584 			panic("need to implement bus address support");
1585 #if 0
1586 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1587 #endif
1588 		} else
1589 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1590 		kern_ptr = kern_ptr + kern_watermark;
1591 
1592 		kern_watermark += len_to_copy;
1593 		ext_watermark += len_to_copy;
1594 
1595 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1596 		     CTL_FLAG_DATA_IN) {
1597 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1598 					 "bytes to user\n", len_to_copy));
1599 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1600 					 "to %p\n", kern_ptr, ext_ptr));
1601 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1602 				ctl_set_internal_failure(ctsio,
1603 							 /*sks_valid*/ 0,
1604 							 /*retry_count*/ 0);
1605 				goto bailout;
1606 			}
1607 		} else {
1608 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1609 					 "bytes from user\n", len_to_copy));
1610 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1611 					 "to %p\n", ext_ptr, kern_ptr));
1612 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1613 				ctl_set_internal_failure(ctsio,
1614 							 /*sks_valid*/ 0,
1615 							 /*retry_count*/0);
1616 				goto bailout;
1617 			}
1618 		}
1619 
1620 		len_copied += len_to_copy;
1621 
1622 		if (ext_sglist[i].len == ext_watermark) {
1623 			i++;
1624 			ext_watermark = 0;
1625 		}
1626 
1627 		if (kern_sglist[j].len == kern_watermark) {
1628 			j++;
1629 			kern_watermark = 0;
1630 		}
1631 	}
1632 
1633 	ctsio->ext_data_filled += len_copied;
1634 
1635 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1636 			 "kern_sg_entries: %d\n", ext_sg_entries,
1637 			 kern_sg_entries));
1638 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1639 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1640 			 ctsio->kern_data_len));
1641 
1642 
1643 	/* XXX KDM set residual?? */
1644 bailout:
1645 
1646 	if (ext_sglist_malloced != 0)
1647 		free(ext_sglist, M_CTL);
1648 
1649 	return (CTL_RETVAL_COMPLETE);
1650 }
1651 
1652 /*
1653  * Serialize a command that went down the "wrong" side, and so was sent to
1654  * this controller for execution.  The logic is a little different than the
1655  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1656  * sent back to the other side, but in the success case, we execute the
1657  * command on this side (XFER mode) or tell the other side to execute it
1658  * (SER_ONLY mode).
1659  */
1660 static int
1661 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio, int have_lock)
1662 {
1663 	struct ctl_softc *ctl_softc;
1664 	union ctl_ha_msg msg_info;
1665 	struct ctl_lun *lun;
1666 	int retval = 0;
1667 
1668 	ctl_softc = control_softc;
1669 	if (have_lock == 0)
1670 		mtx_lock(&ctl_softc->ctl_lock);
1671 
1672 	lun = ctl_softc->ctl_luns[ctsio->io_hdr.nexus.targ_lun];
1673 	if (lun==NULL)
1674 	{
1675 		/*
1676 		 * Why isn't LUN defined? The other side wouldn't
1677 		 * send a cmd if the LUN is undefined.
1678 		 */
1679 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1680 
1681 		/* "Logical unit not supported" */
1682 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1683 				   lun,
1684 				   /*sense_format*/SSD_TYPE_NONE,
1685 				   /*current_error*/ 1,
1686 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1687 				   /*asc*/ 0x25,
1688 				   /*ascq*/ 0x00,
1689 				   SSD_ELEM_NONE);
1690 
1691 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1692 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1693 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1694 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1695 		msg_info.hdr.serializing_sc = NULL;
1696 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1697 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1698 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1699 		}
1700 		if (have_lock == 0)
1701 			mtx_unlock(&ctl_softc->ctl_lock);
1702 		return(1);
1703 
1704 	}
1705 
1706     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1707 
1708 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1709 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1710 		 ooa_links))) {
1711 	case CTL_ACTION_BLOCK:
1712 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1713 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1714 				  blocked_links);
1715 		break;
1716 	case CTL_ACTION_PASS:
1717 	case CTL_ACTION_SKIP:
1718 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1719 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1720 			STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
1721 					   &ctsio->io_hdr, links);
1722 		} else {
1723 
1724 			/* send msg back to other side */
1725 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1726 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1727 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1728 #if 0
1729 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1730 #endif
1731 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1732 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1733 			}
1734 		}
1735 		break;
1736 	case CTL_ACTION_OVERLAP:
1737 		/* OVERLAPPED COMMANDS ATTEMPTED */
1738 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1739 				   lun,
1740 				   /*sense_format*/SSD_TYPE_NONE,
1741 				   /*current_error*/ 1,
1742 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1743 				   /*asc*/ 0x4E,
1744 				   /*ascq*/ 0x00,
1745 				   SSD_ELEM_NONE);
1746 
1747 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1748 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1749 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1750 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1751 		msg_info.hdr.serializing_sc = NULL;
1752 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1753 #if 0
1754 		printf("BAD JUJU:Major Bummer Overlap\n");
1755 #endif
1756 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1757 		retval = 1;
1758 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1759 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1760 		}
1761 		break;
1762 	case CTL_ACTION_OVERLAP_TAG:
1763 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1764 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1765 				   lun,
1766 				   /*sense_format*/SSD_TYPE_NONE,
1767 				   /*current_error*/ 1,
1768 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1769 				   /*asc*/ 0x4D,
1770 				   /*ascq*/ ctsio->tag_num & 0xff,
1771 				   SSD_ELEM_NONE);
1772 
1773 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1774 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1775 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1776 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1777 		msg_info.hdr.serializing_sc = NULL;
1778 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1779 #if 0
1780 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1781 #endif
1782 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1783 		retval = 1;
1784 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1785 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1786 		}
1787 		break;
1788 	case CTL_ACTION_ERROR:
1789 	default:
1790 		/* "Internal target failure" */
1791 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1792 				   lun,
1793 				   /*sense_format*/SSD_TYPE_NONE,
1794 				   /*current_error*/ 1,
1795 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1796 				   /*asc*/ 0x44,
1797 				   /*ascq*/ 0x00,
1798 				   SSD_ELEM_NONE);
1799 
1800 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1801 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1802 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1803 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1804 		msg_info.hdr.serializing_sc = NULL;
1805 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1806 #if 0
1807 		printf("BAD JUJU:Major Bummer HW Error\n");
1808 #endif
1809 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1810 		retval = 1;
1811 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1812 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1813 		}
1814 		break;
1815 	}
1816 	if (have_lock == 0)
1817 		mtx_unlock(&ctl_softc->ctl_lock);
1818 	return (retval);
1819 }
1820 
1821 static int
1822 ctl_ioctl_submit_wait(union ctl_io *io)
1823 {
1824 	struct ctl_fe_ioctl_params params;
1825 	ctl_fe_ioctl_state last_state;
1826 	int done, retval;
1827 
1828 	retval = 0;
1829 
1830 	bzero(&params, sizeof(params));
1831 
1832 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1833 	cv_init(&params.sem, "ctlioccv");
1834 	params.state = CTL_IOCTL_INPROG;
1835 	last_state = params.state;
1836 
1837 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1838 
1839 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1840 
1841 	/* This shouldn't happen */
1842 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1843 		return (retval);
1844 
1845 	done = 0;
1846 
1847 	do {
1848 		mtx_lock(&params.ioctl_mtx);
1849 		/*
1850 		 * Check the state here, and don't sleep if the state has
1851 		 * already changed (i.e. wakeup has already occured, but we
1852 		 * weren't waiting yet).
1853 		 */
1854 		if (params.state == last_state) {
1855 			/* XXX KDM cv_wait_sig instead? */
1856 			cv_wait(&params.sem, &params.ioctl_mtx);
1857 		}
1858 		last_state = params.state;
1859 
1860 		switch (params.state) {
1861 		case CTL_IOCTL_INPROG:
1862 			/* Why did we wake up? */
1863 			/* XXX KDM error here? */
1864 			mtx_unlock(&params.ioctl_mtx);
1865 			break;
1866 		case CTL_IOCTL_DATAMOVE:
1867 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1868 
1869 			/*
1870 			 * change last_state back to INPROG to avoid
1871 			 * deadlock on subsequent data moves.
1872 			 */
1873 			params.state = last_state = CTL_IOCTL_INPROG;
1874 
1875 			mtx_unlock(&params.ioctl_mtx);
1876 			ctl_ioctl_do_datamove(&io->scsiio);
1877 			/*
1878 			 * Note that in some cases, most notably writes,
1879 			 * this will queue the I/O and call us back later.
1880 			 * In other cases, generally reads, this routine
1881 			 * will immediately call back and wake us up,
1882 			 * probably using our own context.
1883 			 */
1884 			io->scsiio.be_move_done(io);
1885 			break;
1886 		case CTL_IOCTL_DONE:
1887 			mtx_unlock(&params.ioctl_mtx);
1888 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1889 			done = 1;
1890 			break;
1891 		default:
1892 			mtx_unlock(&params.ioctl_mtx);
1893 			/* XXX KDM error here? */
1894 			break;
1895 		}
1896 	} while (done == 0);
1897 
1898 	mtx_destroy(&params.ioctl_mtx);
1899 	cv_destroy(&params.sem);
1900 
1901 	return (CTL_RETVAL_COMPLETE);
1902 }
1903 
1904 static void
1905 ctl_ioctl_datamove(union ctl_io *io)
1906 {
1907 	struct ctl_fe_ioctl_params *params;
1908 
1909 	params = (struct ctl_fe_ioctl_params *)
1910 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1911 
1912 	mtx_lock(&params->ioctl_mtx);
1913 	params->state = CTL_IOCTL_DATAMOVE;
1914 	cv_broadcast(&params->sem);
1915 	mtx_unlock(&params->ioctl_mtx);
1916 }
1917 
1918 static void
1919 ctl_ioctl_done(union ctl_io *io)
1920 {
1921 	struct ctl_fe_ioctl_params *params;
1922 
1923 	params = (struct ctl_fe_ioctl_params *)
1924 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1925 
1926 	mtx_lock(&params->ioctl_mtx);
1927 	params->state = CTL_IOCTL_DONE;
1928 	cv_broadcast(&params->sem);
1929 	mtx_unlock(&params->ioctl_mtx);
1930 }
1931 
1932 static void
1933 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
1934 {
1935 	struct ctl_fe_ioctl_startstop_info *sd_info;
1936 
1937 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
1938 
1939 	sd_info->hs_info.status = metatask->status;
1940 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
1941 	sd_info->hs_info.luns_complete =
1942 		metatask->taskinfo.startstop.luns_complete;
1943 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
1944 
1945 	cv_broadcast(&sd_info->sem);
1946 }
1947 
1948 static void
1949 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
1950 {
1951 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
1952 
1953 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
1954 
1955 	mtx_lock(fe_bbr_info->lock);
1956 	fe_bbr_info->bbr_info->status = metatask->status;
1957 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
1958 	fe_bbr_info->wakeup_done = 1;
1959 	mtx_unlock(fe_bbr_info->lock);
1960 
1961 	cv_broadcast(&fe_bbr_info->sem);
1962 }
1963 
1964 /*
1965  * Must be called with the ctl_lock held.
1966  * Returns 0 for success, errno for failure.
1967  */
1968 static int
1969 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1970 		   struct ctl_ooa *ooa_hdr)
1971 {
1972 	union ctl_io *io;
1973 	int retval;
1974 
1975 	retval = 0;
1976 
1977 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1978 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1979 	     ooa_links)) {
1980 		struct ctl_ooa_entry *cur_entry, entry;
1981 
1982 		/*
1983 		 * If we've got more than we can fit, just count the
1984 		 * remaining entries.
1985 		 */
1986 		if (*cur_fill_num >= ooa_hdr->alloc_num)
1987 			continue;
1988 
1989 		cur_entry = &ooa_hdr->entries[*cur_fill_num];
1990 
1991 		bzero(&entry, sizeof(entry));
1992 
1993 		entry.tag_num = io->scsiio.tag_num;
1994 		entry.lun_num = lun->lun;
1995 #ifdef CTL_TIME_IO
1996 		entry.start_bt = io->io_hdr.start_bt;
1997 #endif
1998 		bcopy(io->scsiio.cdb, entry.cdb, io->scsiio.cdb_len);
1999 		entry.cdb_len = io->scsiio.cdb_len;
2000 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2001 			entry.cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2002 
2003 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2004 			entry.cmd_flags |= CTL_OOACMD_FLAG_DMA;
2005 
2006 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2007 			entry.cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2008 
2009 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2010 			entry.cmd_flags |= CTL_OOACMD_FLAG_RTR;
2011 
2012 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2013 			entry.cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2014 
2015 		retval = copyout(&entry, cur_entry, sizeof(entry));
2016 
2017 		if (retval != 0)
2018 			break;
2019 	}
2020 
2021 	return (retval);
2022 }
2023 
2024 static void *
2025 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2026 		 size_t error_str_len)
2027 {
2028 	void *kptr;
2029 
2030 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2031 	if (kptr == NULL) {
2032 		snprintf(error_str, error_str_len, "Cannot allocate %d bytes",
2033 			 len);
2034 		return (NULL);
2035 	}
2036 
2037 	if (copyin(user_addr, kptr, len) != 0) {
2038 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2039 			 "from user address %p to kernel address %p", len,
2040 			 user_addr, kptr);
2041 		free(kptr, M_CTL);
2042 		return (NULL);
2043 	}
2044 
2045 	return (kptr);
2046 }
2047 
2048 static void
2049 ctl_free_args(int num_be_args, struct ctl_be_arg *be_args)
2050 {
2051 	int i;
2052 
2053 	if (be_args == NULL)
2054 		return;
2055 
2056 	for (i = 0; i < num_be_args; i++) {
2057 		free(be_args[i].kname, M_CTL);
2058 		free(be_args[i].kvalue, M_CTL);
2059 	}
2060 
2061 	free(be_args, M_CTL);
2062 }
2063 
2064 static struct ctl_be_arg *
2065 ctl_copyin_args(int num_be_args, struct ctl_be_arg *be_args,
2066 		char *error_str, size_t error_str_len)
2067 {
2068 	struct ctl_be_arg *args;
2069 	int i;
2070 
2071 	args = ctl_copyin_alloc(be_args, num_be_args * sizeof(*be_args),
2072 				error_str, error_str_len);
2073 
2074 	if (args == NULL)
2075 		goto bailout;
2076 
2077 	for (i = 0; i < num_be_args; i++) {
2078 		uint8_t *tmpptr;
2079 
2080 		args[i].kname = ctl_copyin_alloc(args[i].name,
2081 			args[i].namelen, error_str, error_str_len);
2082 		if (args[i].kname == NULL)
2083 			goto bailout;
2084 
2085 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2086 			snprintf(error_str, error_str_len, "Argument %d "
2087 				 "name is not NUL-terminated", i);
2088 			goto bailout;
2089 		}
2090 
2091 		args[i].kvalue = NULL;
2092 
2093 		tmpptr = ctl_copyin_alloc(args[i].value,
2094 			args[i].vallen, error_str, error_str_len);
2095 		if (tmpptr == NULL)
2096 			goto bailout;
2097 
2098 		args[i].kvalue = tmpptr;
2099 
2100 		if ((args[i].flags & CTL_BEARG_ASCII)
2101 		 && (tmpptr[args[i].vallen - 1] != '\0')) {
2102 			snprintf(error_str, error_str_len, "Argument %d "
2103 				 "value is not NUL-terminated", i);
2104 			goto bailout;
2105 		}
2106 	}
2107 
2108 	return (args);
2109 bailout:
2110 
2111 	ctl_free_args(num_be_args, args);
2112 
2113 	return (NULL);
2114 }
2115 
2116 /*
2117  * Escape characters that are illegal or not recommended in XML.
2118  */
2119 int
2120 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2121 {
2122 	int retval;
2123 
2124 	retval = 0;
2125 
2126 	for (; *str; str++) {
2127 		switch (*str) {
2128 		case '&':
2129 			retval = sbuf_printf(sb, "&amp;");
2130 			break;
2131 		case '>':
2132 			retval = sbuf_printf(sb, "&gt;");
2133 			break;
2134 		case '<':
2135 			retval = sbuf_printf(sb, "&lt;");
2136 			break;
2137 		default:
2138 			retval = sbuf_putc(sb, *str);
2139 			break;
2140 		}
2141 
2142 		if (retval != 0)
2143 			break;
2144 
2145 	}
2146 
2147 	return (retval);
2148 }
2149 
2150 static int
2151 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2152 	  struct thread *td)
2153 {
2154 	struct ctl_softc *softc;
2155 	int retval;
2156 
2157 	softc = control_softc;
2158 
2159 	retval = 0;
2160 
2161 	switch (cmd) {
2162 	case CTL_IO: {
2163 		union ctl_io *io;
2164 		void *pool_tmp;
2165 
2166 		/*
2167 		 * If we haven't been "enabled", don't allow any SCSI I/O
2168 		 * to this FETD.
2169 		 */
2170 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2171 			retval = -EPERM;
2172 			break;
2173 		}
2174 
2175 		io = ctl_alloc_io(softc->ioctl_info.fe.ctl_pool_ref);
2176 		if (io == NULL) {
2177 			printf("ctl_ioctl: can't allocate ctl_io!\n");
2178 			retval = -ENOSPC;
2179 			break;
2180 		}
2181 
2182 		/*
2183 		 * Need to save the pool reference so it doesn't get
2184 		 * spammed by the user's ctl_io.
2185 		 */
2186 		pool_tmp = io->io_hdr.pool;
2187 
2188 		memcpy(io, (void *)addr, sizeof(*io));
2189 
2190 		io->io_hdr.pool = pool_tmp;
2191 		/*
2192 		 * No status yet, so make sure the status is set properly.
2193 		 */
2194 		io->io_hdr.status = CTL_STATUS_NONE;
2195 
2196 		/*
2197 		 * The user sets the initiator ID, target and LUN IDs.
2198 		 */
2199 		io->io_hdr.nexus.targ_port = softc->ioctl_info.fe.targ_port;
2200 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2201 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2202 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2203 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2204 
2205 		retval = ctl_ioctl_submit_wait(io);
2206 
2207 		if (retval != 0) {
2208 			ctl_free_io(io);
2209 			break;
2210 		}
2211 
2212 		memcpy((void *)addr, io, sizeof(*io));
2213 
2214 		/* return this to our pool */
2215 		ctl_free_io(io);
2216 
2217 		break;
2218 	}
2219 	case CTL_ENABLE_PORT:
2220 	case CTL_DISABLE_PORT:
2221 	case CTL_SET_PORT_WWNS: {
2222 		struct ctl_frontend *fe;
2223 		struct ctl_port_entry *entry;
2224 
2225 		entry = (struct ctl_port_entry *)addr;
2226 
2227 		mtx_lock(&softc->ctl_lock);
2228 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2229 			int action, done;
2230 
2231 			action = 0;
2232 			done = 0;
2233 
2234 			if ((entry->port_type == CTL_PORT_NONE)
2235 			 && (entry->targ_port == fe->targ_port)) {
2236 				/*
2237 				 * If the user only wants to enable or
2238 				 * disable or set WWNs on a specific port,
2239 				 * do the operation and we're done.
2240 				 */
2241 				action = 1;
2242 				done = 1;
2243 			} else if (entry->port_type & fe->port_type) {
2244 				/*
2245 				 * Compare the user's type mask with the
2246 				 * particular frontend type to see if we
2247 				 * have a match.
2248 				 */
2249 				action = 1;
2250 				done = 0;
2251 
2252 				/*
2253 				 * Make sure the user isn't trying to set
2254 				 * WWNs on multiple ports at the same time.
2255 				 */
2256 				if (cmd == CTL_SET_PORT_WWNS) {
2257 					printf("%s: Can't set WWNs on "
2258 					       "multiple ports\n", __func__);
2259 					retval = EINVAL;
2260 					break;
2261 				}
2262 			}
2263 			if (action != 0) {
2264 				/*
2265 				 * XXX KDM we have to drop the lock here,
2266 				 * because the online/offline operations
2267 				 * can potentially block.  We need to
2268 				 * reference count the frontends so they
2269 				 * can't go away,
2270 				 */
2271 				mtx_unlock(&softc->ctl_lock);
2272 
2273 				if (cmd == CTL_ENABLE_PORT)
2274 					ctl_frontend_online(fe);
2275 				else if (cmd == CTL_DISABLE_PORT)
2276 					ctl_frontend_offline(fe);
2277 
2278 				mtx_lock(&softc->ctl_lock);
2279 
2280 				if (cmd == CTL_SET_PORT_WWNS)
2281 					ctl_frontend_set_wwns(fe,
2282 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2283 					    1 : 0, entry->wwnn,
2284 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2285 					    1 : 0, entry->wwpn);
2286 			}
2287 			if (done != 0)
2288 				break;
2289 		}
2290 		mtx_unlock(&softc->ctl_lock);
2291 		break;
2292 	}
2293 	case CTL_GET_PORT_LIST: {
2294 		struct ctl_frontend *fe;
2295 		struct ctl_port_list *list;
2296 		int i;
2297 
2298 		list = (struct ctl_port_list *)addr;
2299 
2300 		if (list->alloc_len != (list->alloc_num *
2301 		    sizeof(struct ctl_port_entry))) {
2302 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2303 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2304 			       "%zu\n", __func__, list->alloc_len,
2305 			       list->alloc_num, sizeof(struct ctl_port_entry));
2306 			retval = EINVAL;
2307 			break;
2308 		}
2309 		list->fill_len = 0;
2310 		list->fill_num = 0;
2311 		list->dropped_num = 0;
2312 		i = 0;
2313 		mtx_lock(&softc->ctl_lock);
2314 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2315 			struct ctl_port_entry entry, *list_entry;
2316 
2317 			if (list->fill_num >= list->alloc_num) {
2318 				list->dropped_num++;
2319 				continue;
2320 			}
2321 
2322 			entry.port_type = fe->port_type;
2323 			strlcpy(entry.port_name, fe->port_name,
2324 				sizeof(entry.port_name));
2325 			entry.targ_port = fe->targ_port;
2326 			entry.physical_port = fe->physical_port;
2327 			entry.virtual_port = fe->virtual_port;
2328 			entry.wwnn = fe->wwnn;
2329 			entry.wwpn = fe->wwpn;
2330 			if (fe->status & CTL_PORT_STATUS_ONLINE)
2331 				entry.online = 1;
2332 			else
2333 				entry.online = 0;
2334 
2335 			list_entry = &list->entries[i];
2336 
2337 			retval = copyout(&entry, list_entry, sizeof(entry));
2338 			if (retval != 0) {
2339 				printf("%s: CTL_GET_PORT_LIST: copyout "
2340 				       "returned %d\n", __func__, retval);
2341 				break;
2342 			}
2343 			i++;
2344 			list->fill_num++;
2345 			list->fill_len += sizeof(entry);
2346 		}
2347 		mtx_unlock(&softc->ctl_lock);
2348 
2349 		/*
2350 		 * If this is non-zero, we had a copyout fault, so there's
2351 		 * probably no point in attempting to set the status inside
2352 		 * the structure.
2353 		 */
2354 		if (retval != 0)
2355 			break;
2356 
2357 		if (list->dropped_num > 0)
2358 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2359 		else
2360 			list->status = CTL_PORT_LIST_OK;
2361 		break;
2362 	}
2363 	case CTL_DUMP_OOA: {
2364 		struct ctl_lun *lun;
2365 		union ctl_io *io;
2366 		char printbuf[128];
2367 		struct sbuf sb;
2368 
2369 		mtx_lock(&softc->ctl_lock);
2370 		printf("Dumping OOA queues:\n");
2371 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2372 			for (io = (union ctl_io *)TAILQ_FIRST(
2373 			     &lun->ooa_queue); io != NULL;
2374 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2375 			     ooa_links)) {
2376 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2377 					 SBUF_FIXEDLEN);
2378 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2379 					    (intmax_t)lun->lun,
2380 					    io->scsiio.tag_num,
2381 					    (io->io_hdr.flags &
2382 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2383 					    (io->io_hdr.flags &
2384 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2385 					    (io->io_hdr.flags &
2386 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2387 			                    (io->io_hdr.flags &
2388 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2389 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2390 				sbuf_finish(&sb);
2391 				printf("%s\n", sbuf_data(&sb));
2392 			}
2393 		}
2394 		printf("OOA queues dump done\n");
2395 		mtx_unlock(&softc->ctl_lock);
2396 		break;
2397 	}
2398 	case CTL_GET_OOA: {
2399 		struct ctl_lun *lun;
2400 		struct ctl_ooa *ooa_hdr;
2401 		uint32_t cur_fill_num;
2402 
2403 		ooa_hdr = (struct ctl_ooa *)addr;
2404 
2405 		if ((ooa_hdr->alloc_len == 0)
2406 		 || (ooa_hdr->alloc_num == 0)) {
2407 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2408 			       "must be non-zero\n", __func__,
2409 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2410 			retval = EINVAL;
2411 			break;
2412 		}
2413 
2414 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2415 		    sizeof(struct ctl_ooa_entry))) {
2416 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2417 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2418 			       __func__, ooa_hdr->alloc_len,
2419 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2420 			retval = EINVAL;
2421 			break;
2422 		}
2423 
2424 		mtx_lock(&softc->ctl_lock);
2425 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2426 		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2427 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2428 			mtx_unlock(&softc->ctl_lock);
2429 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2430 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2431 			retval = EINVAL;
2432 			break;
2433 		}
2434 
2435 		cur_fill_num = 0;
2436 
2437 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2438 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2439 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2440 					ooa_hdr);
2441 				if (retval != 0)
2442 					break;
2443 			}
2444 			if (retval != 0) {
2445 				mtx_unlock(&softc->ctl_lock);
2446 				break;
2447 			}
2448 		} else {
2449 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2450 
2451 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr);
2452 		}
2453 		mtx_unlock(&softc->ctl_lock);
2454 
2455 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2456 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2457 			sizeof(struct ctl_ooa_entry);
2458 
2459 		getbintime(&ooa_hdr->cur_bt);
2460 
2461 		if (cur_fill_num > ooa_hdr->alloc_num) {
2462 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2463 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2464 		} else {
2465 			ooa_hdr->dropped_num = 0;
2466 			ooa_hdr->status = CTL_OOA_OK;
2467 		}
2468 		break;
2469 	}
2470 	case CTL_CHECK_OOA: {
2471 		union ctl_io *io;
2472 		struct ctl_lun *lun;
2473 		struct ctl_ooa_info *ooa_info;
2474 
2475 
2476 		ooa_info = (struct ctl_ooa_info *)addr;
2477 
2478 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2479 			ooa_info->status = CTL_OOA_INVALID_LUN;
2480 			break;
2481 		}
2482 		mtx_lock(&softc->ctl_lock);
2483 		lun = softc->ctl_luns[ooa_info->lun_id];
2484 		if (lun == NULL) {
2485 			mtx_unlock(&softc->ctl_lock);
2486 			ooa_info->status = CTL_OOA_INVALID_LUN;
2487 			break;
2488 		}
2489 
2490 		ooa_info->num_entries = 0;
2491 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2492 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2493 		     &io->io_hdr, ooa_links)) {
2494 			ooa_info->num_entries++;
2495 		}
2496 
2497 		mtx_unlock(&softc->ctl_lock);
2498 		ooa_info->status = CTL_OOA_SUCCESS;
2499 
2500 		break;
2501 	}
2502 	case CTL_HARD_START:
2503 	case CTL_HARD_STOP: {
2504 		struct ctl_fe_ioctl_startstop_info ss_info;
2505 		struct cfi_metatask *metatask;
2506 		struct mtx hs_mtx;
2507 
2508 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2509 
2510 		cv_init(&ss_info.sem, "hard start/stop cv" );
2511 
2512 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2513 		if (metatask == NULL) {
2514 			retval = ENOMEM;
2515 			mtx_destroy(&hs_mtx);
2516 			break;
2517 		}
2518 
2519 		if (cmd == CTL_HARD_START)
2520 			metatask->tasktype = CFI_TASK_STARTUP;
2521 		else
2522 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2523 
2524 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2525 		metatask->callback_arg = &ss_info;
2526 
2527 		cfi_action(metatask);
2528 
2529 		/* Wait for the callback */
2530 		mtx_lock(&hs_mtx);
2531 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2532 		mtx_unlock(&hs_mtx);
2533 
2534 		/*
2535 		 * All information has been copied from the metatask by the
2536 		 * time cv_broadcast() is called, so we free the metatask here.
2537 		 */
2538 		cfi_free_metatask(metatask);
2539 
2540 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2541 
2542 		mtx_destroy(&hs_mtx);
2543 		break;
2544 	}
2545 	case CTL_BBRREAD: {
2546 		struct ctl_bbrread_info *bbr_info;
2547 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2548 		struct mtx bbr_mtx;
2549 		struct cfi_metatask *metatask;
2550 
2551 		bbr_info = (struct ctl_bbrread_info *)addr;
2552 
2553 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2554 
2555 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2556 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2557 
2558 		fe_bbr_info.bbr_info = bbr_info;
2559 		fe_bbr_info.lock = &bbr_mtx;
2560 
2561 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2562 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2563 
2564 		if (metatask == NULL) {
2565 			mtx_destroy(&bbr_mtx);
2566 			cv_destroy(&fe_bbr_info.sem);
2567 			retval = ENOMEM;
2568 			break;
2569 		}
2570 		metatask->tasktype = CFI_TASK_BBRREAD;
2571 		metatask->callback = ctl_ioctl_bbrread_callback;
2572 		metatask->callback_arg = &fe_bbr_info;
2573 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2574 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2575 		metatask->taskinfo.bbrread.len = bbr_info->len;
2576 
2577 		cfi_action(metatask);
2578 
2579 		mtx_lock(&bbr_mtx);
2580 		while (fe_bbr_info.wakeup_done == 0)
2581 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2582 		mtx_unlock(&bbr_mtx);
2583 
2584 		bbr_info->status = metatask->status;
2585 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2586 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2587 		memcpy(&bbr_info->sense_data,
2588 		       &metatask->taskinfo.bbrread.sense_data,
2589 		       ctl_min(sizeof(bbr_info->sense_data),
2590 			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2591 
2592 		cfi_free_metatask(metatask);
2593 
2594 		mtx_destroy(&bbr_mtx);
2595 		cv_destroy(&fe_bbr_info.sem);
2596 
2597 		break;
2598 	}
2599 	case CTL_DELAY_IO: {
2600 		struct ctl_io_delay_info *delay_info;
2601 #ifdef CTL_IO_DELAY
2602 		struct ctl_lun *lun;
2603 #endif /* CTL_IO_DELAY */
2604 
2605 		delay_info = (struct ctl_io_delay_info *)addr;
2606 
2607 #ifdef CTL_IO_DELAY
2608 		mtx_lock(&softc->ctl_lock);
2609 
2610 		if ((delay_info->lun_id > CTL_MAX_LUNS)
2611 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2612 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2613 		} else {
2614 			lun = softc->ctl_luns[delay_info->lun_id];
2615 
2616 			delay_info->status = CTL_DELAY_STATUS_OK;
2617 
2618 			switch (delay_info->delay_type) {
2619 			case CTL_DELAY_TYPE_CONT:
2620 				break;
2621 			case CTL_DELAY_TYPE_ONESHOT:
2622 				break;
2623 			default:
2624 				delay_info->status =
2625 					CTL_DELAY_STATUS_INVALID_TYPE;
2626 				break;
2627 			}
2628 
2629 			switch (delay_info->delay_loc) {
2630 			case CTL_DELAY_LOC_DATAMOVE:
2631 				lun->delay_info.datamove_type =
2632 					delay_info->delay_type;
2633 				lun->delay_info.datamove_delay =
2634 					delay_info->delay_secs;
2635 				break;
2636 			case CTL_DELAY_LOC_DONE:
2637 				lun->delay_info.done_type =
2638 					delay_info->delay_type;
2639 				lun->delay_info.done_delay =
2640 					delay_info->delay_secs;
2641 				break;
2642 			default:
2643 				delay_info->status =
2644 					CTL_DELAY_STATUS_INVALID_LOC;
2645 				break;
2646 			}
2647 		}
2648 
2649 		mtx_unlock(&softc->ctl_lock);
2650 #else
2651 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2652 #endif /* CTL_IO_DELAY */
2653 		break;
2654 	}
2655 	case CTL_REALSYNC_SET: {
2656 		int *syncstate;
2657 
2658 		syncstate = (int *)addr;
2659 
2660 		mtx_lock(&softc->ctl_lock);
2661 		switch (*syncstate) {
2662 		case 0:
2663 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2664 			break;
2665 		case 1:
2666 			softc->flags |= CTL_FLAG_REAL_SYNC;
2667 			break;
2668 		default:
2669 			retval = -EINVAL;
2670 			break;
2671 		}
2672 		mtx_unlock(&softc->ctl_lock);
2673 		break;
2674 	}
2675 	case CTL_REALSYNC_GET: {
2676 		int *syncstate;
2677 
2678 		syncstate = (int*)addr;
2679 
2680 		mtx_lock(&softc->ctl_lock);
2681 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2682 			*syncstate = 1;
2683 		else
2684 			*syncstate = 0;
2685 		mtx_unlock(&softc->ctl_lock);
2686 
2687 		break;
2688 	}
2689 	case CTL_SETSYNC:
2690 	case CTL_GETSYNC: {
2691 		struct ctl_sync_info *sync_info;
2692 		struct ctl_lun *lun;
2693 
2694 		sync_info = (struct ctl_sync_info *)addr;
2695 
2696 		mtx_lock(&softc->ctl_lock);
2697 		lun = softc->ctl_luns[sync_info->lun_id];
2698 		if (lun == NULL) {
2699 			mtx_unlock(&softc->ctl_lock);
2700 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2701 		}
2702 		/*
2703 		 * Get or set the sync interval.  We're not bounds checking
2704 		 * in the set case, hopefully the user won't do something
2705 		 * silly.
2706 		 */
2707 		if (cmd == CTL_GETSYNC)
2708 			sync_info->sync_interval = lun->sync_interval;
2709 		else
2710 			lun->sync_interval = sync_info->sync_interval;
2711 
2712 		mtx_unlock(&softc->ctl_lock);
2713 
2714 		sync_info->status = CTL_GS_SYNC_OK;
2715 
2716 		break;
2717 	}
2718 	case CTL_GETSTATS: {
2719 		struct ctl_stats *stats;
2720 		struct ctl_lun *lun;
2721 		int i;
2722 
2723 		stats = (struct ctl_stats *)addr;
2724 
2725 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2726 		     stats->alloc_len) {
2727 			stats->status = CTL_SS_NEED_MORE_SPACE;
2728 			stats->num_luns = softc->num_luns;
2729 			break;
2730 		}
2731 		/*
2732 		 * XXX KDM no locking here.  If the LUN list changes,
2733 		 * things can blow up.
2734 		 */
2735 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2736 		     i++, lun = STAILQ_NEXT(lun, links)) {
2737 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2738 					 sizeof(lun->stats));
2739 			if (retval != 0)
2740 				break;
2741 		}
2742 		stats->num_luns = softc->num_luns;
2743 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2744 				 softc->num_luns;
2745 		stats->status = CTL_SS_OK;
2746 #ifdef CTL_TIME_IO
2747 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2748 #else
2749 		stats->flags = CTL_STATS_FLAG_NONE;
2750 #endif
2751 		getnanouptime(&stats->timestamp);
2752 		break;
2753 	}
2754 	case CTL_ERROR_INJECT: {
2755 		struct ctl_error_desc *err_desc, *new_err_desc;
2756 		struct ctl_lun *lun;
2757 
2758 		err_desc = (struct ctl_error_desc *)addr;
2759 
2760 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2761 				      M_WAITOK | M_ZERO);
2762 		if (new_err_desc == NULL) {
2763 			printf("%s: CTL_ERROR_INJECT: error allocating %zu "
2764 			       "bytes\n", __func__, sizeof(*new_err_desc));
2765 			retval = ENOMEM;
2766 			break;
2767 		}
2768 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2769 
2770 		mtx_lock(&softc->ctl_lock);
2771 		lun = softc->ctl_luns[err_desc->lun_id];
2772 		if (lun == NULL) {
2773 			mtx_unlock(&softc->ctl_lock);
2774 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2775 			       __func__, (uintmax_t)err_desc->lun_id);
2776 			retval = EINVAL;
2777 			break;
2778 		}
2779 
2780 		/*
2781 		 * We could do some checking here to verify the validity
2782 		 * of the request, but given the complexity of error
2783 		 * injection requests, the checking logic would be fairly
2784 		 * complex.
2785 		 *
2786 		 * For now, if the request is invalid, it just won't get
2787 		 * executed and might get deleted.
2788 		 */
2789 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2790 
2791 		/*
2792 		 * XXX KDM check to make sure the serial number is unique,
2793 		 * in case we somehow manage to wrap.  That shouldn't
2794 		 * happen for a very long time, but it's the right thing to
2795 		 * do.
2796 		 */
2797 		new_err_desc->serial = lun->error_serial;
2798 		err_desc->serial = lun->error_serial;
2799 		lun->error_serial++;
2800 
2801 		mtx_unlock(&softc->ctl_lock);
2802 		break;
2803 	}
2804 	case CTL_ERROR_INJECT_DELETE: {
2805 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2806 		struct ctl_lun *lun;
2807 		int delete_done;
2808 
2809 		delete_desc = (struct ctl_error_desc *)addr;
2810 		delete_done = 0;
2811 
2812 		mtx_lock(&softc->ctl_lock);
2813 		lun = softc->ctl_luns[delete_desc->lun_id];
2814 		if (lun == NULL) {
2815 			mtx_unlock(&softc->ctl_lock);
2816 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2817 			       __func__, (uintmax_t)delete_desc->lun_id);
2818 			retval = EINVAL;
2819 			break;
2820 		}
2821 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2822 			if (desc->serial != delete_desc->serial)
2823 				continue;
2824 
2825 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2826 				      links);
2827 			free(desc, M_CTL);
2828 			delete_done = 1;
2829 		}
2830 		mtx_unlock(&softc->ctl_lock);
2831 		if (delete_done == 0) {
2832 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2833 			       "error serial %ju on LUN %u\n", __func__,
2834 			       delete_desc->serial, delete_desc->lun_id);
2835 			retval = EINVAL;
2836 			break;
2837 		}
2838 		break;
2839 	}
2840 	case CTL_DUMP_STRUCTS: {
2841 		int i, j, k;
2842 		struct ctl_frontend *fe;
2843 
2844 		printf("CTL IID to WWPN map start:\n");
2845 		for (i = 0; i < CTL_MAX_PORTS; i++) {
2846 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2847 				if (softc->wwpn_iid[i][j].in_use == 0)
2848 					continue;
2849 
2850 				printf("port %d iid %u WWPN %#jx\n",
2851 				       softc->wwpn_iid[i][j].port,
2852 				       softc->wwpn_iid[i][j].iid,
2853 				       (uintmax_t)softc->wwpn_iid[i][j].wwpn);
2854 			}
2855 		}
2856 		printf("CTL IID to WWPN map end\n");
2857 		printf("CTL Persistent Reservation information start:\n");
2858 		for (i = 0; i < CTL_MAX_LUNS; i++) {
2859 			struct ctl_lun *lun;
2860 
2861 			lun = softc->ctl_luns[i];
2862 
2863 			if ((lun == NULL)
2864 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2865 				continue;
2866 
2867 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2868 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2869 					if (lun->per_res[j+k].registered == 0)
2870 						continue;
2871 					printf("LUN %d port %d iid %d key "
2872 					       "%#jx\n", i, j, k,
2873 					       (uintmax_t)scsi_8btou64(
2874 					       lun->per_res[j+k].res_key.key));
2875 				}
2876 			}
2877 		}
2878 		printf("CTL Persistent Reservation information end\n");
2879 		printf("CTL Frontends:\n");
2880 		/*
2881 		 * XXX KDM calling this without a lock.  We'd likely want
2882 		 * to drop the lock before calling the frontend's dump
2883 		 * routine anyway.
2884 		 */
2885 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2886 			printf("Frontend %s Type %u pport %d vport %d WWNN "
2887 			       "%#jx WWPN %#jx\n", fe->port_name, fe->port_type,
2888 			       fe->physical_port, fe->virtual_port,
2889 			       (uintmax_t)fe->wwnn, (uintmax_t)fe->wwpn);
2890 
2891 			/*
2892 			 * Frontends are not required to support the dump
2893 			 * routine.
2894 			 */
2895 			if (fe->fe_dump == NULL)
2896 				continue;
2897 
2898 			fe->fe_dump();
2899 		}
2900 		printf("CTL Frontend information end\n");
2901 		break;
2902 	}
2903 	case CTL_LUN_REQ: {
2904 		struct ctl_lun_req *lun_req;
2905 		struct ctl_backend_driver *backend;
2906 
2907 		lun_req = (struct ctl_lun_req *)addr;
2908 
2909 		backend = ctl_backend_find(lun_req->backend);
2910 		if (backend == NULL) {
2911 			lun_req->status = CTL_LUN_ERROR;
2912 			snprintf(lun_req->error_str,
2913 				 sizeof(lun_req->error_str),
2914 				 "Backend \"%s\" not found.",
2915 				 lun_req->backend);
2916 			break;
2917 		}
2918 		if (lun_req->num_be_args > 0) {
2919 			lun_req->kern_be_args = ctl_copyin_args(
2920 				lun_req->num_be_args,
2921 				lun_req->be_args,
2922 				lun_req->error_str,
2923 				sizeof(lun_req->error_str));
2924 			if (lun_req->kern_be_args == NULL) {
2925 				lun_req->status = CTL_LUN_ERROR;
2926 				break;
2927 			}
2928 		}
2929 
2930 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2931 
2932 		if (lun_req->num_be_args > 0) {
2933 			ctl_free_args(lun_req->num_be_args,
2934 				      lun_req->kern_be_args);
2935 		}
2936 		break;
2937 	}
2938 	case CTL_LUN_LIST: {
2939 		struct sbuf *sb;
2940 		struct ctl_lun *lun;
2941 		struct ctl_lun_list *list;
2942 
2943 		list = (struct ctl_lun_list *)addr;
2944 
2945 		/*
2946 		 * Allocate a fixed length sbuf here, based on the length
2947 		 * of the user's buffer.  We could allocate an auto-extending
2948 		 * buffer, and then tell the user how much larger our
2949 		 * amount of data is than his buffer, but that presents
2950 		 * some problems:
2951 		 *
2952 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2953 		 *     we can't hold a lock while calling them with an
2954 		 *     auto-extending buffer.
2955  		 *
2956 		 * 2.  There is not currently a LUN reference counting
2957 		 *     mechanism, outside of outstanding transactions on
2958 		 *     the LUN's OOA queue.  So a LUN could go away on us
2959 		 *     while we're getting the LUN number, backend-specific
2960 		 *     information, etc.  Thus, given the way things
2961 		 *     currently work, we need to hold the CTL lock while
2962 		 *     grabbing LUN information.
2963 		 *
2964 		 * So, from the user's standpoint, the best thing to do is
2965 		 * allocate what he thinks is a reasonable buffer length,
2966 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2967 		 * double the buffer length and try again.  (And repeat
2968 		 * that until he succeeds.)
2969 		 */
2970 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2971 		if (sb == NULL) {
2972 			list->status = CTL_LUN_LIST_ERROR;
2973 			snprintf(list->error_str, sizeof(list->error_str),
2974 				 "Unable to allocate %d bytes for LUN list",
2975 				 list->alloc_len);
2976 			break;
2977 		}
2978 
2979 		sbuf_printf(sb, "<ctllunlist>\n");
2980 
2981 		mtx_lock(&softc->ctl_lock);
2982 
2983 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2984 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2985 					     (uintmax_t)lun->lun);
2986 
2987 			/*
2988 			 * Bail out as soon as we see that we've overfilled
2989 			 * the buffer.
2990 			 */
2991 			if (retval != 0)
2992 				break;
2993 
2994 			retval = sbuf_printf(sb, "<backend_type>%s"
2995 					     "</backend_type>\n",
2996 					     (lun->backend == NULL) ?  "none" :
2997 					     lun->backend->name);
2998 
2999 			if (retval != 0)
3000 				break;
3001 
3002 			retval = sbuf_printf(sb, "<lun_type>%d</lun_type>\n",
3003 					     lun->be_lun->lun_type);
3004 
3005 			if (retval != 0)
3006 				break;
3007 
3008 			if (lun->backend == NULL) {
3009 				retval = sbuf_printf(sb, "</lun>\n");
3010 				if (retval != 0)
3011 					break;
3012 				continue;
3013 			}
3014 
3015 			retval = sbuf_printf(sb, "<size>%ju</size>\n",
3016 					     (lun->be_lun->maxlba > 0) ?
3017 					     lun->be_lun->maxlba + 1 : 0);
3018 
3019 			if (retval != 0)
3020 				break;
3021 
3022 			retval = sbuf_printf(sb, "<blocksize>%u</blocksize>\n",
3023 					     lun->be_lun->blocksize);
3024 
3025 			if (retval != 0)
3026 				break;
3027 
3028 			retval = sbuf_printf(sb, "<serial_number>");
3029 
3030 			if (retval != 0)
3031 				break;
3032 
3033 			retval = ctl_sbuf_printf_esc(sb,
3034 						     lun->be_lun->serial_num);
3035 
3036 			if (retval != 0)
3037 				break;
3038 
3039 			retval = sbuf_printf(sb, "</serial_number>\n");
3040 
3041 			if (retval != 0)
3042 				break;
3043 
3044 			retval = sbuf_printf(sb, "<device_id>");
3045 
3046 			if (retval != 0)
3047 				break;
3048 
3049 			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3050 
3051 			if (retval != 0)
3052 				break;
3053 
3054 			retval = sbuf_printf(sb, "</device_id>\n");
3055 
3056 			if (retval != 0)
3057 				break;
3058 
3059 			if (lun->backend->lun_info == NULL) {
3060 				retval = sbuf_printf(sb, "</lun>\n");
3061 				if (retval != 0)
3062 					break;
3063 				continue;
3064 			}
3065 
3066 			retval =lun->backend->lun_info(lun->be_lun->be_lun, sb);
3067 
3068 			if (retval != 0)
3069 				break;
3070 
3071 			retval = sbuf_printf(sb, "</lun>\n");
3072 
3073 			if (retval != 0)
3074 				break;
3075 		}
3076 		mtx_unlock(&softc->ctl_lock);
3077 
3078 		if ((retval != 0)
3079 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3080 			retval = 0;
3081 			sbuf_delete(sb);
3082 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3083 			snprintf(list->error_str, sizeof(list->error_str),
3084 				 "Out of space, %d bytes is too small",
3085 				 list->alloc_len);
3086 			break;
3087 		}
3088 
3089 		sbuf_finish(sb);
3090 
3091 		retval = copyout(sbuf_data(sb), list->lun_xml,
3092 				 sbuf_len(sb) + 1);
3093 
3094 		list->fill_len = sbuf_len(sb) + 1;
3095 		list->status = CTL_LUN_LIST_OK;
3096 		sbuf_delete(sb);
3097 		break;
3098 	}
3099 	default: {
3100 		/* XXX KDM should we fix this? */
3101 #if 0
3102 		struct ctl_backend_driver *backend;
3103 		unsigned int type;
3104 		int found;
3105 
3106 		found = 0;
3107 
3108 		/*
3109 		 * We encode the backend type as the ioctl type for backend
3110 		 * ioctls.  So parse it out here, and then search for a
3111 		 * backend of this type.
3112 		 */
3113 		type = _IOC_TYPE(cmd);
3114 
3115 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3116 			if (backend->type == type) {
3117 				found = 1;
3118 				break;
3119 			}
3120 		}
3121 		if (found == 0) {
3122 			printf("ctl: unknown ioctl command %#lx or backend "
3123 			       "%d\n", cmd, type);
3124 			retval = -EINVAL;
3125 			break;
3126 		}
3127 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3128 #endif
3129 		retval = ENOTTY;
3130 		break;
3131 	}
3132 	}
3133 	return (retval);
3134 }
3135 
3136 uint32_t
3137 ctl_get_initindex(struct ctl_nexus *nexus)
3138 {
3139 	if (nexus->targ_port < CTL_MAX_PORTS)
3140 		return (nexus->initid.id +
3141 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3142 	else
3143 		return (nexus->initid.id +
3144 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3145 			CTL_MAX_INIT_PER_PORT));
3146 }
3147 
3148 uint32_t
3149 ctl_get_resindex(struct ctl_nexus *nexus)
3150 {
3151 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3152 }
3153 
3154 uint32_t
3155 ctl_port_idx(int port_num)
3156 {
3157 	if (port_num < CTL_MAX_PORTS)
3158 		return(port_num);
3159 	else
3160 		return(port_num - CTL_MAX_PORTS);
3161 }
3162 
3163 /*
3164  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3165  * that are a power of 2.
3166  */
3167 int
3168 ctl_ffz(uint32_t *mask, uint32_t size)
3169 {
3170 	uint32_t num_chunks, num_pieces;
3171 	int i, j;
3172 
3173 	num_chunks = (size >> 5);
3174 	if (num_chunks == 0)
3175 		num_chunks++;
3176 	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3177 
3178 	for (i = 0; i < num_chunks; i++) {
3179 		for (j = 0; j < num_pieces; j++) {
3180 			if ((mask[i] & (1 << j)) == 0)
3181 				return ((i << 5) + j);
3182 		}
3183 	}
3184 
3185 	return (-1);
3186 }
3187 
3188 int
3189 ctl_set_mask(uint32_t *mask, uint32_t bit)
3190 {
3191 	uint32_t chunk, piece;
3192 
3193 	chunk = bit >> 5;
3194 	piece = bit % (sizeof(uint32_t) * 8);
3195 
3196 	if ((mask[chunk] & (1 << piece)) != 0)
3197 		return (-1);
3198 	else
3199 		mask[chunk] |= (1 << piece);
3200 
3201 	return (0);
3202 }
3203 
3204 int
3205 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3206 {
3207 	uint32_t chunk, piece;
3208 
3209 	chunk = bit >> 5;
3210 	piece = bit % (sizeof(uint32_t) * 8);
3211 
3212 	if ((mask[chunk] & (1 << piece)) == 0)
3213 		return (-1);
3214 	else
3215 		mask[chunk] &= ~(1 << piece);
3216 
3217 	return (0);
3218 }
3219 
3220 int
3221 ctl_is_set(uint32_t *mask, uint32_t bit)
3222 {
3223 	uint32_t chunk, piece;
3224 
3225 	chunk = bit >> 5;
3226 	piece = bit % (sizeof(uint32_t) * 8);
3227 
3228 	if ((mask[chunk] & (1 << piece)) == 0)
3229 		return (0);
3230 	else
3231 		return (1);
3232 }
3233 
3234 #ifdef unused
3235 /*
3236  * The bus, target and lun are optional, they can be filled in later.
3237  * can_wait is used to determine whether we can wait on the malloc or not.
3238  */
3239 union ctl_io*
3240 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3241 	      uint32_t targ_lun, int can_wait)
3242 {
3243 	union ctl_io *io;
3244 
3245 	if (can_wait)
3246 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3247 	else
3248 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3249 
3250 	if (io != NULL) {
3251 		io->io_hdr.io_type = io_type;
3252 		io->io_hdr.targ_port = targ_port;
3253 		/*
3254 		 * XXX KDM this needs to change/go away.  We need to move
3255 		 * to a preallocated pool of ctl_scsiio structures.
3256 		 */
3257 		io->io_hdr.nexus.targ_target.id = targ_target;
3258 		io->io_hdr.nexus.targ_lun = targ_lun;
3259 	}
3260 
3261 	return (io);
3262 }
3263 
3264 void
3265 ctl_kfree_io(union ctl_io *io)
3266 {
3267 	free(io, M_CTL);
3268 }
3269 #endif /* unused */
3270 
3271 /*
3272  * ctl_softc, pool_type, total_ctl_io are passed in.
3273  * npool is passed out.
3274  */
3275 int
3276 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3277 		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3278 {
3279 	uint32_t i;
3280 	union ctl_io *cur_io, *next_io;
3281 	struct ctl_io_pool *pool;
3282 	int retval;
3283 
3284 	retval = 0;
3285 
3286 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL, M_NOWAIT);
3287 	if (pool == NULL) {
3288 		retval = -ENOMEM;
3289 		goto bailout;
3290 	}
3291 
3292 	memset(pool, 0, sizeof(*pool));
3293 
3294 	pool->type = pool_type;
3295 	pool->ctl_softc = ctl_softc;
3296 
3297 	mtx_lock(&ctl_softc->ctl_lock);
3298 	pool->id = ctl_softc->cur_pool_id++;
3299 	mtx_unlock(&ctl_softc->ctl_lock);
3300 
3301 	pool->flags = CTL_POOL_FLAG_NONE;
3302 	STAILQ_INIT(&pool->free_queue);
3303 
3304 	/*
3305 	 * XXX KDM other options here:
3306 	 * - allocate a page at a time
3307 	 * - allocate one big chunk of memory.
3308 	 * Page allocation might work well, but would take a little more
3309 	 * tracking.
3310 	 */
3311 	for (i = 0; i < total_ctl_io; i++) {
3312 		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTL,
3313 						M_NOWAIT);
3314 		if (cur_io == NULL) {
3315 			retval = ENOMEM;
3316 			break;
3317 		}
3318 		cur_io->io_hdr.pool = pool;
3319 		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3320 		pool->total_ctl_io++;
3321 		pool->free_ctl_io++;
3322 	}
3323 
3324 	if (retval != 0) {
3325 		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3326 		     cur_io != NULL; cur_io = next_io) {
3327 			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3328 							      links);
3329 			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3330 				      ctl_io_hdr, links);
3331 			free(cur_io, M_CTL);
3332 		}
3333 
3334 		free(pool, M_CTL);
3335 		goto bailout;
3336 	}
3337 	mtx_lock(&ctl_softc->ctl_lock);
3338 	ctl_softc->num_pools++;
3339 	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3340 	/*
3341 	 * Increment our usage count if this is an external consumer, so we
3342 	 * can't get unloaded until the external consumer (most likely a
3343 	 * FETD) unloads and frees his pool.
3344 	 *
3345 	 * XXX KDM will this increment the caller's module use count, or
3346 	 * mine?
3347 	 */
3348 #if 0
3349 	if ((pool_type != CTL_POOL_EMERGENCY)
3350 	 && (pool_type != CTL_POOL_INTERNAL)
3351 	 && (pool_type != CTL_POOL_IOCTL)
3352 	 && (pool_type != CTL_POOL_4OTHERSC))
3353 		MOD_INC_USE_COUNT;
3354 #endif
3355 
3356 	mtx_unlock(&ctl_softc->ctl_lock);
3357 
3358 	*npool = pool;
3359 
3360 bailout:
3361 
3362 	return (retval);
3363 }
3364 
3365 /*
3366  * Caller must hold ctl_softc->ctl_lock.
3367  */
3368 int
3369 ctl_pool_acquire(struct ctl_io_pool *pool)
3370 {
3371 	if (pool == NULL)
3372 		return (-EINVAL);
3373 
3374 	if (pool->flags & CTL_POOL_FLAG_INVALID)
3375 		return (-EINVAL);
3376 
3377 	pool->refcount++;
3378 
3379 	return (0);
3380 }
3381 
3382 /*
3383  * Caller must hold ctl_softc->ctl_lock.
3384  */
3385 int
3386 ctl_pool_invalidate(struct ctl_io_pool *pool)
3387 {
3388 	if (pool == NULL)
3389 		return (-EINVAL);
3390 
3391 	pool->flags |= CTL_POOL_FLAG_INVALID;
3392 
3393 	return (0);
3394 }
3395 
3396 /*
3397  * Caller must hold ctl_softc->ctl_lock.
3398  */
3399 int
3400 ctl_pool_release(struct ctl_io_pool *pool)
3401 {
3402 	if (pool == NULL)
3403 		return (-EINVAL);
3404 
3405 	if ((--pool->refcount == 0)
3406 	 && (pool->flags & CTL_POOL_FLAG_INVALID)) {
3407 		ctl_pool_free(pool->ctl_softc, pool);
3408 	}
3409 
3410 	return (0);
3411 }
3412 
3413 /*
3414  * Must be called with ctl_softc->ctl_lock held.
3415  */
3416 void
3417 ctl_pool_free(struct ctl_softc *ctl_softc, struct ctl_io_pool *pool)
3418 {
3419 	union ctl_io *cur_io, *next_io;
3420 
3421 	for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3422 	     cur_io != NULL; cur_io = next_io) {
3423 		next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3424 						      links);
3425 		STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr, ctl_io_hdr,
3426 			      links);
3427 		free(cur_io, M_CTL);
3428 	}
3429 
3430 	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3431 	ctl_softc->num_pools--;
3432 
3433 	/*
3434 	 * XXX KDM will this decrement the caller's usage count or mine?
3435 	 */
3436 #if 0
3437 	if ((pool->type != CTL_POOL_EMERGENCY)
3438 	 && (pool->type != CTL_POOL_INTERNAL)
3439 	 && (pool->type != CTL_POOL_IOCTL))
3440 		MOD_DEC_USE_COUNT;
3441 #endif
3442 
3443 	free(pool, M_CTL);
3444 }
3445 
3446 /*
3447  * This routine does not block (except for spinlocks of course).
3448  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3449  * possible.
3450  */
3451 union ctl_io *
3452 ctl_alloc_io(void *pool_ref)
3453 {
3454 	union ctl_io *io;
3455 	struct ctl_softc *ctl_softc;
3456 	struct ctl_io_pool *pool, *npool;
3457 	struct ctl_io_pool *emergency_pool;
3458 
3459 	pool = (struct ctl_io_pool *)pool_ref;
3460 
3461 	if (pool == NULL) {
3462 		printf("%s: pool is NULL\n", __func__);
3463 		return (NULL);
3464 	}
3465 
3466 	emergency_pool = NULL;
3467 
3468 	ctl_softc = pool->ctl_softc;
3469 
3470 	mtx_lock(&ctl_softc->ctl_lock);
3471 	/*
3472 	 * First, try to get the io structure from the user's pool.
3473 	 */
3474 	if (ctl_pool_acquire(pool) == 0) {
3475 		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3476 		if (io != NULL) {
3477 			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3478 			pool->total_allocated++;
3479 			pool->free_ctl_io--;
3480 			mtx_unlock(&ctl_softc->ctl_lock);
3481 			return (io);
3482 		} else
3483 			ctl_pool_release(pool);
3484 	}
3485 	/*
3486 	 * If he doesn't have any io structures left, search for an
3487 	 * emergency pool and grab one from there.
3488 	 */
3489 	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3490 		if (npool->type != CTL_POOL_EMERGENCY)
3491 			continue;
3492 
3493 		if (ctl_pool_acquire(npool) != 0)
3494 			continue;
3495 
3496 		emergency_pool = npool;
3497 
3498 		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3499 		if (io != NULL) {
3500 			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3501 			npool->total_allocated++;
3502 			npool->free_ctl_io--;
3503 			mtx_unlock(&ctl_softc->ctl_lock);
3504 			return (io);
3505 		} else
3506 			ctl_pool_release(npool);
3507 	}
3508 
3509 	/* Drop the spinlock before we malloc */
3510 	mtx_unlock(&ctl_softc->ctl_lock);
3511 
3512 	/*
3513 	 * The emergency pool (if it exists) didn't have one, so try an
3514 	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3515 	 */
3516 	io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3517 	if (io != NULL) {
3518 		/*
3519 		 * If the emergency pool exists but is empty, add this
3520 		 * ctl_io to its list when it gets freed.
3521 		 */
3522 		if (emergency_pool != NULL) {
3523 			mtx_lock(&ctl_softc->ctl_lock);
3524 			if (ctl_pool_acquire(emergency_pool) == 0) {
3525 				io->io_hdr.pool = emergency_pool;
3526 				emergency_pool->total_ctl_io++;
3527 				/*
3528 				 * Need to bump this, otherwise
3529 				 * total_allocated and total_freed won't
3530 				 * match when we no longer have anything
3531 				 * outstanding.
3532 				 */
3533 				emergency_pool->total_allocated++;
3534 			}
3535 			mtx_unlock(&ctl_softc->ctl_lock);
3536 		} else
3537 			io->io_hdr.pool = NULL;
3538 	}
3539 
3540 	return (io);
3541 }
3542 
3543 static void
3544 ctl_free_io_internal(union ctl_io *io, int have_lock)
3545 {
3546 	if (io == NULL)
3547 		return;
3548 
3549 	/*
3550 	 * If this ctl_io has a pool, return it to that pool.
3551 	 */
3552 	if (io->io_hdr.pool != NULL) {
3553 		struct ctl_io_pool *pool;
3554 #if 0
3555 		struct ctl_softc *ctl_softc;
3556 		union ctl_io *tmp_io;
3557 		unsigned long xflags;
3558 		int i;
3559 
3560 		ctl_softc = control_softc;
3561 #endif
3562 
3563 		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3564 
3565 		if (have_lock == 0)
3566 			mtx_lock(&pool->ctl_softc->ctl_lock);
3567 #if 0
3568 		save_flags(xflags);
3569 
3570 		for (i = 0, tmp_io = (union ctl_io *)STAILQ_FIRST(
3571 		     &ctl_softc->task_queue); tmp_io != NULL; i++,
3572 		     tmp_io = (union ctl_io *)STAILQ_NEXT(&tmp_io->io_hdr,
3573 		     links)) {
3574 			if (tmp_io == io) {
3575 				printf("%s: %p is still on the task queue!\n",
3576 				       __func__, tmp_io);
3577 				printf("%s: (%d): type %d "
3578 				       "msg %d cdb %x iptl: "
3579 				       "%d:%d:%d:%d tag 0x%04x "
3580 				       "flg %#lx\n",
3581 					__func__, i,
3582 					tmp_io->io_hdr.io_type,
3583 					tmp_io->io_hdr.msg_type,
3584 					tmp_io->scsiio.cdb[0],
3585 					tmp_io->io_hdr.nexus.initid.id,
3586 					tmp_io->io_hdr.nexus.targ_port,
3587 					tmp_io->io_hdr.nexus.targ_target.id,
3588 					tmp_io->io_hdr.nexus.targ_lun,
3589 					(tmp_io->io_hdr.io_type ==
3590 					CTL_IO_TASK) ?
3591 					tmp_io->taskio.tag_num :
3592 					tmp_io->scsiio.tag_num,
3593 					xflags);
3594 				panic("I/O still on the task queue!");
3595 			}
3596 		}
3597 #endif
3598 		io->io_hdr.io_type = 0xff;
3599 		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3600 		pool->total_freed++;
3601 		pool->free_ctl_io++;
3602 		ctl_pool_release(pool);
3603 		if (have_lock == 0)
3604 			mtx_unlock(&pool->ctl_softc->ctl_lock);
3605 	} else {
3606 		/*
3607 		 * Otherwise, just free it.  We probably malloced it and
3608 		 * the emergency pool wasn't available.
3609 		 */
3610 		free(io, M_CTL);
3611 	}
3612 
3613 }
3614 
3615 void
3616 ctl_free_io(union ctl_io *io)
3617 {
3618 	ctl_free_io_internal(io, /*have_lock*/ 0);
3619 }
3620 
3621 void
3622 ctl_zero_io(union ctl_io *io)
3623 {
3624 	void *pool_ref;
3625 
3626 	if (io == NULL)
3627 		return;
3628 
3629 	/*
3630 	 * May need to preserve linked list pointers at some point too.
3631 	 */
3632 	pool_ref = io->io_hdr.pool;
3633 
3634 	memset(io, 0, sizeof(*io));
3635 
3636 	io->io_hdr.pool = pool_ref;
3637 }
3638 
3639 /*
3640  * This routine is currently used for internal copies of ctl_ios that need
3641  * to persist for some reason after we've already returned status to the
3642  * FETD.  (Thus the flag set.)
3643  *
3644  * XXX XXX
3645  * Note that this makes a blind copy of all fields in the ctl_io, except
3646  * for the pool reference.  This includes any memory that has been
3647  * allocated!  That memory will no longer be valid after done has been
3648  * called, so this would be VERY DANGEROUS for command that actually does
3649  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3650  * start and stop commands, which don't transfer any data, so this is not a
3651  * problem.  If it is used for anything else, the caller would also need to
3652  * allocate data buffer space and this routine would need to be modified to
3653  * copy the data buffer(s) as well.
3654  */
3655 void
3656 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3657 {
3658 	void *pool_ref;
3659 
3660 	if ((src == NULL)
3661 	 || (dest == NULL))
3662 		return;
3663 
3664 	/*
3665 	 * May need to preserve linked list pointers at some point too.
3666 	 */
3667 	pool_ref = dest->io_hdr.pool;
3668 
3669 	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3670 
3671 	dest->io_hdr.pool = pool_ref;
3672 	/*
3673 	 * We need to know that this is an internal copy, and doesn't need
3674 	 * to get passed back to the FETD that allocated it.
3675 	 */
3676 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3677 }
3678 
3679 #ifdef NEEDTOPORT
3680 static void
3681 ctl_update_power_subpage(struct copan_power_subpage *page)
3682 {
3683 	int num_luns, num_partitions, config_type;
3684 	struct ctl_softc *softc;
3685 	cs_BOOL_t aor_present, shelf_50pct_power;
3686 	cs_raidset_personality_t rs_type;
3687 	int max_active_luns;
3688 
3689 	softc = control_softc;
3690 
3691 	/* subtract out the processor LUN */
3692 	num_luns = softc->num_luns - 1;
3693 	/*
3694 	 * Default to 7 LUNs active, which was the only number we allowed
3695 	 * in the past.
3696 	 */
3697 	max_active_luns = 7;
3698 
3699 	num_partitions = config_GetRsPartitionInfo();
3700 	config_type = config_GetConfigType();
3701 	shelf_50pct_power = config_GetShelfPowerMode();
3702 	aor_present = config_IsAorRsPresent();
3703 
3704 	rs_type = ddb_GetRsRaidType(1);
3705 	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3706 	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3707 		EPRINT(0, "Unsupported RS type %d!", rs_type);
3708 	}
3709 
3710 
3711 	page->total_luns = num_luns;
3712 
3713 	switch (config_type) {
3714 	case 40:
3715 		/*
3716 		 * In a 40 drive configuration, it doesn't matter what DC
3717 		 * cards we have, whether we have AOR enabled or not,
3718 		 * partitioning or not, or what type of RAIDset we have.
3719 		 * In that scenario, we can power up every LUN we present
3720 		 * to the user.
3721 		 */
3722 		max_active_luns = num_luns;
3723 
3724 		break;
3725 	case 64:
3726 		if (shelf_50pct_power == CS_FALSE) {
3727 			/* 25% power */
3728 			if (aor_present == CS_TRUE) {
3729 				if (rs_type ==
3730 				     CS_RAIDSET_PERSONALITY_RAID5) {
3731 					max_active_luns = 7;
3732 				} else if (rs_type ==
3733 					 CS_RAIDSET_PERSONALITY_RAID1){
3734 					max_active_luns = 14;
3735 				} else {
3736 					/* XXX KDM now what?? */
3737 				}
3738 			} else {
3739 				if (rs_type ==
3740 				     CS_RAIDSET_PERSONALITY_RAID5) {
3741 					max_active_luns = 8;
3742 				} else if (rs_type ==
3743 					 CS_RAIDSET_PERSONALITY_RAID1){
3744 					max_active_luns = 16;
3745 				} else {
3746 					/* XXX KDM now what?? */
3747 				}
3748 			}
3749 		} else {
3750 			/* 50% power */
3751 			/*
3752 			 * With 50% power in a 64 drive configuration, we
3753 			 * can power all LUNs we present.
3754 			 */
3755 			max_active_luns = num_luns;
3756 		}
3757 		break;
3758 	case 112:
3759 		if (shelf_50pct_power == CS_FALSE) {
3760 			/* 25% power */
3761 			if (aor_present == CS_TRUE) {
3762 				if (rs_type ==
3763 				     CS_RAIDSET_PERSONALITY_RAID5) {
3764 					max_active_luns = 7;
3765 				} else if (rs_type ==
3766 					 CS_RAIDSET_PERSONALITY_RAID1){
3767 					max_active_luns = 14;
3768 				} else {
3769 					/* XXX KDM now what?? */
3770 				}
3771 			} else {
3772 				if (rs_type ==
3773 				     CS_RAIDSET_PERSONALITY_RAID5) {
3774 					max_active_luns = 8;
3775 				} else if (rs_type ==
3776 					 CS_RAIDSET_PERSONALITY_RAID1){
3777 					max_active_luns = 16;
3778 				} else {
3779 					/* XXX KDM now what?? */
3780 				}
3781 			}
3782 		} else {
3783 			/* 50% power */
3784 			if (aor_present == CS_TRUE) {
3785 				if (rs_type ==
3786 				     CS_RAIDSET_PERSONALITY_RAID5) {
3787 					max_active_luns = 14;
3788 				} else if (rs_type ==
3789 					 CS_RAIDSET_PERSONALITY_RAID1){
3790 					/*
3791 					 * We're assuming here that disk
3792 					 * caching is enabled, and so we're
3793 					 * able to power up half of each
3794 					 * LUN, and cache all writes.
3795 					 */
3796 					max_active_luns = num_luns;
3797 				} else {
3798 					/* XXX KDM now what?? */
3799 				}
3800 			} else {
3801 				if (rs_type ==
3802 				     CS_RAIDSET_PERSONALITY_RAID5) {
3803 					max_active_luns = 15;
3804 				} else if (rs_type ==
3805 					 CS_RAIDSET_PERSONALITY_RAID1){
3806 					max_active_luns = 30;
3807 				} else {
3808 					/* XXX KDM now what?? */
3809 				}
3810 			}
3811 		}
3812 		break;
3813 	default:
3814 		/*
3815 		 * In this case, we have an unknown configuration, so we
3816 		 * just use the default from above.
3817 		 */
3818 		break;
3819 	}
3820 
3821 	page->max_active_luns = max_active_luns;
3822 #if 0
3823 	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
3824 	       page->total_luns, page->max_active_luns);
3825 #endif
3826 }
3827 #endif /* NEEDTOPORT */
3828 
3829 /*
3830  * This routine could be used in the future to load default and/or saved
3831  * mode page parameters for a particuar lun.
3832  */
3833 static int
3834 ctl_init_page_index(struct ctl_lun *lun)
3835 {
3836 	int i;
3837 	struct ctl_page_index *page_index;
3838 	struct ctl_softc *softc;
3839 
3840 	memcpy(&lun->mode_pages.index, page_index_template,
3841 	       sizeof(page_index_template));
3842 
3843 	softc = lun->ctl_softc;
3844 
3845 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3846 
3847 		page_index = &lun->mode_pages.index[i];
3848 		/*
3849 		 * If this is a disk-only mode page, there's no point in
3850 		 * setting it up.  For some pages, we have to have some
3851 		 * basic information about the disk in order to calculate the
3852 		 * mode page data.
3853 		 */
3854 		if ((lun->be_lun->lun_type != T_DIRECT)
3855 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3856 			continue;
3857 
3858 		switch (page_index->page_code & SMPH_PC_MASK) {
3859 		case SMS_FORMAT_DEVICE_PAGE: {
3860 			struct scsi_format_page *format_page;
3861 
3862 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3863 				panic("subpage is incorrect!");
3864 
3865 			/*
3866 			 * Sectors per track are set above.  Bytes per
3867 			 * sector need to be set here on a per-LUN basis.
3868 			 */
3869 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3870 			       &format_page_default,
3871 			       sizeof(format_page_default));
3872 			memcpy(&lun->mode_pages.format_page[
3873 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3874 			       sizeof(format_page_changeable));
3875 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3876 			       &format_page_default,
3877 			       sizeof(format_page_default));
3878 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3879 			       &format_page_default,
3880 			       sizeof(format_page_default));
3881 
3882 			format_page = &lun->mode_pages.format_page[
3883 				CTL_PAGE_CURRENT];
3884 			scsi_ulto2b(lun->be_lun->blocksize,
3885 				    format_page->bytes_per_sector);
3886 
3887 			format_page = &lun->mode_pages.format_page[
3888 				CTL_PAGE_DEFAULT];
3889 			scsi_ulto2b(lun->be_lun->blocksize,
3890 				    format_page->bytes_per_sector);
3891 
3892 			format_page = &lun->mode_pages.format_page[
3893 				CTL_PAGE_SAVED];
3894 			scsi_ulto2b(lun->be_lun->blocksize,
3895 				    format_page->bytes_per_sector);
3896 
3897 			page_index->page_data =
3898 				(uint8_t *)lun->mode_pages.format_page;
3899 			break;
3900 		}
3901 		case SMS_RIGID_DISK_PAGE: {
3902 			struct scsi_rigid_disk_page *rigid_disk_page;
3903 			uint32_t sectors_per_cylinder;
3904 			uint64_t cylinders;
3905 #ifndef	__XSCALE__
3906 			int shift;
3907 #endif /* !__XSCALE__ */
3908 
3909 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3910 				panic("invalid subpage value %d",
3911 				      page_index->subpage);
3912 
3913 			/*
3914 			 * Rotation rate and sectors per track are set
3915 			 * above.  We calculate the cylinders here based on
3916 			 * capacity.  Due to the number of heads and
3917 			 * sectors per track we're using, smaller arrays
3918 			 * may turn out to have 0 cylinders.  Linux and
3919 			 * FreeBSD don't pay attention to these mode pages
3920 			 * to figure out capacity, but Solaris does.  It
3921 			 * seems to deal with 0 cylinders just fine, and
3922 			 * works out a fake geometry based on the capacity.
3923 			 */
3924 			memcpy(&lun->mode_pages.rigid_disk_page[
3925 			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
3926 			       sizeof(rigid_disk_page_default));
3927 			memcpy(&lun->mode_pages.rigid_disk_page[
3928 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3929 			       sizeof(rigid_disk_page_changeable));
3930 			memcpy(&lun->mode_pages.rigid_disk_page[
3931 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3932 			       sizeof(rigid_disk_page_default));
3933 			memcpy(&lun->mode_pages.rigid_disk_page[
3934 			       CTL_PAGE_SAVED], &rigid_disk_page_default,
3935 			       sizeof(rigid_disk_page_default));
3936 
3937 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3938 				CTL_DEFAULT_HEADS;
3939 
3940 			/*
3941 			 * The divide method here will be more accurate,
3942 			 * probably, but results in floating point being
3943 			 * used in the kernel on i386 (__udivdi3()).  On the
3944 			 * XScale, though, __udivdi3() is implemented in
3945 			 * software.
3946 			 *
3947 			 * The shift method for cylinder calculation is
3948 			 * accurate if sectors_per_cylinder is a power of
3949 			 * 2.  Otherwise it might be slightly off -- you
3950 			 * might have a bit of a truncation problem.
3951 			 */
3952 #ifdef	__XSCALE__
3953 			cylinders = (lun->be_lun->maxlba + 1) /
3954 				sectors_per_cylinder;
3955 #else
3956 			for (shift = 31; shift > 0; shift--) {
3957 				if (sectors_per_cylinder & (1 << shift))
3958 					break;
3959 			}
3960 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3961 #endif
3962 
3963 			/*
3964 			 * We've basically got 3 bytes, or 24 bits for the
3965 			 * cylinder size in the mode page.  If we're over,
3966 			 * just round down to 2^24.
3967 			 */
3968 			if (cylinders > 0xffffff)
3969 				cylinders = 0xffffff;
3970 
3971 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3972 				CTL_PAGE_CURRENT];
3973 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3974 
3975 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3976 				CTL_PAGE_DEFAULT];
3977 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3978 
3979 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3980 				CTL_PAGE_SAVED];
3981 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3982 
3983 			page_index->page_data =
3984 				(uint8_t *)lun->mode_pages.rigid_disk_page;
3985 			break;
3986 		}
3987 		case SMS_CACHING_PAGE: {
3988 
3989 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3990 				panic("invalid subpage value %d",
3991 				      page_index->subpage);
3992 			/*
3993 			 * Defaults should be okay here, no calculations
3994 			 * needed.
3995 			 */
3996 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3997 			       &caching_page_default,
3998 			       sizeof(caching_page_default));
3999 			memcpy(&lun->mode_pages.caching_page[
4000 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4001 			       sizeof(caching_page_changeable));
4002 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4003 			       &caching_page_default,
4004 			       sizeof(caching_page_default));
4005 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4006 			       &caching_page_default,
4007 			       sizeof(caching_page_default));
4008 			page_index->page_data =
4009 				(uint8_t *)lun->mode_pages.caching_page;
4010 			break;
4011 		}
4012 		case SMS_CONTROL_MODE_PAGE: {
4013 
4014 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4015 				panic("invalid subpage value %d",
4016 				      page_index->subpage);
4017 
4018 			/*
4019 			 * Defaults should be okay here, no calculations
4020 			 * needed.
4021 			 */
4022 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4023 			       &control_page_default,
4024 			       sizeof(control_page_default));
4025 			memcpy(&lun->mode_pages.control_page[
4026 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4027 			       sizeof(control_page_changeable));
4028 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4029 			       &control_page_default,
4030 			       sizeof(control_page_default));
4031 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4032 			       &control_page_default,
4033 			       sizeof(control_page_default));
4034 			page_index->page_data =
4035 				(uint8_t *)lun->mode_pages.control_page;
4036 			break;
4037 
4038 		}
4039 		case SMS_VENDOR_SPECIFIC_PAGE:{
4040 			switch (page_index->subpage) {
4041 			case PWR_SUBPAGE_CODE: {
4042 				struct copan_power_subpage *current_page,
4043 							   *saved_page;
4044 
4045 				memcpy(&lun->mode_pages.power_subpage[
4046 				       CTL_PAGE_CURRENT],
4047 				       &power_page_default,
4048 				       sizeof(power_page_default));
4049 				memcpy(&lun->mode_pages.power_subpage[
4050 				       CTL_PAGE_CHANGEABLE],
4051 				       &power_page_changeable,
4052 				       sizeof(power_page_changeable));
4053 				memcpy(&lun->mode_pages.power_subpage[
4054 				       CTL_PAGE_DEFAULT],
4055 				       &power_page_default,
4056 				       sizeof(power_page_default));
4057 				memcpy(&lun->mode_pages.power_subpage[
4058 				       CTL_PAGE_SAVED],
4059 				       &power_page_default,
4060 				       sizeof(power_page_default));
4061 				page_index->page_data =
4062 				    (uint8_t *)lun->mode_pages.power_subpage;
4063 
4064 				current_page = (struct copan_power_subpage *)
4065 					(page_index->page_data +
4066 					 (page_index->page_len *
4067 					  CTL_PAGE_CURRENT));
4068 			        saved_page = (struct copan_power_subpage *)
4069 				        (page_index->page_data +
4070 					 (page_index->page_len *
4071 					  CTL_PAGE_SAVED));
4072 				break;
4073 			}
4074 			case APS_SUBPAGE_CODE: {
4075 				struct copan_aps_subpage *current_page,
4076 							 *saved_page;
4077 
4078 				// This gets set multiple times but
4079 				// it should always be the same. It's
4080 				// only done during init so who cares.
4081 				index_to_aps_page = i;
4082 
4083 				memcpy(&lun->mode_pages.aps_subpage[
4084 				       CTL_PAGE_CURRENT],
4085 				       &aps_page_default,
4086 				       sizeof(aps_page_default));
4087 				memcpy(&lun->mode_pages.aps_subpage[
4088 				       CTL_PAGE_CHANGEABLE],
4089 				       &aps_page_changeable,
4090 				       sizeof(aps_page_changeable));
4091 				memcpy(&lun->mode_pages.aps_subpage[
4092 				       CTL_PAGE_DEFAULT],
4093 				       &aps_page_default,
4094 				       sizeof(aps_page_default));
4095 				memcpy(&lun->mode_pages.aps_subpage[
4096 				       CTL_PAGE_SAVED],
4097 				       &aps_page_default,
4098 				       sizeof(aps_page_default));
4099 				page_index->page_data =
4100 					(uint8_t *)lun->mode_pages.aps_subpage;
4101 
4102 				current_page = (struct copan_aps_subpage *)
4103 					(page_index->page_data +
4104 					 (page_index->page_len *
4105 					  CTL_PAGE_CURRENT));
4106 				saved_page = (struct copan_aps_subpage *)
4107 					(page_index->page_data +
4108 					 (page_index->page_len *
4109 					  CTL_PAGE_SAVED));
4110 				break;
4111 			}
4112 			case DBGCNF_SUBPAGE_CODE: {
4113 				struct copan_debugconf_subpage *current_page,
4114 							       *saved_page;
4115 
4116 				memcpy(&lun->mode_pages.debugconf_subpage[
4117 				       CTL_PAGE_CURRENT],
4118 				       &debugconf_page_default,
4119 				       sizeof(debugconf_page_default));
4120 				memcpy(&lun->mode_pages.debugconf_subpage[
4121 				       CTL_PAGE_CHANGEABLE],
4122 				       &debugconf_page_changeable,
4123 				       sizeof(debugconf_page_changeable));
4124 				memcpy(&lun->mode_pages.debugconf_subpage[
4125 				       CTL_PAGE_DEFAULT],
4126 				       &debugconf_page_default,
4127 				       sizeof(debugconf_page_default));
4128 				memcpy(&lun->mode_pages.debugconf_subpage[
4129 				       CTL_PAGE_SAVED],
4130 				       &debugconf_page_default,
4131 				       sizeof(debugconf_page_default));
4132 				page_index->page_data =
4133 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4134 
4135 				current_page = (struct copan_debugconf_subpage *)
4136 					(page_index->page_data +
4137 					 (page_index->page_len *
4138 					  CTL_PAGE_CURRENT));
4139 				saved_page = (struct copan_debugconf_subpage *)
4140 					(page_index->page_data +
4141 					 (page_index->page_len *
4142 					  CTL_PAGE_SAVED));
4143 				break;
4144 			}
4145 			default:
4146 				panic("invalid subpage value %d",
4147 				      page_index->subpage);
4148 				break;
4149 			}
4150    			break;
4151 		}
4152 		default:
4153 			panic("invalid page value %d",
4154 			      page_index->page_code & SMPH_PC_MASK);
4155 			break;
4156     	}
4157 	}
4158 
4159 	return (CTL_RETVAL_COMPLETE);
4160 }
4161 
4162 /*
4163  * LUN allocation.
4164  *
4165  * Requirements:
4166  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4167  *   wants us to allocate the LUN and he can block.
4168  * - ctl_softc is always set
4169  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4170  *
4171  * Returns 0 for success, non-zero (errno) for failure.
4172  */
4173 static int
4174 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4175 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4176 {
4177 	struct ctl_lun *nlun, *lun;
4178 	struct ctl_frontend *fe;
4179 	int lun_number, i;
4180 
4181 	if (be_lun == NULL)
4182 		return (EINVAL);
4183 
4184 	/*
4185 	 * We currently only support Direct Access or Processor LUN types.
4186 	 */
4187 	switch (be_lun->lun_type) {
4188 	case T_DIRECT:
4189 		break;
4190 	case T_PROCESSOR:
4191 		break;
4192 	case T_SEQUENTIAL:
4193 	case T_CHANGER:
4194 	default:
4195 		be_lun->lun_config_status(be_lun->be_lun,
4196 					  CTL_LUN_CONFIG_FAILURE);
4197 		break;
4198 	}
4199 	if (ctl_lun == NULL) {
4200 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4201 		if (lun == NULL) {
4202 			be_lun->lun_config_status(lun->be_lun->be_lun,
4203 						  CTL_LUN_CONFIG_FAILURE);
4204 			return (-ENOMEM);
4205 		}
4206 		lun->flags = CTL_LUN_MALLOCED;
4207 	} else
4208 		lun = ctl_lun;
4209 
4210 	memset(lun, 0, sizeof(*lun));
4211 
4212 	mtx_lock(&ctl_softc->ctl_lock);
4213 	/*
4214 	 * See if the caller requested a particular LUN number.  If so, see
4215 	 * if it is available.  Otherwise, allocate the first available LUN.
4216 	 */
4217 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4218 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4219 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4220 			mtx_unlock(&ctl_softc->ctl_lock);
4221 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4222 				printf("ctl: requested LUN ID %d is higher "
4223 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4224 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4225 			} else {
4226 				/*
4227 				 * XXX KDM return an error, or just assign
4228 				 * another LUN ID in this case??
4229 				 */
4230 				printf("ctl: requested LUN ID %d is already "
4231 				       "in use\n", be_lun->req_lun_id);
4232 			}
4233 			if (lun->flags & CTL_LUN_MALLOCED)
4234 				free(lun, M_CTL);
4235 			be_lun->lun_config_status(be_lun->be_lun,
4236 						  CTL_LUN_CONFIG_FAILURE);
4237 			return (ENOSPC);
4238 		}
4239 		lun_number = be_lun->req_lun_id;
4240 	} else {
4241 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4242 		if (lun_number == -1) {
4243 			mtx_unlock(&ctl_softc->ctl_lock);
4244 			printf("ctl: can't allocate LUN on target %ju, out of "
4245 			       "LUNs\n", (uintmax_t)target_id.id);
4246 			if (lun->flags & CTL_LUN_MALLOCED)
4247 				free(lun, M_CTL);
4248 			be_lun->lun_config_status(be_lun->be_lun,
4249 						  CTL_LUN_CONFIG_FAILURE);
4250 			return (ENOSPC);
4251 		}
4252 	}
4253 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4254 
4255 	lun->target = target_id;
4256 	lun->lun = lun_number;
4257 	lun->be_lun = be_lun;
4258 	/*
4259 	 * The processor LUN is always enabled.  Disk LUNs come on line
4260 	 * disabled, and must be enabled by the backend.
4261 	 */
4262 	lun->flags = CTL_LUN_DISABLED;
4263 	lun->backend = be_lun->be;
4264 	be_lun->ctl_lun = lun;
4265 	be_lun->lun_id = lun_number;
4266 	atomic_add_int(&be_lun->be->num_luns, 1);
4267 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4268 		lun->flags |= CTL_LUN_STOPPED;
4269 
4270 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4271 		lun->flags |= CTL_LUN_INOPERABLE;
4272 
4273 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4274 		lun->flags |= CTL_LUN_PRIMARY_SC;
4275 
4276 	lun->ctl_softc = ctl_softc;
4277 	TAILQ_INIT(&lun->ooa_queue);
4278 	TAILQ_INIT(&lun->blocked_queue);
4279 	STAILQ_INIT(&lun->error_list);
4280 
4281 	/*
4282 	 * Initialize the mode page index.
4283 	 */
4284 	ctl_init_page_index(lun);
4285 
4286 	/*
4287 	 * Set the poweron UA for all initiators on this LUN only.
4288 	 */
4289 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4290 		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4291 
4292 	/*
4293 	 * Now, before we insert this lun on the lun list, set the lun
4294 	 * inventory changed UA for all other luns.
4295 	 */
4296 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4297 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4298 			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4299 		}
4300 	}
4301 
4302 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4303 
4304 	ctl_softc->ctl_luns[lun_number] = lun;
4305 
4306 	ctl_softc->num_luns++;
4307 
4308 	/* Setup statistics gathering */
4309 	lun->stats.device_type = be_lun->lun_type;
4310 	lun->stats.lun_number = lun_number;
4311 	if (lun->stats.device_type == T_DIRECT)
4312 		lun->stats.blocksize = be_lun->blocksize;
4313 	else
4314 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4315 	for (i = 0;i < CTL_MAX_PORTS;i++)
4316 		lun->stats.ports[i].targ_port = i;
4317 
4318 	mtx_unlock(&ctl_softc->ctl_lock);
4319 
4320 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4321 
4322 	/*
4323 	 * Run through each registered FETD and bring it online if it isn't
4324 	 * already.  Enable the target ID if it hasn't been enabled, and
4325 	 * enable this particular LUN.
4326 	 */
4327 	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4328 		int retval;
4329 
4330 		/*
4331 		 * XXX KDM this only works for ONE TARGET ID.  We'll need
4332 		 * to do things differently if we go to a multiple target
4333 		 * ID scheme.
4334 		 */
4335 		if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) == 0) {
4336 
4337 			retval = fe->targ_enable(fe->targ_lun_arg, target_id);
4338 			if (retval != 0) {
4339 				printf("ctl_alloc_lun: FETD %s port %d "
4340 				       "returned error %d for targ_enable on "
4341 				       "target %ju\n", fe->port_name,
4342 				       fe->targ_port, retval,
4343 				       (uintmax_t)target_id.id);
4344 			} else
4345 				fe->status |= CTL_PORT_STATUS_TARG_ONLINE;
4346 		}
4347 
4348 		retval = fe->lun_enable(fe->targ_lun_arg, target_id,lun_number);
4349 		if (retval != 0) {
4350 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4351 			       "%d for lun_enable on target %ju lun %d\n",
4352 			       fe->port_name, fe->targ_port, retval,
4353 			       (uintmax_t)target_id.id, lun_number);
4354 		} else
4355 			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4356 	}
4357 	return (0);
4358 }
4359 
4360 /*
4361  * Delete a LUN.
4362  * Assumptions:
4363  * - caller holds ctl_softc->ctl_lock.
4364  * - LUN has already been marked invalid and any pending I/O has been taken
4365  *   care of.
4366  */
4367 static int
4368 ctl_free_lun(struct ctl_lun *lun)
4369 {
4370 	struct ctl_softc *softc;
4371 #if 0
4372 	struct ctl_frontend *fe;
4373 #endif
4374 	struct ctl_lun *nlun;
4375 	union ctl_io *io, *next_io;
4376 	int i;
4377 
4378 	softc = lun->ctl_softc;
4379 
4380 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4381 
4382 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4383 
4384 	softc->ctl_luns[lun->lun] = NULL;
4385 
4386 	if (TAILQ_FIRST(&lun->ooa_queue) != NULL) {
4387 		printf("ctl_free_lun: aieee!! freeing a LUN with "
4388 		       "outstanding I/O!!\n");
4389 	}
4390 
4391 	/*
4392 	 * If we have anything pending on the RtR queue, remove it.
4393 	 */
4394 	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue); io != NULL;
4395 	     io = next_io) {
4396 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
4397 		if ((io->io_hdr.nexus.targ_target.id == lun->target.id)
4398 		 && (io->io_hdr.nexus.targ_lun == lun->lun))
4399 			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
4400 				      ctl_io_hdr, links);
4401 	}
4402 
4403 	/*
4404 	 * Then remove everything from the blocked queue.
4405 	 */
4406 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue); io != NULL;
4407 	     io = next_io) {
4408 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,blocked_links);
4409 		TAILQ_REMOVE(&lun->blocked_queue, &io->io_hdr, blocked_links);
4410 		io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
4411 	}
4412 
4413 	/*
4414 	 * Now clear out the OOA queue, and free all the I/O.
4415 	 * XXX KDM should we notify the FETD here?  We probably need to
4416 	 * quiesce the LUN before deleting it.
4417 	 */
4418 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); io != NULL;
4419 	     io = next_io) {
4420 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, ooa_links);
4421 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
4422 		ctl_free_io_internal(io, /*have_lock*/ 1);
4423 	}
4424 
4425 	softc->num_luns--;
4426 
4427 	/*
4428 	 * XXX KDM this scheme only works for a single target/multiple LUN
4429 	 * setup.  It needs to be revamped for a multiple target scheme.
4430 	 *
4431 	 * XXX KDM this results in fe->lun_disable() getting called twice,
4432 	 * once when ctl_disable_lun() is called, and a second time here.
4433 	 * We really need to re-think the LUN disable semantics.  There
4434 	 * should probably be several steps/levels to LUN removal:
4435 	 *  - disable
4436 	 *  - invalidate
4437 	 *  - free
4438  	 *
4439 	 * Right now we only have a disable method when communicating to
4440 	 * the front end ports, at least for individual LUNs.
4441 	 */
4442 #if 0
4443 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
4444 		int retval;
4445 
4446 		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4447 					 lun->lun);
4448 		if (retval != 0) {
4449 			printf("ctl_free_lun: FETD %s port %d returned error "
4450 			       "%d for lun_disable on target %ju lun %jd\n",
4451 			       fe->port_name, fe->targ_port, retval,
4452 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4453 		}
4454 
4455 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4456 			fe->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4457 
4458 			retval = fe->targ_disable(fe->targ_lun_arg,lun->target);
4459 			if (retval != 0) {
4460 				printf("ctl_free_lun: FETD %s port %d "
4461 				       "returned error %d for targ_disable on "
4462 				       "target %ju\n", fe->port_name,
4463 				       fe->targ_port, retval,
4464 				       (uintmax_t)lun->target.id);
4465 			} else
4466 				fe->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4467 
4468 			if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4469 				continue;
4470 
4471 #if 0
4472 			fe->port_offline(fe->onoff_arg);
4473 			fe->status &= ~CTL_PORT_STATUS_ONLINE;
4474 #endif
4475 		}
4476 	}
4477 #endif
4478 
4479 	/*
4480 	 * Tell the backend to free resources, if this LUN has a backend.
4481 	 */
4482 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4483 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4484 
4485 	if (lun->flags & CTL_LUN_MALLOCED)
4486 		free(lun, M_CTL);
4487 
4488 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4489 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4490 			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4491 		}
4492 	}
4493 
4494 	return (0);
4495 }
4496 
4497 static void
4498 ctl_create_lun(struct ctl_be_lun *be_lun)
4499 {
4500 	struct ctl_softc *ctl_softc;
4501 
4502 	ctl_softc = control_softc;
4503 
4504 	/*
4505 	 * ctl_alloc_lun() should handle all potential failure cases.
4506 	 */
4507 	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4508 }
4509 
4510 int
4511 ctl_add_lun(struct ctl_be_lun *be_lun)
4512 {
4513 	struct ctl_softc *ctl_softc;
4514 
4515 	ctl_softc = control_softc;
4516 
4517 	mtx_lock(&ctl_softc->ctl_lock);
4518 	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4519 	mtx_unlock(&ctl_softc->ctl_lock);
4520 
4521 	ctl_wakeup_thread();
4522 
4523 	return (0);
4524 }
4525 
4526 int
4527 ctl_enable_lun(struct ctl_be_lun *be_lun)
4528 {
4529 	struct ctl_softc *ctl_softc;
4530 	struct ctl_frontend *fe, *nfe;
4531 	struct ctl_lun *lun;
4532 	int retval;
4533 
4534 	ctl_softc = control_softc;
4535 
4536 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4537 
4538 	mtx_lock(&ctl_softc->ctl_lock);
4539 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4540 		/*
4541 		 * eh?  Why did we get called if the LUN is already
4542 		 * enabled?
4543 		 */
4544 		mtx_unlock(&ctl_softc->ctl_lock);
4545 		return (0);
4546 	}
4547 	lun->flags &= ~CTL_LUN_DISABLED;
4548 
4549 	for (fe = STAILQ_FIRST(&ctl_softc->fe_list); fe != NULL; fe = nfe) {
4550 		nfe = STAILQ_NEXT(fe, links);
4551 
4552 		/*
4553 		 * Drop the lock while we call the FETD's enable routine.
4554 		 * This can lead to a callback into CTL (at least in the
4555 		 * case of the internal initiator frontend.
4556 		 */
4557 		mtx_unlock(&ctl_softc->ctl_lock);
4558 		retval = fe->lun_enable(fe->targ_lun_arg, lun->target,lun->lun);
4559 		mtx_lock(&ctl_softc->ctl_lock);
4560 		if (retval != 0) {
4561 			printf("%s: FETD %s port %d returned error "
4562 			       "%d for lun_enable on target %ju lun %jd\n",
4563 			       __func__, fe->port_name, fe->targ_port, retval,
4564 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4565 		}
4566 #if 0
4567 		 else {
4568             /* NOTE:  TODO:  why does lun enable affect port status? */
4569 			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4570 		}
4571 #endif
4572 	}
4573 
4574 	mtx_unlock(&ctl_softc->ctl_lock);
4575 
4576 	return (0);
4577 }
4578 
4579 int
4580 ctl_disable_lun(struct ctl_be_lun *be_lun)
4581 {
4582 	struct ctl_softc *ctl_softc;
4583 	struct ctl_frontend *fe;
4584 	struct ctl_lun *lun;
4585 	int retval;
4586 
4587 	ctl_softc = control_softc;
4588 
4589 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4590 
4591 	mtx_lock(&ctl_softc->ctl_lock);
4592 
4593 	if (lun->flags & CTL_LUN_DISABLED) {
4594 		mtx_unlock(&ctl_softc->ctl_lock);
4595 		return (0);
4596 	}
4597 	lun->flags |= CTL_LUN_DISABLED;
4598 
4599 	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4600 		mtx_unlock(&ctl_softc->ctl_lock);
4601 		/*
4602 		 * Drop the lock before we call the frontend's disable
4603 		 * routine, to avoid lock order reversals.
4604 		 *
4605 		 * XXX KDM what happens if the frontend list changes while
4606 		 * we're traversing it?  It's unlikely, but should be handled.
4607 		 */
4608 		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4609 					 lun->lun);
4610 		mtx_lock(&ctl_softc->ctl_lock);
4611 		if (retval != 0) {
4612 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4613 			       "%d for lun_disable on target %ju lun %jd\n",
4614 			       fe->port_name, fe->targ_port, retval,
4615 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4616 		}
4617 	}
4618 
4619 	mtx_unlock(&ctl_softc->ctl_lock);
4620 
4621 	return (0);
4622 }
4623 
4624 int
4625 ctl_start_lun(struct ctl_be_lun *be_lun)
4626 {
4627 	struct ctl_softc *ctl_softc;
4628 	struct ctl_lun *lun;
4629 
4630 	ctl_softc = control_softc;
4631 
4632 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4633 
4634 	mtx_lock(&ctl_softc->ctl_lock);
4635 	lun->flags &= ~CTL_LUN_STOPPED;
4636 	mtx_unlock(&ctl_softc->ctl_lock);
4637 
4638 	return (0);
4639 }
4640 
4641 int
4642 ctl_stop_lun(struct ctl_be_lun *be_lun)
4643 {
4644 	struct ctl_softc *ctl_softc;
4645 	struct ctl_lun *lun;
4646 
4647 	ctl_softc = control_softc;
4648 
4649 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4650 
4651 	mtx_lock(&ctl_softc->ctl_lock);
4652 	lun->flags |= CTL_LUN_STOPPED;
4653 	mtx_unlock(&ctl_softc->ctl_lock);
4654 
4655 	return (0);
4656 }
4657 
4658 int
4659 ctl_lun_offline(struct ctl_be_lun *be_lun)
4660 {
4661 	struct ctl_softc *ctl_softc;
4662 	struct ctl_lun *lun;
4663 
4664 	ctl_softc = control_softc;
4665 
4666 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4667 
4668 	mtx_lock(&ctl_softc->ctl_lock);
4669 	lun->flags |= CTL_LUN_OFFLINE;
4670 	mtx_unlock(&ctl_softc->ctl_lock);
4671 
4672 	return (0);
4673 }
4674 
4675 int
4676 ctl_lun_online(struct ctl_be_lun *be_lun)
4677 {
4678 	struct ctl_softc *ctl_softc;
4679 	struct ctl_lun *lun;
4680 
4681 	ctl_softc = control_softc;
4682 
4683 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4684 
4685 	mtx_lock(&ctl_softc->ctl_lock);
4686 	lun->flags &= ~CTL_LUN_OFFLINE;
4687 	mtx_unlock(&ctl_softc->ctl_lock);
4688 
4689 	return (0);
4690 }
4691 
4692 int
4693 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4694 {
4695 	struct ctl_softc *ctl_softc;
4696 	struct ctl_lun *lun;
4697 
4698 	ctl_softc = control_softc;
4699 
4700 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4701 
4702 	mtx_lock(&ctl_softc->ctl_lock);
4703 
4704 	/*
4705 	 * The LUN needs to be disabled before it can be marked invalid.
4706 	 */
4707 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4708 		mtx_unlock(&ctl_softc->ctl_lock);
4709 		return (-1);
4710 	}
4711 	/*
4712 	 * Mark the LUN invalid.
4713 	 */
4714 	lun->flags |= CTL_LUN_INVALID;
4715 
4716 	/*
4717 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4718 	 * If we have something in the OOA queue, we'll free it when the
4719 	 * last I/O completes.
4720 	 */
4721 	if (TAILQ_FIRST(&lun->ooa_queue) == NULL)
4722 		ctl_free_lun(lun);
4723 	mtx_unlock(&ctl_softc->ctl_lock);
4724 
4725 	return (0);
4726 }
4727 
4728 int
4729 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4730 {
4731 	struct ctl_softc *ctl_softc;
4732 	struct ctl_lun *lun;
4733 
4734 	ctl_softc = control_softc;
4735 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4736 
4737 	mtx_lock(&ctl_softc->ctl_lock);
4738 	lun->flags |= CTL_LUN_INOPERABLE;
4739 	mtx_unlock(&ctl_softc->ctl_lock);
4740 
4741 	return (0);
4742 }
4743 
4744 int
4745 ctl_lun_operable(struct ctl_be_lun *be_lun)
4746 {
4747 	struct ctl_softc *ctl_softc;
4748 	struct ctl_lun *lun;
4749 
4750 	ctl_softc = control_softc;
4751 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4752 
4753 	mtx_lock(&ctl_softc->ctl_lock);
4754 	lun->flags &= ~CTL_LUN_INOPERABLE;
4755 	mtx_unlock(&ctl_softc->ctl_lock);
4756 
4757 	return (0);
4758 }
4759 
4760 int
4761 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
4762 		   int lock)
4763 {
4764 	struct ctl_softc *softc;
4765 	struct ctl_lun *lun;
4766 	struct copan_aps_subpage *current_sp;
4767 	struct ctl_page_index *page_index;
4768 	int i;
4769 
4770 	softc = control_softc;
4771 
4772 	mtx_lock(&softc->ctl_lock);
4773 
4774 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4775 
4776 	page_index = NULL;
4777 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4778 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
4779 		     APS_PAGE_CODE)
4780 			continue;
4781 
4782 		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
4783 			continue;
4784 		page_index = &lun->mode_pages.index[i];
4785 	}
4786 
4787 	if (page_index == NULL) {
4788 		mtx_unlock(&softc->ctl_lock);
4789 		printf("%s: APS subpage not found for lun %ju!\n", __func__,
4790 		       (uintmax_t)lun->lun);
4791 		return (1);
4792 	}
4793 #if 0
4794 	if ((softc->aps_locked_lun != 0)
4795 	 && (softc->aps_locked_lun != lun->lun)) {
4796 		printf("%s: attempt to lock LUN %llu when %llu is already "
4797 		       "locked\n");
4798 		mtx_unlock(&softc->ctl_lock);
4799 		return (1);
4800 	}
4801 #endif
4802 
4803 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
4804 		(page_index->page_len * CTL_PAGE_CURRENT));
4805 
4806 	if (lock != 0) {
4807 		current_sp->lock_active = APS_LOCK_ACTIVE;
4808 		softc->aps_locked_lun = lun->lun;
4809 	} else {
4810 		current_sp->lock_active = 0;
4811 		softc->aps_locked_lun = 0;
4812 	}
4813 
4814 
4815 	/*
4816 	 * If we're in HA mode, try to send the lock message to the other
4817 	 * side.
4818 	 */
4819 	if (ctl_is_single == 0) {
4820 		int isc_retval;
4821 		union ctl_ha_msg lock_msg;
4822 
4823 		lock_msg.hdr.nexus = *nexus;
4824 		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
4825 		if (lock != 0)
4826 			lock_msg.aps.lock_flag = 1;
4827 		else
4828 			lock_msg.aps.lock_flag = 0;
4829 		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
4830 					 sizeof(lock_msg), 0);
4831 		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
4832 			printf("%s: APS (lock=%d) error returned from "
4833 			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
4834 			mtx_unlock(&softc->ctl_lock);
4835 			return (1);
4836 		}
4837 	}
4838 
4839 	mtx_unlock(&softc->ctl_lock);
4840 
4841 	return (0);
4842 }
4843 
4844 void
4845 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4846 {
4847 	struct ctl_lun *lun;
4848 	struct ctl_softc *softc;
4849 	int i;
4850 
4851 	softc = control_softc;
4852 
4853 	mtx_lock(&softc->ctl_lock);
4854 
4855 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4856 
4857 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4858 		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
4859 
4860 	mtx_unlock(&softc->ctl_lock);
4861 }
4862 
4863 /*
4864  * Backend "memory move is complete" callback for requests that never
4865  * make it down to say RAIDCore's configuration code.
4866  */
4867 int
4868 ctl_config_move_done(union ctl_io *io)
4869 {
4870 	int retval;
4871 
4872 	retval = CTL_RETVAL_COMPLETE;
4873 
4874 
4875 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4876 	/*
4877 	 * XXX KDM this shouldn't happen, but what if it does?
4878 	 */
4879 	if (io->io_hdr.io_type != CTL_IO_SCSI)
4880 		panic("I/O type isn't CTL_IO_SCSI!");
4881 
4882 	if ((io->io_hdr.port_status == 0)
4883 	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4884 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
4885 		io->io_hdr.status = CTL_SUCCESS;
4886 	else if ((io->io_hdr.port_status != 0)
4887 	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4888 	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
4889 		/*
4890 		 * For hardware error sense keys, the sense key
4891 		 * specific value is defined to be a retry count,
4892 		 * but we use it to pass back an internal FETD
4893 		 * error code.  XXX KDM  Hopefully the FETD is only
4894 		 * using 16 bits for an error code, since that's
4895 		 * all the space we have in the sks field.
4896 		 */
4897 		ctl_set_internal_failure(&io->scsiio,
4898 					 /*sks_valid*/ 1,
4899 					 /*retry_count*/
4900 					 io->io_hdr.port_status);
4901 		free(io->scsiio.kern_data_ptr, M_CTL);
4902 		ctl_done(io);
4903 		goto bailout;
4904 	}
4905 
4906 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
4907 	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
4908 	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4909 		/*
4910 		 * XXX KDM just assuming a single pointer here, and not a
4911 		 * S/G list.  If we start using S/G lists for config data,
4912 		 * we'll need to know how to clean them up here as well.
4913 		 */
4914 		free(io->scsiio.kern_data_ptr, M_CTL);
4915 		/* Hopefully the user has already set the status... */
4916 		ctl_done(io);
4917 	} else {
4918 		/*
4919 		 * XXX KDM now we need to continue data movement.  Some
4920 		 * options:
4921 		 * - call ctl_scsiio() again?  We don't do this for data
4922 		 *   writes, because for those at least we know ahead of
4923 		 *   time where the write will go and how long it is.  For
4924 		 *   config writes, though, that information is largely
4925 		 *   contained within the write itself, thus we need to
4926 		 *   parse out the data again.
4927 		 *
4928 		 * - Call some other function once the data is in?
4929 		 */
4930 
4931 		/*
4932 		 * XXX KDM call ctl_scsiio() again for now, and check flag
4933 		 * bits to see whether we're allocated or not.
4934 		 */
4935 		retval = ctl_scsiio(&io->scsiio);
4936 	}
4937 bailout:
4938 	return (retval);
4939 }
4940 
4941 /*
4942  * This gets called by a backend driver when it is done with a
4943  * configuration write.
4944  */
4945 void
4946 ctl_config_write_done(union ctl_io *io)
4947 {
4948 	/*
4949 	 * If the IO_CONT flag is set, we need to call the supplied
4950 	 * function to continue processing the I/O, instead of completing
4951 	 * the I/O just yet.
4952 	 *
4953 	 * If there is an error, though, we don't want to keep processing.
4954 	 * Instead, just send status back to the initiator.
4955 	 */
4956 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
4957 	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
4958 	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
4959 		io->scsiio.io_cont(io);
4960 		return;
4961 	}
4962 	/*
4963 	 * Since a configuration write can be done for commands that actually
4964 	 * have data allocated, like write buffer, and commands that have
4965 	 * no data, like start/stop unit, we need to check here.
4966 	 */
4967 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
4968 		free(io->scsiio.kern_data_ptr, M_CTL);
4969 	ctl_done(io);
4970 }
4971 
4972 /*
4973  * SCSI release command.
4974  */
4975 int
4976 ctl_scsi_release(struct ctl_scsiio *ctsio)
4977 {
4978 	int length, longid, thirdparty_id, resv_id;
4979 	struct ctl_softc *ctl_softc;
4980 	struct ctl_lun *lun;
4981 
4982 	length = 0;
4983 	resv_id = 0;
4984 
4985 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4986 
4987 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4988 	ctl_softc = control_softc;
4989 
4990 	switch (ctsio->cdb[0]) {
4991 	case RELEASE: {
4992 		struct scsi_release *cdb;
4993 
4994 		cdb = (struct scsi_release *)ctsio->cdb;
4995 		if ((cdb->byte2 & 0x1f) != 0) {
4996 			ctl_set_invalid_field(ctsio,
4997 					      /*sks_valid*/ 1,
4998 					      /*command*/ 1,
4999 					      /*field*/ 1,
5000 					      /*bit_valid*/ 0,
5001 					      /*bit*/ 0);
5002 			ctl_done((union ctl_io *)ctsio);
5003 			return (CTL_RETVAL_COMPLETE);
5004 		}
5005 		break;
5006 	}
5007 	case RELEASE_10: {
5008 		struct scsi_release_10 *cdb;
5009 
5010 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5011 
5012 		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5013 			ctl_set_invalid_field(ctsio,
5014 					      /*sks_valid*/ 1,
5015 					      /*command*/ 1,
5016 					      /*field*/ 1,
5017 					      /*bit_valid*/ 1,
5018 					      /*bit*/ 0);
5019 			ctl_done((union ctl_io *)ctsio);
5020 			return (CTL_RETVAL_COMPLETE);
5021 
5022 		}
5023 
5024 		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5025 			ctl_set_invalid_field(ctsio,
5026 					      /*sks_valid*/ 1,
5027 					      /*command*/ 1,
5028 					      /*field*/ 1,
5029 					      /*bit_valid*/ 1,
5030 					      /*bit*/ 4);
5031 			ctl_done((union ctl_io *)ctsio);
5032 			return (CTL_RETVAL_COMPLETE);
5033 		}
5034 
5035 		if (cdb->byte2 & SR10_LONGID)
5036 			longid = 1;
5037 		else
5038 			thirdparty_id = cdb->thirdparty_id;
5039 
5040 		resv_id = cdb->resv_id;
5041 		length = scsi_2btoul(cdb->length);
5042 		break;
5043 	}
5044 	}
5045 
5046 
5047 	/*
5048 	 * XXX KDM right now, we only support LUN reservation.  We don't
5049 	 * support 3rd party reservations, or extent reservations, which
5050 	 * might actually need the parameter list.  If we've gotten this
5051 	 * far, we've got a LUN reservation.  Anything else got kicked out
5052 	 * above.  So, according to SPC, ignore the length.
5053 	 */
5054 	length = 0;
5055 
5056 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5057 	 && (length > 0)) {
5058 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5059 		if (ctsio->kern_data_ptr == NULL) {
5060 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5061 			ctsio->io_hdr.status = SCSI_STATUS_BUSY;
5062 			ctl_done((union ctl_io *)ctsio);
5063 			return (CTL_RETVAL_COMPLETE);
5064 		}
5065 		ctsio->kern_data_len = length;
5066 		ctsio->kern_total_len = length;
5067 		ctsio->kern_data_resid = 0;
5068 		ctsio->kern_rel_offset = 0;
5069 		ctsio->kern_sg_entries = 0;
5070 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5071 		ctsio->be_move_done = ctl_config_move_done;
5072 		ctl_datamove((union ctl_io *)ctsio);
5073 
5074 		return (CTL_RETVAL_COMPLETE);
5075 	}
5076 
5077 	if (length > 0)
5078 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5079 
5080 	mtx_lock(&ctl_softc->ctl_lock);
5081 
5082 	/*
5083 	 * According to SPC, it is not an error for an intiator to attempt
5084 	 * to release a reservation on a LUN that isn't reserved, or that
5085 	 * is reserved by another initiator.  The reservation can only be
5086 	 * released, though, by the initiator who made it or by one of
5087 	 * several reset type events.
5088 	 */
5089 	if (lun->flags & CTL_LUN_RESERVED) {
5090 		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5091 		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5092 		 && (ctsio->io_hdr.nexus.targ_target.id ==
5093 		     lun->rsv_nexus.targ_target.id)) {
5094 			lun->flags &= ~CTL_LUN_RESERVED;
5095 		}
5096 	}
5097 
5098 	ctsio->scsi_status = SCSI_STATUS_OK;
5099 	ctsio->io_hdr.status = CTL_SUCCESS;
5100 
5101 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5102 		free(ctsio->kern_data_ptr, M_CTL);
5103 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5104 	}
5105 
5106 	mtx_unlock(&ctl_softc->ctl_lock);
5107 
5108 	ctl_done((union ctl_io *)ctsio);
5109 	return (CTL_RETVAL_COMPLETE);
5110 }
5111 
5112 int
5113 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5114 {
5115 	int extent, thirdparty, longid;
5116 	int resv_id, length;
5117 	uint64_t thirdparty_id;
5118 	struct ctl_softc *ctl_softc;
5119 	struct ctl_lun *lun;
5120 
5121 	extent = 0;
5122 	thirdparty = 0;
5123 	longid = 0;
5124 	resv_id = 0;
5125 	length = 0;
5126 	thirdparty_id = 0;
5127 
5128 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5129 
5130 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5131 	ctl_softc = control_softc;
5132 
5133 	switch (ctsio->cdb[0]) {
5134 	case RESERVE: {
5135 		struct scsi_reserve *cdb;
5136 
5137 		cdb = (struct scsi_reserve *)ctsio->cdb;
5138 		if ((cdb->byte2 & 0x1f) != 0) {
5139 			ctl_set_invalid_field(ctsio,
5140 					      /*sks_valid*/ 1,
5141 					      /*command*/ 1,
5142 					      /*field*/ 1,
5143 					      /*bit_valid*/ 0,
5144 					      /*bit*/ 0);
5145 			ctl_done((union ctl_io *)ctsio);
5146 			return (CTL_RETVAL_COMPLETE);
5147 		}
5148 		resv_id = cdb->resv_id;
5149 		length = scsi_2btoul(cdb->length);
5150 		break;
5151 	}
5152 	case RESERVE_10: {
5153 		struct scsi_reserve_10 *cdb;
5154 
5155 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5156 
5157 		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5158 			ctl_set_invalid_field(ctsio,
5159 					      /*sks_valid*/ 1,
5160 					      /*command*/ 1,
5161 					      /*field*/ 1,
5162 					      /*bit_valid*/ 1,
5163 					      /*bit*/ 0);
5164 			ctl_done((union ctl_io *)ctsio);
5165 			return (CTL_RETVAL_COMPLETE);
5166 		}
5167 		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5168 			ctl_set_invalid_field(ctsio,
5169 					      /*sks_valid*/ 1,
5170 					      /*command*/ 1,
5171 					      /*field*/ 1,
5172 					      /*bit_valid*/ 1,
5173 					      /*bit*/ 4);
5174 			ctl_done((union ctl_io *)ctsio);
5175 			return (CTL_RETVAL_COMPLETE);
5176 		}
5177 		if (cdb->byte2 & SR10_LONGID)
5178 			longid = 1;
5179 		else
5180 			thirdparty_id = cdb->thirdparty_id;
5181 
5182 		resv_id = cdb->resv_id;
5183 		length = scsi_2btoul(cdb->length);
5184 		break;
5185 	}
5186 	}
5187 
5188 	/*
5189 	 * XXX KDM right now, we only support LUN reservation.  We don't
5190 	 * support 3rd party reservations, or extent reservations, which
5191 	 * might actually need the parameter list.  If we've gotten this
5192 	 * far, we've got a LUN reservation.  Anything else got kicked out
5193 	 * above.  So, according to SPC, ignore the length.
5194 	 */
5195 	length = 0;
5196 
5197 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5198 	 && (length > 0)) {
5199 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5200 		if (ctsio->kern_data_ptr == NULL) {
5201 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5202 			ctsio->io_hdr.status = SCSI_STATUS_BUSY;
5203 			ctl_done((union ctl_io *)ctsio);
5204 			return (CTL_RETVAL_COMPLETE);
5205 		}
5206 		ctsio->kern_data_len = length;
5207 		ctsio->kern_total_len = length;
5208 		ctsio->kern_data_resid = 0;
5209 		ctsio->kern_rel_offset = 0;
5210 		ctsio->kern_sg_entries = 0;
5211 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5212 		ctsio->be_move_done = ctl_config_move_done;
5213 		ctl_datamove((union ctl_io *)ctsio);
5214 
5215 		return (CTL_RETVAL_COMPLETE);
5216 	}
5217 
5218 	if (length > 0)
5219 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5220 
5221 	mtx_lock(&ctl_softc->ctl_lock);
5222 	if (lun->flags & CTL_LUN_RESERVED) {
5223 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5224 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5225 		 || (ctsio->io_hdr.nexus.targ_target.id !=
5226 		     lun->rsv_nexus.targ_target.id)) {
5227 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5228 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5229 			goto bailout;
5230 		}
5231 	}
5232 
5233 	lun->flags |= CTL_LUN_RESERVED;
5234 	lun->rsv_nexus = ctsio->io_hdr.nexus;
5235 
5236 	ctsio->scsi_status = SCSI_STATUS_OK;
5237 	ctsio->io_hdr.status = CTL_SUCCESS;
5238 
5239 bailout:
5240 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5241 		free(ctsio->kern_data_ptr, M_CTL);
5242 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5243 	}
5244 
5245 	mtx_unlock(&ctl_softc->ctl_lock);
5246 
5247 	ctl_done((union ctl_io *)ctsio);
5248 	return (CTL_RETVAL_COMPLETE);
5249 }
5250 
5251 int
5252 ctl_start_stop(struct ctl_scsiio *ctsio)
5253 {
5254 	struct scsi_start_stop_unit *cdb;
5255 	struct ctl_lun *lun;
5256 	struct ctl_softc *ctl_softc;
5257 	int retval;
5258 
5259 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5260 
5261 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5262 	ctl_softc = control_softc;
5263 	retval = 0;
5264 
5265 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5266 
5267 	/*
5268 	 * XXX KDM
5269 	 * We don't support the immediate bit on a stop unit.  In order to
5270 	 * do that, we would need to code up a way to know that a stop is
5271 	 * pending, and hold off any new commands until it completes, one
5272 	 * way or another.  Then we could accept or reject those commands
5273 	 * depending on its status.  We would almost need to do the reverse
5274 	 * of what we do below for an immediate start -- return the copy of
5275 	 * the ctl_io to the FETD with status to send to the host (and to
5276 	 * free the copy!) and then free the original I/O once the stop
5277 	 * actually completes.  That way, the OOA queue mechanism can work
5278 	 * to block commands that shouldn't proceed.  Another alternative
5279 	 * would be to put the copy in the queue in place of the original,
5280 	 * and return the original back to the caller.  That could be
5281 	 * slightly safer..
5282 	 */
5283 	if ((cdb->byte2 & SSS_IMMED)
5284 	 && ((cdb->how & SSS_START) == 0)) {
5285 		ctl_set_invalid_field(ctsio,
5286 				      /*sks_valid*/ 1,
5287 				      /*command*/ 1,
5288 				      /*field*/ 1,
5289 				      /*bit_valid*/ 1,
5290 				      /*bit*/ 0);
5291 		ctl_done((union ctl_io *)ctsio);
5292 		return (CTL_RETVAL_COMPLETE);
5293 	}
5294 
5295 	/*
5296 	 * We don't support the power conditions field.  We need to check
5297 	 * this prior to checking the load/eject and start/stop bits.
5298 	 */
5299 	if ((cdb->how & SSS_PC_MASK) != SSS_PC_START_VALID) {
5300 		ctl_set_invalid_field(ctsio,
5301 				      /*sks_valid*/ 1,
5302 				      /*command*/ 1,
5303 				      /*field*/ 4,
5304 				      /*bit_valid*/ 1,
5305 				      /*bit*/ 4);
5306 		ctl_done((union ctl_io *)ctsio);
5307 		return (CTL_RETVAL_COMPLETE);
5308 	}
5309 
5310 	/*
5311 	 * Media isn't removable, so we can't load or eject it.
5312 	 */
5313 	if ((cdb->how & SSS_LOEJ) != 0) {
5314 		ctl_set_invalid_field(ctsio,
5315 				      /*sks_valid*/ 1,
5316 				      /*command*/ 1,
5317 				      /*field*/ 4,
5318 				      /*bit_valid*/ 1,
5319 				      /*bit*/ 1);
5320 		ctl_done((union ctl_io *)ctsio);
5321 		return (CTL_RETVAL_COMPLETE);
5322 	}
5323 
5324 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5325 	 && ((cdb->how & SSS_START)==0)) {
5326 		uint32_t residx;
5327 
5328 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5329 		if (!lun->per_res[residx].registered
5330 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5331 
5332 			ctl_set_reservation_conflict(ctsio);
5333 			ctl_done((union ctl_io *)ctsio);
5334 			return (CTL_RETVAL_COMPLETE);
5335 		}
5336 	}
5337 
5338 	/*
5339 	 * If there is no backend on this device, we can't start or stop
5340 	 * it.  In theory we shouldn't get any start/stop commands in the
5341 	 * first place at this level if the LUN doesn't have a backend.
5342 	 * That should get stopped by the command decode code.
5343 	 */
5344 	if (lun->backend == NULL) {
5345 		ctl_set_invalid_opcode(ctsio);
5346 		ctl_done((union ctl_io *)ctsio);
5347 		return (CTL_RETVAL_COMPLETE);
5348 	}
5349 
5350 	/*
5351 	 * XXX KDM Copan-specific offline behavior.
5352 	 * Figure out a reasonable way to port this?
5353 	 */
5354 #ifdef NEEDTOPORT
5355 	mtx_lock(&ctl_softc->ctl_lock);
5356 
5357 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5358 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5359 		/*
5360 		 * If the LUN is offline, and the on/offline bit isn't set,
5361 		 * reject the start or stop.  Otherwise, let it through.
5362 		 */
5363 		mtx_unlock(&ctl_softc->ctl_lock);
5364 		ctl_set_lun_not_ready(ctsio);
5365 		ctl_done((union ctl_io *)ctsio);
5366 	} else {
5367 		mtx_unlock(&ctl_softc->ctl_lock);
5368 #endif /* NEEDTOPORT */
5369 		/*
5370 		 * This could be a start or a stop when we're online,
5371 		 * or a stop/offline or start/online.  A start or stop when
5372 		 * we're offline is covered in the case above.
5373 		 */
5374 		/*
5375 		 * In the non-immediate case, we send the request to
5376 		 * the backend and return status to the user when
5377 		 * it is done.
5378 		 *
5379 		 * In the immediate case, we allocate a new ctl_io
5380 		 * to hold a copy of the request, and send that to
5381 		 * the backend.  We then set good status on the
5382 		 * user's request and return it immediately.
5383 		 */
5384 		if (cdb->byte2 & SSS_IMMED) {
5385 			union ctl_io *new_io;
5386 
5387 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5388 			if (new_io == NULL) {
5389 				ctl_set_busy(ctsio);
5390 				ctl_done((union ctl_io *)ctsio);
5391 			} else {
5392 				ctl_copy_io((union ctl_io *)ctsio,
5393 					    new_io);
5394 				retval = lun->backend->config_write(new_io);
5395 				ctl_set_success(ctsio);
5396 				ctl_done((union ctl_io *)ctsio);
5397 			}
5398 		} else {
5399 			retval = lun->backend->config_write(
5400 				(union ctl_io *)ctsio);
5401 		}
5402 #ifdef NEEDTOPORT
5403 	}
5404 #endif
5405 	return (retval);
5406 }
5407 
5408 /*
5409  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5410  * we don't really do anything with the LBA and length fields if the user
5411  * passes them in.  Instead we'll just flush out the cache for the entire
5412  * LUN.
5413  */
5414 int
5415 ctl_sync_cache(struct ctl_scsiio *ctsio)
5416 {
5417 	struct ctl_lun *lun;
5418 	struct ctl_softc *ctl_softc;
5419 	uint64_t starting_lba;
5420 	uint32_t block_count;
5421 	int reladr, immed;
5422 	int retval;
5423 
5424 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5425 
5426 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5427 	ctl_softc = control_softc;
5428 	retval = 0;
5429 	reladr = 0;
5430 	immed = 0;
5431 
5432 	switch (ctsio->cdb[0]) {
5433 	case SYNCHRONIZE_CACHE: {
5434 		struct scsi_sync_cache *cdb;
5435 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5436 
5437 		if (cdb->byte2 & SSC_RELADR)
5438 			reladr = 1;
5439 
5440 		if (cdb->byte2 & SSC_IMMED)
5441 			immed = 1;
5442 
5443 		starting_lba = scsi_4btoul(cdb->begin_lba);
5444 		block_count = scsi_2btoul(cdb->lb_count);
5445 		break;
5446 	}
5447 	case SYNCHRONIZE_CACHE_16: {
5448 		struct scsi_sync_cache_16 *cdb;
5449 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5450 
5451 		if (cdb->byte2 & SSC_RELADR)
5452 			reladr = 1;
5453 
5454 		if (cdb->byte2 & SSC_IMMED)
5455 			immed = 1;
5456 
5457 		starting_lba = scsi_8btou64(cdb->begin_lba);
5458 		block_count = scsi_4btoul(cdb->lb_count);
5459 		break;
5460 	}
5461 	default:
5462 		ctl_set_invalid_opcode(ctsio);
5463 		ctl_done((union ctl_io *)ctsio);
5464 		goto bailout;
5465 		break; /* NOTREACHED */
5466 	}
5467 
5468 	if (immed) {
5469 		/*
5470 		 * We don't support the immediate bit.  Since it's in the
5471 		 * same place for the 10 and 16 byte SYNCHRONIZE CACHE
5472 		 * commands, we can just return the same error in either
5473 		 * case.
5474 		 */
5475 		ctl_set_invalid_field(ctsio,
5476 				      /*sks_valid*/ 1,
5477 				      /*command*/ 1,
5478 				      /*field*/ 1,
5479 				      /*bit_valid*/ 1,
5480 				      /*bit*/ 1);
5481 		ctl_done((union ctl_io *)ctsio);
5482 		goto bailout;
5483 	}
5484 
5485 	if (reladr) {
5486 		/*
5487 		 * We don't support the reladr bit either.  It can only be
5488 		 * used with linked commands, and we don't support linked
5489 		 * commands.  Since the bit is in the same place for the
5490 		 * 10 and 16 byte SYNCHRONIZE CACHE * commands, we can
5491 		 * just return the same error in either case.
5492 		 */
5493 		ctl_set_invalid_field(ctsio,
5494 				      /*sks_valid*/ 1,
5495 				      /*command*/ 1,
5496 				      /*field*/ 1,
5497 				      /*bit_valid*/ 1,
5498 				      /*bit*/ 0);
5499 		ctl_done((union ctl_io *)ctsio);
5500 		goto bailout;
5501 	}
5502 
5503 	/*
5504 	 * We check the LBA and length, but don't do anything with them.
5505 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5506 	 * get flushed.  This check will just help satisfy anyone who wants
5507 	 * to see an error for an out of range LBA.
5508 	 */
5509 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5510 		ctl_set_lba_out_of_range(ctsio);
5511 		ctl_done((union ctl_io *)ctsio);
5512 		goto bailout;
5513 	}
5514 
5515 	/*
5516 	 * If this LUN has no backend, we can't flush the cache anyway.
5517 	 */
5518 	if (lun->backend == NULL) {
5519 		ctl_set_invalid_opcode(ctsio);
5520 		ctl_done((union ctl_io *)ctsio);
5521 		goto bailout;
5522 	}
5523 
5524 	/*
5525 	 * Check to see whether we're configured to send the SYNCHRONIZE
5526 	 * CACHE command directly to the back end.
5527 	 */
5528 	mtx_lock(&ctl_softc->ctl_lock);
5529 	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5530 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5531 		lun->sync_count = 0;
5532 		mtx_unlock(&ctl_softc->ctl_lock);
5533 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5534 	} else {
5535 		mtx_unlock(&ctl_softc->ctl_lock);
5536 		ctl_set_success(ctsio);
5537 		ctl_done((union ctl_io *)ctsio);
5538 	}
5539 
5540 bailout:
5541 
5542 	return (retval);
5543 }
5544 
5545 int
5546 ctl_format(struct ctl_scsiio *ctsio)
5547 {
5548 	struct scsi_format *cdb;
5549 	struct ctl_lun *lun;
5550 	struct ctl_softc *ctl_softc;
5551 	int length, defect_list_len;
5552 
5553 	CTL_DEBUG_PRINT(("ctl_format\n"));
5554 
5555 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5556 	ctl_softc = control_softc;
5557 
5558 	cdb = (struct scsi_format *)ctsio->cdb;
5559 
5560 	length = 0;
5561 	if (cdb->byte2 & SF_FMTDATA) {
5562 		if (cdb->byte2 & SF_LONGLIST)
5563 			length = sizeof(struct scsi_format_header_long);
5564 		else
5565 			length = sizeof(struct scsi_format_header_short);
5566 	}
5567 
5568 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5569 	 && (length > 0)) {
5570 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5571 		if (ctsio->kern_data_ptr == NULL) {
5572 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5573 			ctsio->io_hdr.status = SCSI_STATUS_BUSY;
5574 			ctl_done((union ctl_io *)ctsio);
5575 			return (CTL_RETVAL_COMPLETE);
5576 		}
5577 		ctsio->kern_data_len = length;
5578 		ctsio->kern_total_len = length;
5579 		ctsio->kern_data_resid = 0;
5580 		ctsio->kern_rel_offset = 0;
5581 		ctsio->kern_sg_entries = 0;
5582 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5583 		ctsio->be_move_done = ctl_config_move_done;
5584 		ctl_datamove((union ctl_io *)ctsio);
5585 
5586 		return (CTL_RETVAL_COMPLETE);
5587 	}
5588 
5589 	defect_list_len = 0;
5590 
5591 	if (cdb->byte2 & SF_FMTDATA) {
5592 		if (cdb->byte2 & SF_LONGLIST) {
5593 			struct scsi_format_header_long *header;
5594 
5595 			header = (struct scsi_format_header_long *)
5596 				ctsio->kern_data_ptr;
5597 
5598 			defect_list_len = scsi_4btoul(header->defect_list_len);
5599 			if (defect_list_len != 0) {
5600 				ctl_set_invalid_field(ctsio,
5601 						      /*sks_valid*/ 1,
5602 						      /*command*/ 0,
5603 						      /*field*/ 2,
5604 						      /*bit_valid*/ 0,
5605 						      /*bit*/ 0);
5606 				goto bailout;
5607 			}
5608 		} else {
5609 			struct scsi_format_header_short *header;
5610 
5611 			header = (struct scsi_format_header_short *)
5612 				ctsio->kern_data_ptr;
5613 
5614 			defect_list_len = scsi_2btoul(header->defect_list_len);
5615 			if (defect_list_len != 0) {
5616 				ctl_set_invalid_field(ctsio,
5617 						      /*sks_valid*/ 1,
5618 						      /*command*/ 0,
5619 						      /*field*/ 2,
5620 						      /*bit_valid*/ 0,
5621 						      /*bit*/ 0);
5622 				goto bailout;
5623 			}
5624 		}
5625 	}
5626 
5627 	/*
5628 	 * The format command will clear out the "Medium format corrupted"
5629 	 * status if set by the configuration code.  That status is really
5630 	 * just a way to notify the host that we have lost the media, and
5631 	 * get them to issue a command that will basically make them think
5632 	 * they're blowing away the media.
5633 	 */
5634 	mtx_lock(&ctl_softc->ctl_lock);
5635 	lun->flags &= ~CTL_LUN_INOPERABLE;
5636 	mtx_unlock(&ctl_softc->ctl_lock);
5637 
5638 	ctsio->scsi_status = SCSI_STATUS_OK;
5639 	ctsio->io_hdr.status = CTL_SUCCESS;
5640 bailout:
5641 
5642 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5643 		free(ctsio->kern_data_ptr, M_CTL);
5644 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5645 	}
5646 
5647 	ctl_done((union ctl_io *)ctsio);
5648 	return (CTL_RETVAL_COMPLETE);
5649 }
5650 
5651 int
5652 ctl_write_buffer(struct ctl_scsiio *ctsio)
5653 {
5654 	struct scsi_write_buffer *cdb;
5655 	struct copan_page_header *header;
5656 	struct ctl_lun *lun;
5657 	struct ctl_softc *ctl_softc;
5658 	int buffer_offset, len;
5659 	int retval;
5660 
5661 	header = NULL;
5662 
5663 	retval = CTL_RETVAL_COMPLETE;
5664 
5665 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5666 
5667 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5668 	ctl_softc = control_softc;
5669 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5670 
5671 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5672 		ctl_set_invalid_field(ctsio,
5673 				      /*sks_valid*/ 1,
5674 				      /*command*/ 1,
5675 				      /*field*/ 1,
5676 				      /*bit_valid*/ 1,
5677 				      /*bit*/ 4);
5678 		ctl_done((union ctl_io *)ctsio);
5679 		return (CTL_RETVAL_COMPLETE);
5680 	}
5681 	if (cdb->buffer_id != 0) {
5682 		ctl_set_invalid_field(ctsio,
5683 				      /*sks_valid*/ 1,
5684 				      /*command*/ 1,
5685 				      /*field*/ 2,
5686 				      /*bit_valid*/ 0,
5687 				      /*bit*/ 0);
5688 		ctl_done((union ctl_io *)ctsio);
5689 		return (CTL_RETVAL_COMPLETE);
5690 	}
5691 
5692 	len = scsi_3btoul(cdb->length);
5693 	buffer_offset = scsi_3btoul(cdb->offset);
5694 
5695 	if (len > sizeof(lun->write_buffer)) {
5696 		ctl_set_invalid_field(ctsio,
5697 				      /*sks_valid*/ 1,
5698 				      /*command*/ 1,
5699 				      /*field*/ 6,
5700 				      /*bit_valid*/ 0,
5701 				      /*bit*/ 0);
5702 		ctl_done((union ctl_io *)ctsio);
5703 		return (CTL_RETVAL_COMPLETE);
5704 	}
5705 
5706 	if (buffer_offset != 0) {
5707 		ctl_set_invalid_field(ctsio,
5708 				      /*sks_valid*/ 1,
5709 				      /*command*/ 1,
5710 				      /*field*/ 3,
5711 				      /*bit_valid*/ 0,
5712 				      /*bit*/ 0);
5713 		ctl_done((union ctl_io *)ctsio);
5714 		return (CTL_RETVAL_COMPLETE);
5715 	}
5716 
5717 	/*
5718 	 * If we've got a kernel request that hasn't been malloced yet,
5719 	 * malloc it and tell the caller the data buffer is here.
5720 	 */
5721 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5722 		ctsio->kern_data_ptr = lun->write_buffer;
5723 		ctsio->kern_data_len = len;
5724 		ctsio->kern_total_len = len;
5725 		ctsio->kern_data_resid = 0;
5726 		ctsio->kern_rel_offset = 0;
5727 		ctsio->kern_sg_entries = 0;
5728 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5729 		ctsio->be_move_done = ctl_config_move_done;
5730 		ctl_datamove((union ctl_io *)ctsio);
5731 
5732 		return (CTL_RETVAL_COMPLETE);
5733 	}
5734 
5735 	ctl_done((union ctl_io *)ctsio);
5736 
5737 	return (CTL_RETVAL_COMPLETE);
5738 }
5739 
5740 /*
5741  * Note that this function currently doesn't actually do anything inside
5742  * CTL to enforce things if the DQue bit is turned on.
5743  *
5744  * Also note that this function can't be used in the default case, because
5745  * the DQue bit isn't set in the changeable mask for the control mode page
5746  * anyway.  This is just here as an example for how to implement a page
5747  * handler, and a placeholder in case we want to allow the user to turn
5748  * tagged queueing on and off.
5749  *
5750  * The D_SENSE bit handling is functional, however, and will turn
5751  * descriptor sense on and off for a given LUN.
5752  */
5753 int
5754 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5755 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5756 {
5757 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5758 	struct ctl_lun *lun;
5759 	struct ctl_softc *softc;
5760 	int set_ua;
5761 	uint32_t initidx;
5762 
5763 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5764 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5765 	set_ua = 0;
5766 
5767 	user_cp = (struct scsi_control_page *)page_ptr;
5768 	current_cp = (struct scsi_control_page *)
5769 		(page_index->page_data + (page_index->page_len *
5770 		CTL_PAGE_CURRENT));
5771 	saved_cp = (struct scsi_control_page *)
5772 		(page_index->page_data + (page_index->page_len *
5773 		CTL_PAGE_SAVED));
5774 
5775 	softc = control_softc;
5776 
5777 	mtx_lock(&softc->ctl_lock);
5778 	if (((current_cp->rlec & SCP_DSENSE) == 0)
5779 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5780 		/*
5781 		 * Descriptor sense is currently turned off and the user
5782 		 * wants to turn it on.
5783 		 */
5784 		current_cp->rlec |= SCP_DSENSE;
5785 		saved_cp->rlec |= SCP_DSENSE;
5786 		lun->flags |= CTL_LUN_SENSE_DESC;
5787 		set_ua = 1;
5788 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5789 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5790 		/*
5791 		 * Descriptor sense is currently turned on, and the user
5792 		 * wants to turn it off.
5793 		 */
5794 		current_cp->rlec &= ~SCP_DSENSE;
5795 		saved_cp->rlec &= ~SCP_DSENSE;
5796 		lun->flags &= ~CTL_LUN_SENSE_DESC;
5797 		set_ua = 1;
5798 	}
5799 	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
5800 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
5801 #ifdef NEEDTOPORT
5802 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5803 				    CTL_UNTAG_TO_UNTAG,
5804 				    csevent_LogType_Trace,
5805 				    csevent_Severity_Information,
5806 				    csevent_AlertLevel_Green,
5807 				    csevent_FRU_Firmware,
5808 				    csevent_FRU_Unknown,
5809 				    "Received untagged to untagged transition");
5810 #endif /* NEEDTOPORT */
5811 		} else {
5812 #ifdef NEEDTOPORT
5813 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5814 				    CTL_UNTAG_TO_TAG,
5815 				    csevent_LogType_ConfigChange,
5816 				    csevent_Severity_Information,
5817 				    csevent_AlertLevel_Green,
5818 				    csevent_FRU_Firmware,
5819 				    csevent_FRU_Unknown,
5820 				    "Received untagged to tagged "
5821 				    "queueing transition");
5822 #endif /* NEEDTOPORT */
5823 
5824 			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
5825 			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
5826 			set_ua = 1;
5827 		}
5828 	} else {
5829 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
5830 #ifdef NEEDTOPORT
5831 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5832 				    CTL_TAG_TO_UNTAG,
5833 				    csevent_LogType_ConfigChange,
5834 				    csevent_Severity_Warning,
5835 				    csevent_AlertLevel_Yellow,
5836 				    csevent_FRU_Firmware,
5837 				    csevent_FRU_Unknown,
5838 				    "Received tagged queueing to untagged "
5839 				    "transition");
5840 #endif /* NEEDTOPORT */
5841 
5842 			current_cp->queue_flags |= SCP_QUEUE_DQUE;
5843 			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
5844 			set_ua = 1;
5845 		} else {
5846 #ifdef NEEDTOPORT
5847 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5848 				    CTL_TAG_TO_TAG,
5849 				    csevent_LogType_Trace,
5850 				    csevent_Severity_Information,
5851 				    csevent_AlertLevel_Green,
5852 				    csevent_FRU_Firmware,
5853 				    csevent_FRU_Unknown,
5854 				    "Received tagged queueing to tagged "
5855 				    "queueing transition");
5856 #endif /* NEEDTOPORT */
5857 		}
5858 	}
5859 	if (set_ua != 0) {
5860 		int i;
5861 		/*
5862 		 * Let other initiators know that the mode
5863 		 * parameters for this LUN have changed.
5864 		 */
5865 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
5866 			if (i == initidx)
5867 				continue;
5868 
5869 			lun->pending_sense[i].ua_pending |=
5870 				CTL_UA_MODE_CHANGE;
5871 		}
5872 	}
5873 	mtx_unlock(&softc->ctl_lock);
5874 
5875 	return (0);
5876 }
5877 
5878 int
5879 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
5880 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5881 {
5882 	return (0);
5883 }
5884 
5885 int
5886 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
5887 			   struct ctl_page_index *page_index, int pc)
5888 {
5889 	struct copan_power_subpage *page;
5890 
5891 	page = (struct copan_power_subpage *)page_index->page_data +
5892 		(page_index->page_len * pc);
5893 
5894 	switch (pc) {
5895 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5896 		/*
5897 		 * We don't update the changable bits for this page.
5898 		 */
5899 		break;
5900 	case SMS_PAGE_CTRL_CURRENT >> 6:
5901 	case SMS_PAGE_CTRL_DEFAULT >> 6:
5902 	case SMS_PAGE_CTRL_SAVED >> 6:
5903 #ifdef NEEDTOPORT
5904 		ctl_update_power_subpage(page);
5905 #endif
5906 		break;
5907 	default:
5908 #ifdef NEEDTOPORT
5909 		EPRINT(0, "Invalid PC %d!!", pc);
5910 #endif
5911 		break;
5912 	}
5913 	return (0);
5914 }
5915 
5916 
5917 int
5918 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
5919 		   struct ctl_page_index *page_index, uint8_t *page_ptr)
5920 {
5921 	struct copan_aps_subpage *user_sp;
5922 	struct copan_aps_subpage *current_sp;
5923 	union ctl_modepage_info *modepage_info;
5924 	struct ctl_softc *softc;
5925 	struct ctl_lun *lun;
5926 	int retval;
5927 
5928 	retval = CTL_RETVAL_COMPLETE;
5929 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5930 		     (page_index->page_len * CTL_PAGE_CURRENT));
5931 	softc = control_softc;
5932 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5933 
5934 	user_sp = (struct copan_aps_subpage *)page_ptr;
5935 
5936 	modepage_info = (union ctl_modepage_info *)
5937 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5938 
5939 	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
5940 	modepage_info->header.subpage = page_index->subpage;
5941 	modepage_info->aps.lock_active = user_sp->lock_active;
5942 
5943 	mtx_lock(&softc->ctl_lock);
5944 
5945 	/*
5946 	 * If there is a request to lock the LUN and another LUN is locked
5947 	 * this is an error. If the requested LUN is already locked ignore
5948 	 * the request. If no LUN is locked attempt to lock it.
5949 	 * if there is a request to unlock the LUN and the LUN is currently
5950 	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
5951 	 * if another LUN is locked or no LUN is locked.
5952 	 */
5953 	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
5954 		if (softc->aps_locked_lun == lun->lun) {
5955 			/*
5956 			 * This LUN is already locked, so we're done.
5957 			 */
5958 			retval = CTL_RETVAL_COMPLETE;
5959 		} else if (softc->aps_locked_lun == 0) {
5960 			/*
5961 			 * No one has the lock, pass the request to the
5962 			 * backend.
5963 			 */
5964 			retval = lun->backend->config_write(
5965 				(union ctl_io *)ctsio);
5966 		} else {
5967 			/*
5968 			 * Someone else has the lock, throw out the request.
5969 			 */
5970 			ctl_set_already_locked(ctsio);
5971 			free(ctsio->kern_data_ptr, M_CTL);
5972 			ctl_done((union ctl_io *)ctsio);
5973 
5974 			/*
5975 			 * Set the return value so that ctl_do_mode_select()
5976 			 * won't try to complete the command.  We already
5977 			 * completed it here.
5978 			 */
5979 			retval = CTL_RETVAL_ERROR;
5980 		}
5981 	} else if (softc->aps_locked_lun == lun->lun) {
5982 		/*
5983 		 * This LUN is locked, so pass the unlock request to the
5984 		 * backend.
5985 		 */
5986 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5987 	}
5988 	mtx_unlock(&softc->ctl_lock);
5989 
5990 	return (retval);
5991 }
5992 
5993 int
5994 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5995 				struct ctl_page_index *page_index,
5996 				uint8_t *page_ptr)
5997 {
5998 	uint8_t *c;
5999 	int i;
6000 
6001 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6002 	ctl_time_io_secs =
6003 		(c[0] << 8) |
6004 		(c[1] << 0) |
6005 		0;
6006 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6007 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6008 	printf("page data:");
6009 	for (i=0; i<8; i++)
6010 		printf(" %.2x",page_ptr[i]);
6011 	printf("\n");
6012 	return (0);
6013 }
6014 
6015 int
6016 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6017 			       struct ctl_page_index *page_index,
6018 			       int pc)
6019 {
6020 	struct copan_debugconf_subpage *page;
6021 
6022 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6023 		(page_index->page_len * pc);
6024 
6025 	switch (pc) {
6026 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6027 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6028 	case SMS_PAGE_CTRL_SAVED >> 6:
6029 		/*
6030 		 * We don't update the changable or default bits for this page.
6031 		 */
6032 		break;
6033 	case SMS_PAGE_CTRL_CURRENT >> 6:
6034 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6035 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6036 		break;
6037 	default:
6038 #ifdef NEEDTOPORT
6039 		EPRINT(0, "Invalid PC %d!!", pc);
6040 #endif /* NEEDTOPORT */
6041 		break;
6042 	}
6043 	return (0);
6044 }
6045 
6046 
6047 static int
6048 ctl_do_mode_select(union ctl_io *io)
6049 {
6050 	struct scsi_mode_page_header *page_header;
6051 	struct ctl_page_index *page_index;
6052 	struct ctl_scsiio *ctsio;
6053 	int control_dev, page_len;
6054 	int page_len_offset, page_len_size;
6055 	union ctl_modepage_info *modepage_info;
6056 	struct ctl_lun *lun;
6057 	int *len_left, *len_used;
6058 	int retval, i;
6059 
6060 	ctsio = &io->scsiio;
6061 	page_index = NULL;
6062 	page_len = 0;
6063 	retval = CTL_RETVAL_COMPLETE;
6064 
6065 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6066 
6067 	if (lun->be_lun->lun_type != T_DIRECT)
6068 		control_dev = 1;
6069 	else
6070 		control_dev = 0;
6071 
6072 	modepage_info = (union ctl_modepage_info *)
6073 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6074 	len_left = &modepage_info->header.len_left;
6075 	len_used = &modepage_info->header.len_used;
6076 
6077 do_next_page:
6078 
6079 	page_header = (struct scsi_mode_page_header *)
6080 		(ctsio->kern_data_ptr + *len_used);
6081 
6082 	if (*len_left == 0) {
6083 		free(ctsio->kern_data_ptr, M_CTL);
6084 		ctl_set_success(ctsio);
6085 		ctl_done((union ctl_io *)ctsio);
6086 		return (CTL_RETVAL_COMPLETE);
6087 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6088 
6089 		free(ctsio->kern_data_ptr, M_CTL);
6090 		ctl_set_param_len_error(ctsio);
6091 		ctl_done((union ctl_io *)ctsio);
6092 		return (CTL_RETVAL_COMPLETE);
6093 
6094 	} else if ((page_header->page_code & SMPH_SPF)
6095 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6096 
6097 		free(ctsio->kern_data_ptr, M_CTL);
6098 		ctl_set_param_len_error(ctsio);
6099 		ctl_done((union ctl_io *)ctsio);
6100 		return (CTL_RETVAL_COMPLETE);
6101 	}
6102 
6103 
6104 	/*
6105 	 * XXX KDM should we do something with the block descriptor?
6106 	 */
6107 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6108 
6109 		if ((control_dev != 0)
6110 		 && (lun->mode_pages.index[i].page_flags &
6111 		     CTL_PAGE_FLAG_DISK_ONLY))
6112 			continue;
6113 
6114 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6115 		    (page_header->page_code & SMPH_PC_MASK))
6116 			continue;
6117 
6118 		/*
6119 		 * If neither page has a subpage code, then we've got a
6120 		 * match.
6121 		 */
6122 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6123 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6124 			page_index = &lun->mode_pages.index[i];
6125 			page_len = page_header->page_length;
6126 			break;
6127 		}
6128 
6129 		/*
6130 		 * If both pages have subpages, then the subpage numbers
6131 		 * have to match.
6132 		 */
6133 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6134 		  && (page_header->page_code & SMPH_SPF)) {
6135 			struct scsi_mode_page_header_sp *sph;
6136 
6137 			sph = (struct scsi_mode_page_header_sp *)page_header;
6138 
6139 			if (lun->mode_pages.index[i].subpage ==
6140 			    sph->subpage) {
6141 				page_index = &lun->mode_pages.index[i];
6142 				page_len = scsi_2btoul(sph->page_length);
6143 				break;
6144 			}
6145 		}
6146 	}
6147 
6148 	/*
6149 	 * If we couldn't find the page, or if we don't have a mode select
6150 	 * handler for it, send back an error to the user.
6151 	 */
6152 	if ((page_index == NULL)
6153 	 || (page_index->select_handler == NULL)) {
6154 		ctl_set_invalid_field(ctsio,
6155 				      /*sks_valid*/ 1,
6156 				      /*command*/ 0,
6157 				      /*field*/ *len_used,
6158 				      /*bit_valid*/ 0,
6159 				      /*bit*/ 0);
6160 		free(ctsio->kern_data_ptr, M_CTL);
6161 		ctl_done((union ctl_io *)ctsio);
6162 		return (CTL_RETVAL_COMPLETE);
6163 	}
6164 
6165 	if (page_index->page_code & SMPH_SPF) {
6166 		page_len_offset = 2;
6167 		page_len_size = 2;
6168 	} else {
6169 		page_len_size = 1;
6170 		page_len_offset = 1;
6171 	}
6172 
6173 	/*
6174 	 * If the length the initiator gives us isn't the one we specify in
6175 	 * the mode page header, or if they didn't specify enough data in
6176 	 * the CDB to avoid truncating this page, kick out the request.
6177 	 */
6178 	if ((page_len != (page_index->page_len - page_len_offset -
6179 			  page_len_size))
6180 	 || (*len_left < page_index->page_len)) {
6181 
6182 
6183 		ctl_set_invalid_field(ctsio,
6184 				      /*sks_valid*/ 1,
6185 				      /*command*/ 0,
6186 				      /*field*/ *len_used + page_len_offset,
6187 				      /*bit_valid*/ 0,
6188 				      /*bit*/ 0);
6189 		free(ctsio->kern_data_ptr, M_CTL);
6190 		ctl_done((union ctl_io *)ctsio);
6191 		return (CTL_RETVAL_COMPLETE);
6192 	}
6193 
6194 	/*
6195 	 * Run through the mode page, checking to make sure that the bits
6196 	 * the user changed are actually legal for him to change.
6197 	 */
6198 	for (i = 0; i < page_index->page_len; i++) {
6199 		uint8_t *user_byte, *change_mask, *current_byte;
6200 		int bad_bit;
6201 		int j;
6202 
6203 		user_byte = (uint8_t *)page_header + i;
6204 		change_mask = page_index->page_data +
6205 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6206 		current_byte = page_index->page_data +
6207 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6208 
6209 		/*
6210 		 * Check to see whether the user set any bits in this byte
6211 		 * that he is not allowed to set.
6212 		 */
6213 		if ((*user_byte & ~(*change_mask)) ==
6214 		    (*current_byte & ~(*change_mask)))
6215 			continue;
6216 
6217 		/*
6218 		 * Go through bit by bit to determine which one is illegal.
6219 		 */
6220 		bad_bit = 0;
6221 		for (j = 7; j >= 0; j--) {
6222 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6223 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6224 				bad_bit = i;
6225 				break;
6226 			}
6227 		}
6228 		ctl_set_invalid_field(ctsio,
6229 				      /*sks_valid*/ 1,
6230 				      /*command*/ 0,
6231 				      /*field*/ *len_used + i,
6232 				      /*bit_valid*/ 1,
6233 				      /*bit*/ bad_bit);
6234 		free(ctsio->kern_data_ptr, M_CTL);
6235 		ctl_done((union ctl_io *)ctsio);
6236 		return (CTL_RETVAL_COMPLETE);
6237 	}
6238 
6239 	/*
6240 	 * Decrement these before we call the page handler, since we may
6241 	 * end up getting called back one way or another before the handler
6242 	 * returns to this context.
6243 	 */
6244 	*len_left -= page_index->page_len;
6245 	*len_used += page_index->page_len;
6246 
6247 	retval = page_index->select_handler(ctsio, page_index,
6248 					    (uint8_t *)page_header);
6249 
6250 	/*
6251 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6252 	 * wait until this queued command completes to finish processing
6253 	 * the mode page.  If it returns anything other than
6254 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6255 	 * already set the sense information, freed the data pointer, and
6256 	 * completed the io for us.
6257 	 */
6258 	if (retval != CTL_RETVAL_COMPLETE)
6259 		goto bailout_no_done;
6260 
6261 	/*
6262 	 * If the initiator sent us more than one page, parse the next one.
6263 	 */
6264 	if (*len_left > 0)
6265 		goto do_next_page;
6266 
6267 	ctl_set_success(ctsio);
6268 	free(ctsio->kern_data_ptr, M_CTL);
6269 	ctl_done((union ctl_io *)ctsio);
6270 
6271 bailout_no_done:
6272 
6273 	return (CTL_RETVAL_COMPLETE);
6274 
6275 }
6276 
6277 int
6278 ctl_mode_select(struct ctl_scsiio *ctsio)
6279 {
6280 	int param_len, pf, sp;
6281 	int header_size, bd_len;
6282 	int len_left, len_used;
6283 	struct ctl_page_index *page_index;
6284 	struct ctl_lun *lun;
6285 	int control_dev, page_len;
6286 	union ctl_modepage_info *modepage_info;
6287 	int retval;
6288 
6289 	pf = 0;
6290 	sp = 0;
6291 	page_len = 0;
6292 	len_used = 0;
6293 	len_left = 0;
6294 	retval = 0;
6295 	bd_len = 0;
6296 	page_index = NULL;
6297 
6298 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6299 
6300 	if (lun->be_lun->lun_type != T_DIRECT)
6301 		control_dev = 1;
6302 	else
6303 		control_dev = 0;
6304 
6305 	switch (ctsio->cdb[0]) {
6306 	case MODE_SELECT_6: {
6307 		struct scsi_mode_select_6 *cdb;
6308 
6309 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6310 
6311 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6312 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6313 
6314 		param_len = cdb->length;
6315 		header_size = sizeof(struct scsi_mode_header_6);
6316 		break;
6317 	}
6318 	case MODE_SELECT_10: {
6319 		struct scsi_mode_select_10 *cdb;
6320 
6321 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6322 
6323 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6324 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6325 
6326 		param_len = scsi_2btoul(cdb->length);
6327 		header_size = sizeof(struct scsi_mode_header_10);
6328 		break;
6329 	}
6330 	default:
6331 		ctl_set_invalid_opcode(ctsio);
6332 		ctl_done((union ctl_io *)ctsio);
6333 		return (CTL_RETVAL_COMPLETE);
6334 		break; /* NOTREACHED */
6335 	}
6336 
6337 	/*
6338 	 * From SPC-3:
6339 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6340 	 * shall be empty. This condition shall not be considered as an error."
6341 	 */
6342 	if (param_len == 0) {
6343 		ctl_set_success(ctsio);
6344 		ctl_done((union ctl_io *)ctsio);
6345 		return (CTL_RETVAL_COMPLETE);
6346 	}
6347 
6348 	/*
6349 	 * Since we'll hit this the first time through, prior to
6350 	 * allocation, we don't need to free a data buffer here.
6351 	 */
6352 	if (param_len < header_size) {
6353 		ctl_set_param_len_error(ctsio);
6354 		ctl_done((union ctl_io *)ctsio);
6355 		return (CTL_RETVAL_COMPLETE);
6356 	}
6357 
6358 	/*
6359 	 * Allocate the data buffer and grab the user's data.  In theory,
6360 	 * we shouldn't have to sanity check the parameter list length here
6361 	 * because the maximum size is 64K.  We should be able to malloc
6362 	 * that much without too many problems.
6363 	 */
6364 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6365 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6366 		if (ctsio->kern_data_ptr == NULL) {
6367 			ctl_set_busy(ctsio);
6368 			ctl_done((union ctl_io *)ctsio);
6369 			return (CTL_RETVAL_COMPLETE);
6370 		}
6371 		ctsio->kern_data_len = param_len;
6372 		ctsio->kern_total_len = param_len;
6373 		ctsio->kern_data_resid = 0;
6374 		ctsio->kern_rel_offset = 0;
6375 		ctsio->kern_sg_entries = 0;
6376 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6377 		ctsio->be_move_done = ctl_config_move_done;
6378 		ctl_datamove((union ctl_io *)ctsio);
6379 
6380 		return (CTL_RETVAL_COMPLETE);
6381 	}
6382 
6383 	switch (ctsio->cdb[0]) {
6384 	case MODE_SELECT_6: {
6385 		struct scsi_mode_header_6 *mh6;
6386 
6387 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6388 		bd_len = mh6->blk_desc_len;
6389 		break;
6390 	}
6391 	case MODE_SELECT_10: {
6392 		struct scsi_mode_header_10 *mh10;
6393 
6394 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6395 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6396 		break;
6397 	}
6398 	default:
6399 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6400 		break;
6401 	}
6402 
6403 	if (param_len < (header_size + bd_len)) {
6404 		free(ctsio->kern_data_ptr, M_CTL);
6405 		ctl_set_param_len_error(ctsio);
6406 		ctl_done((union ctl_io *)ctsio);
6407 		return (CTL_RETVAL_COMPLETE);
6408 	}
6409 
6410 	/*
6411 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6412 	 * ctl_config_write_done(), it'll get passed back to
6413 	 * ctl_do_mode_select() for further processing, or completion if
6414 	 * we're all done.
6415 	 */
6416 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6417 	ctsio->io_cont = ctl_do_mode_select;
6418 
6419 	modepage_info = (union ctl_modepage_info *)
6420 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6421 
6422 	memset(modepage_info, 0, sizeof(*modepage_info));
6423 
6424 	len_left = param_len - header_size - bd_len;
6425 	len_used = header_size + bd_len;
6426 
6427 	modepage_info->header.len_left = len_left;
6428 	modepage_info->header.len_used = len_used;
6429 
6430 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6431 }
6432 
6433 int
6434 ctl_mode_sense(struct ctl_scsiio *ctsio)
6435 {
6436 	struct ctl_lun *lun;
6437 	int pc, page_code, dbd, llba, subpage;
6438 	int alloc_len, page_len, header_len, total_len;
6439 	struct scsi_mode_block_descr *block_desc;
6440 	struct ctl_page_index *page_index;
6441 	int control_dev;
6442 
6443 	dbd = 0;
6444 	llba = 0;
6445 	block_desc = NULL;
6446 	page_index = NULL;
6447 
6448 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6449 
6450 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6451 
6452 	if (lun->be_lun->lun_type != T_DIRECT)
6453 		control_dev = 1;
6454 	else
6455 		control_dev = 0;
6456 
6457 	switch (ctsio->cdb[0]) {
6458 	case MODE_SENSE_6: {
6459 		struct scsi_mode_sense_6 *cdb;
6460 
6461 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6462 
6463 		header_len = sizeof(struct scsi_mode_hdr_6);
6464 		if (cdb->byte2 & SMS_DBD)
6465 			dbd = 1;
6466 		else
6467 			header_len += sizeof(struct scsi_mode_block_descr);
6468 
6469 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6470 		page_code = cdb->page & SMS_PAGE_CODE;
6471 		subpage = cdb->subpage;
6472 		alloc_len = cdb->length;
6473 		break;
6474 	}
6475 	case MODE_SENSE_10: {
6476 		struct scsi_mode_sense_10 *cdb;
6477 
6478 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6479 
6480 		header_len = sizeof(struct scsi_mode_hdr_10);
6481 
6482 		if (cdb->byte2 & SMS_DBD)
6483 			dbd = 1;
6484 		else
6485 			header_len += sizeof(struct scsi_mode_block_descr);
6486 		if (cdb->byte2 & SMS10_LLBAA)
6487 			llba = 1;
6488 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6489 		page_code = cdb->page & SMS_PAGE_CODE;
6490 		subpage = cdb->subpage;
6491 		alloc_len = scsi_2btoul(cdb->length);
6492 		break;
6493 	}
6494 	default:
6495 		ctl_set_invalid_opcode(ctsio);
6496 		ctl_done((union ctl_io *)ctsio);
6497 		return (CTL_RETVAL_COMPLETE);
6498 		break; /* NOTREACHED */
6499 	}
6500 
6501 	/*
6502 	 * We have to make a first pass through to calculate the size of
6503 	 * the pages that match the user's query.  Then we allocate enough
6504 	 * memory to hold it, and actually copy the data into the buffer.
6505 	 */
6506 	switch (page_code) {
6507 	case SMS_ALL_PAGES_PAGE: {
6508 		int i;
6509 
6510 		page_len = 0;
6511 
6512 		/*
6513 		 * At the moment, values other than 0 and 0xff here are
6514 		 * reserved according to SPC-3.
6515 		 */
6516 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6517 		 && (subpage != SMS_SUBPAGE_ALL)) {
6518 			ctl_set_invalid_field(ctsio,
6519 					      /*sks_valid*/ 1,
6520 					      /*command*/ 1,
6521 					      /*field*/ 3,
6522 					      /*bit_valid*/ 0,
6523 					      /*bit*/ 0);
6524 			ctl_done((union ctl_io *)ctsio);
6525 			return (CTL_RETVAL_COMPLETE);
6526 		}
6527 
6528 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6529 			if ((control_dev != 0)
6530 			 && (lun->mode_pages.index[i].page_flags &
6531 			     CTL_PAGE_FLAG_DISK_ONLY))
6532 				continue;
6533 
6534 			/*
6535 			 * We don't use this subpage if the user didn't
6536 			 * request all subpages.
6537 			 */
6538 			if ((lun->mode_pages.index[i].subpage != 0)
6539 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6540 				continue;
6541 
6542 #if 0
6543 			printf("found page %#x len %d\n",
6544 			       lun->mode_pages.index[i].page_code &
6545 			       SMPH_PC_MASK,
6546 			       lun->mode_pages.index[i].page_len);
6547 #endif
6548 			page_len += lun->mode_pages.index[i].page_len;
6549 		}
6550 		break;
6551 	}
6552 	default: {
6553 		int i;
6554 
6555 		page_len = 0;
6556 
6557 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6558 			/* Look for the right page code */
6559 			if ((lun->mode_pages.index[i].page_code &
6560 			     SMPH_PC_MASK) != page_code)
6561 				continue;
6562 
6563 			/* Look for the right subpage or the subpage wildcard*/
6564 			if ((lun->mode_pages.index[i].subpage != subpage)
6565 			 && (subpage != SMS_SUBPAGE_ALL))
6566 				continue;
6567 
6568 			/* Make sure the page is supported for this dev type */
6569 			if ((control_dev != 0)
6570 			 && (lun->mode_pages.index[i].page_flags &
6571 			     CTL_PAGE_FLAG_DISK_ONLY))
6572 				continue;
6573 
6574 #if 0
6575 			printf("found page %#x len %d\n",
6576 			       lun->mode_pages.index[i].page_code &
6577 			       SMPH_PC_MASK,
6578 			       lun->mode_pages.index[i].page_len);
6579 #endif
6580 
6581 			page_len += lun->mode_pages.index[i].page_len;
6582 		}
6583 
6584 		if (page_len == 0) {
6585 			ctl_set_invalid_field(ctsio,
6586 					      /*sks_valid*/ 1,
6587 					      /*command*/ 1,
6588 					      /*field*/ 2,
6589 					      /*bit_valid*/ 1,
6590 					      /*bit*/ 5);
6591 			ctl_done((union ctl_io *)ctsio);
6592 			return (CTL_RETVAL_COMPLETE);
6593 		}
6594 		break;
6595 	}
6596 	}
6597 
6598 	total_len = header_len + page_len;
6599 #if 0
6600 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6601 	       header_len, page_len, total_len);
6602 #endif
6603 
6604 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK);
6605 	if (ctsio->kern_data_ptr == NULL) {
6606 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
6607 		ctsio->scsi_status = SCSI_STATUS_BUSY;
6608 		ctl_done((union ctl_io *)ctsio);
6609 		return (CTL_RETVAL_COMPLETE);
6610 	}
6611 	ctsio->kern_sg_entries = 0;
6612 	ctsio->kern_data_resid = 0;
6613 	ctsio->kern_rel_offset = 0;
6614 	if (total_len < alloc_len) {
6615 		ctsio->residual = alloc_len - total_len;
6616 		ctsio->kern_data_len = total_len;
6617 		ctsio->kern_total_len = total_len;
6618 	} else {
6619 		ctsio->residual = 0;
6620 		ctsio->kern_data_len = alloc_len;
6621 		ctsio->kern_total_len = alloc_len;
6622 	}
6623 	memset(ctsio->kern_data_ptr, 0, total_len);
6624 
6625 	switch (ctsio->cdb[0]) {
6626 	case MODE_SENSE_6: {
6627 		struct scsi_mode_hdr_6 *header;
6628 
6629 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6630 
6631 		header->datalen = ctl_min(total_len - 1, 254);
6632 
6633 		if (dbd)
6634 			header->block_descr_len = 0;
6635 		else
6636 			header->block_descr_len =
6637 				sizeof(struct scsi_mode_block_descr);
6638 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6639 		break;
6640 	}
6641 	case MODE_SENSE_10: {
6642 		struct scsi_mode_hdr_10 *header;
6643 		int datalen;
6644 
6645 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6646 
6647 		datalen = ctl_min(total_len - 2, 65533);
6648 		scsi_ulto2b(datalen, header->datalen);
6649 		if (dbd)
6650 			scsi_ulto2b(0, header->block_descr_len);
6651 		else
6652 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6653 				    header->block_descr_len);
6654 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6655 		break;
6656 	}
6657 	default:
6658 		panic("invalid CDB type %#x", ctsio->cdb[0]);
6659 		break; /* NOTREACHED */
6660 	}
6661 
6662 	/*
6663 	 * If we've got a disk, use its blocksize in the block
6664 	 * descriptor.  Otherwise, just set it to 0.
6665 	 */
6666 	if (dbd == 0) {
6667 		if (control_dev != 0)
6668 			scsi_ulto3b(lun->be_lun->blocksize,
6669 				    block_desc->block_len);
6670 		else
6671 			scsi_ulto3b(0, block_desc->block_len);
6672 	}
6673 
6674 	switch (page_code) {
6675 	case SMS_ALL_PAGES_PAGE: {
6676 		int i, data_used;
6677 
6678 		data_used = header_len;
6679 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6680 			struct ctl_page_index *page_index;
6681 
6682 			page_index = &lun->mode_pages.index[i];
6683 
6684 			if ((control_dev != 0)
6685 			 && (page_index->page_flags &
6686 			    CTL_PAGE_FLAG_DISK_ONLY))
6687 				continue;
6688 
6689 			/*
6690 			 * We don't use this subpage if the user didn't
6691 			 * request all subpages.  We already checked (above)
6692 			 * to make sure the user only specified a subpage
6693 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6694 			 */
6695 			if ((page_index->subpage != 0)
6696 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6697 				continue;
6698 
6699 			/*
6700 			 * Call the handler, if it exists, to update the
6701 			 * page to the latest values.
6702 			 */
6703 			if (page_index->sense_handler != NULL)
6704 				page_index->sense_handler(ctsio, page_index,pc);
6705 
6706 			memcpy(ctsio->kern_data_ptr + data_used,
6707 			       page_index->page_data +
6708 			       (page_index->page_len * pc),
6709 			       page_index->page_len);
6710 			data_used += page_index->page_len;
6711 		}
6712 		break;
6713 	}
6714 	default: {
6715 		int i, data_used;
6716 
6717 		data_used = header_len;
6718 
6719 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6720 			struct ctl_page_index *page_index;
6721 
6722 			page_index = &lun->mode_pages.index[i];
6723 
6724 			/* Look for the right page code */
6725 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6726 				continue;
6727 
6728 			/* Look for the right subpage or the subpage wildcard*/
6729 			if ((page_index->subpage != subpage)
6730 			 && (subpage != SMS_SUBPAGE_ALL))
6731 				continue;
6732 
6733 			/* Make sure the page is supported for this dev type */
6734 			if ((control_dev != 0)
6735 			 && (page_index->page_flags &
6736 			     CTL_PAGE_FLAG_DISK_ONLY))
6737 				continue;
6738 
6739 			/*
6740 			 * Call the handler, if it exists, to update the
6741 			 * page to the latest values.
6742 			 */
6743 			if (page_index->sense_handler != NULL)
6744 				page_index->sense_handler(ctsio, page_index,pc);
6745 
6746 			memcpy(ctsio->kern_data_ptr + data_used,
6747 			       page_index->page_data +
6748 			       (page_index->page_len * pc),
6749 			       page_index->page_len);
6750 			data_used += page_index->page_len;
6751 		}
6752 		break;
6753 	}
6754 	}
6755 
6756 	ctsio->scsi_status = SCSI_STATUS_OK;
6757 
6758 	ctsio->be_move_done = ctl_config_move_done;
6759 	ctl_datamove((union ctl_io *)ctsio);
6760 
6761 	return (CTL_RETVAL_COMPLETE);
6762 }
6763 
6764 int
6765 ctl_read_capacity(struct ctl_scsiio *ctsio)
6766 {
6767 	struct scsi_read_capacity *cdb;
6768 	struct scsi_read_capacity_data *data;
6769 	struct ctl_lun *lun;
6770 	uint32_t lba;
6771 
6772 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6773 
6774 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6775 
6776 	lba = scsi_4btoul(cdb->addr);
6777 	if (((cdb->pmi & SRC_PMI) == 0)
6778 	 && (lba != 0)) {
6779 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6780 				      /*sks_valid*/ 1,
6781 				      /*command*/ 1,
6782 				      /*field*/ 2,
6783 				      /*bit_valid*/ 0,
6784 				      /*bit*/ 0);
6785 		ctl_done((union ctl_io *)ctsio);
6786 		return (CTL_RETVAL_COMPLETE);
6787 	}
6788 
6789 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6790 
6791 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK);
6792 	if (ctsio->kern_data_ptr == NULL) {
6793 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
6794 		ctsio->scsi_status = SCSI_STATUS_BUSY;
6795 		ctl_done((union ctl_io *)ctsio);
6796 		return (CTL_RETVAL_COMPLETE);
6797 	}
6798 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6799 	ctsio->residual = 0;
6800 	ctsio->kern_data_len = sizeof(*data);
6801 	ctsio->kern_total_len = sizeof(*data);
6802 	ctsio->kern_data_resid = 0;
6803 	ctsio->kern_rel_offset = 0;
6804 	ctsio->kern_sg_entries = 0;
6805 
6806 	memset(data, 0, sizeof(*data));
6807 
6808 	/*
6809 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6810 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6811 	 * serivce action set.
6812 	 */
6813 	if (lun->be_lun->maxlba > 0xfffffffe)
6814 		scsi_ulto4b(0xffffffff, data->addr);
6815 	else
6816 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6817 
6818 	/*
6819 	 * XXX KDM this may not be 512 bytes...
6820 	 */
6821 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6822 
6823 	ctsio->scsi_status = SCSI_STATUS_OK;
6824 
6825 	ctsio->be_move_done = ctl_config_move_done;
6826 	ctl_datamove((union ctl_io *)ctsio);
6827 
6828 	return (CTL_RETVAL_COMPLETE);
6829 }
6830 
6831 static int
6832 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6833 {
6834 	struct scsi_read_capacity_16 *cdb;
6835 	struct scsi_read_capacity_data_long *data;
6836 	struct ctl_lun *lun;
6837 	uint64_t lba;
6838 	uint32_t alloc_len;
6839 
6840 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6841 
6842 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6843 
6844 	alloc_len = scsi_4btoul(cdb->alloc_len);
6845 	lba = scsi_8btou64(cdb->addr);
6846 
6847 	if ((cdb->reladr & SRC16_PMI)
6848 	 && (lba != 0)) {
6849 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6850 				      /*sks_valid*/ 1,
6851 				      /*command*/ 1,
6852 				      /*field*/ 2,
6853 				      /*bit_valid*/ 0,
6854 				      /*bit*/ 0);
6855 		ctl_done((union ctl_io *)ctsio);
6856 		return (CTL_RETVAL_COMPLETE);
6857 	}
6858 
6859 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6860 
6861 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK);
6862 	if (ctsio->kern_data_ptr == NULL) {
6863 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
6864 		ctsio->scsi_status = SCSI_STATUS_BUSY;
6865 		ctl_done((union ctl_io *)ctsio);
6866 		return (CTL_RETVAL_COMPLETE);
6867 	}
6868 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6869 
6870 	if (sizeof(*data) < alloc_len) {
6871 		ctsio->residual = alloc_len - sizeof(*data);
6872 		ctsio->kern_data_len = sizeof(*data);
6873 		ctsio->kern_total_len = sizeof(*data);
6874 	} else {
6875 		ctsio->residual = 0;
6876 		ctsio->kern_data_len = alloc_len;
6877 		ctsio->kern_total_len = alloc_len;
6878 	}
6879 	ctsio->kern_data_resid = 0;
6880 	ctsio->kern_rel_offset = 0;
6881 	ctsio->kern_sg_entries = 0;
6882 
6883 	memset(data, 0, sizeof(*data));
6884 
6885 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6886 	/* XXX KDM this may not be 512 bytes... */
6887 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6888 
6889 	ctsio->scsi_status = SCSI_STATUS_OK;
6890 
6891 	ctsio->be_move_done = ctl_config_move_done;
6892 	ctl_datamove((union ctl_io *)ctsio);
6893 
6894 	return (CTL_RETVAL_COMPLETE);
6895 }
6896 
6897 int
6898 ctl_service_action_in(struct ctl_scsiio *ctsio)
6899 {
6900 	struct scsi_service_action_in *cdb;
6901 	int retval;
6902 
6903 	CTL_DEBUG_PRINT(("ctl_service_action_in\n"));
6904 
6905 	cdb = (struct scsi_service_action_in *)ctsio->cdb;
6906 
6907 	retval = CTL_RETVAL_COMPLETE;
6908 
6909 	switch (cdb->service_action) {
6910 	case SRC16_SERVICE_ACTION:
6911 		retval = ctl_read_capacity_16(ctsio);
6912 		break;
6913 	default:
6914 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6915 				      /*sks_valid*/ 1,
6916 				      /*command*/ 1,
6917 				      /*field*/ 1,
6918 				      /*bit_valid*/ 1,
6919 				      /*bit*/ 4);
6920 		ctl_done((union ctl_io *)ctsio);
6921 		break;
6922 	}
6923 
6924 	return (retval);
6925 }
6926 
6927 int
6928 ctl_maintenance_in(struct ctl_scsiio *ctsio)
6929 {
6930 	struct scsi_maintenance_in *cdb;
6931 	int retval;
6932 	int alloc_len, total_len = 0;
6933 	int num_target_port_groups;
6934 	struct ctl_lun *lun;
6935 	struct ctl_softc *softc;
6936 	struct scsi_target_group_data *rtg_ptr;
6937 	struct scsi_target_port_group_descriptor *tpg_desc_ptr1, *tpg_desc_ptr2;
6938 	struct scsi_target_port_descriptor  *tp_desc_ptr1_1, *tp_desc_ptr1_2,
6939 	                                    *tp_desc_ptr2_1, *tp_desc_ptr2_2;
6940 
6941 	CTL_DEBUG_PRINT(("ctl_maintenance_in\n"));
6942 
6943 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
6944 	softc = control_softc;
6945 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6946 
6947 	retval = CTL_RETVAL_COMPLETE;
6948 	mtx_lock(&softc->ctl_lock);
6949 
6950 	if ((cdb->byte2 & SERVICE_ACTION_MASK) != SA_RPRT_TRGT_GRP) {
6951 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6952 				      /*sks_valid*/ 1,
6953 				      /*command*/ 1,
6954 				      /*field*/ 1,
6955 				      /*bit_valid*/ 1,
6956 				      /*bit*/ 4);
6957 		ctl_done((union ctl_io *)ctsio);
6958 		return(retval);
6959 	}
6960 
6961 	if (ctl_is_single)
6962         	num_target_port_groups = NUM_TARGET_PORT_GROUPS - 1;
6963 	else
6964         	num_target_port_groups = NUM_TARGET_PORT_GROUPS;
6965 
6966 	total_len = sizeof(struct scsi_target_group_data) +
6967 		sizeof(struct scsi_target_port_group_descriptor) *
6968 		num_target_port_groups +
6969 		sizeof(struct scsi_target_port_descriptor) *
6970 		NUM_PORTS_PER_GRP * num_target_port_groups;
6971 
6972 	alloc_len = scsi_4btoul(cdb->length);
6973 
6974 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK);
6975 	if (ctsio->kern_data_ptr == NULL) {
6976 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
6977 		ctsio->scsi_status = SCSI_STATUS_BUSY;
6978 		ctl_done((union ctl_io *)ctsio);
6979 		return (CTL_RETVAL_COMPLETE);
6980 	}
6981 	memset(ctsio->kern_data_ptr, 0, total_len);
6982 
6983 	ctsio->kern_sg_entries = 0;
6984 
6985 	if (total_len < alloc_len) {
6986 		ctsio->residual = alloc_len - total_len;
6987 		ctsio->kern_data_len = total_len;
6988 		ctsio->kern_total_len = total_len;
6989 	} else {
6990 		ctsio->residual = 0;
6991 		ctsio->kern_data_len = alloc_len;
6992 		ctsio->kern_total_len = alloc_len;
6993 	}
6994 	ctsio->kern_data_resid = 0;
6995 	ctsio->kern_rel_offset = 0;
6996 
6997 	rtg_ptr = (struct scsi_target_group_data *)ctsio->kern_data_ptr;
6998 
6999 	tpg_desc_ptr1 = &rtg_ptr->groups[0];
7000 	tp_desc_ptr1_1 = &tpg_desc_ptr1->descriptors[0];
7001 	tp_desc_ptr1_2 = (struct scsi_target_port_descriptor *)
7002 	        &tp_desc_ptr1_1->desc_list[0];
7003 
7004 
7005 
7006 	if (ctl_is_single == 0) {
7007 		tpg_desc_ptr2 = (struct scsi_target_port_group_descriptor *)
7008 	                &tp_desc_ptr1_2->desc_list[0];
7009 		tp_desc_ptr2_1 = &tpg_desc_ptr2->descriptors[0];
7010 		tp_desc_ptr2_2 = (struct scsi_target_port_descriptor *)
7011 	        	&tp_desc_ptr2_1->desc_list[0];
7012         } else {
7013 		tpg_desc_ptr2 = NULL;
7014 		tp_desc_ptr2_1 = NULL;
7015 		tp_desc_ptr2_2 = NULL;
7016 	}
7017 
7018 	scsi_ulto4b(total_len - 4, rtg_ptr->length);
7019 	if (ctl_is_single == 0) {
7020         	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7021 			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7022 				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7023 				tpg_desc_ptr2->pref_state =
7024 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7025 			} else {
7026 				tpg_desc_ptr1->pref_state =
7027 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7028 				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7029 			}
7030 		} else {
7031 			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7032 				tpg_desc_ptr1->pref_state =
7033 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7034 				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7035 			} else {
7036 				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7037 				tpg_desc_ptr2->pref_state =
7038 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7039 			}
7040 		}
7041 	} else {
7042 		tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7043 	}
7044 	tpg_desc_ptr1->support = 0;
7045 	tpg_desc_ptr1->target_port_group[1] = 1;
7046 	tpg_desc_ptr1->status = TPG_IMPLICIT;
7047 	tpg_desc_ptr1->target_port_count= NUM_PORTS_PER_GRP;
7048 
7049 	if (ctl_is_single == 0) {
7050 		tpg_desc_ptr2->support = 0;
7051 		tpg_desc_ptr2->target_port_group[1] = 2;
7052 		tpg_desc_ptr2->status = TPG_IMPLICIT;
7053 		tpg_desc_ptr2->target_port_count = NUM_PORTS_PER_GRP;
7054 
7055 		tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7056 		tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7057 
7058 		tp_desc_ptr2_1->relative_target_port_identifier[1] = 9;
7059 		tp_desc_ptr2_2->relative_target_port_identifier[1] = 10;
7060 	} else {
7061         	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7062 			tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7063 			tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7064 		} else {
7065 			tp_desc_ptr1_1->relative_target_port_identifier[1] = 9;
7066 			tp_desc_ptr1_2->relative_target_port_identifier[1] = 10;
7067 		}
7068 	}
7069 
7070 	mtx_unlock(&softc->ctl_lock);
7071 
7072 	ctsio->be_move_done = ctl_config_move_done;
7073 
7074 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7075 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7076 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7077 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7078 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7079 
7080 	ctl_datamove((union ctl_io *)ctsio);
7081 	return(retval);
7082 }
7083 
7084 int
7085 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7086 {
7087 	struct scsi_per_res_in *cdb;
7088 	int alloc_len, total_len = 0;
7089 	/* struct scsi_per_res_in_rsrv in_data; */
7090 	struct ctl_lun *lun;
7091 	struct ctl_softc *softc;
7092 
7093 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7094 
7095 	softc = control_softc;
7096 
7097 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7098 
7099 	alloc_len = scsi_2btoul(cdb->length);
7100 
7101 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7102 
7103 retry:
7104 	mtx_lock(&softc->ctl_lock);
7105 	switch (cdb->action) {
7106 	case SPRI_RK: /* read keys */
7107 		total_len = sizeof(struct scsi_per_res_in_keys) +
7108 			lun->pr_key_count *
7109 			sizeof(struct scsi_per_res_key);
7110 		break;
7111 	case SPRI_RR: /* read reservation */
7112 		if (lun->flags & CTL_LUN_PR_RESERVED)
7113 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7114 		else
7115 			total_len = sizeof(struct scsi_per_res_in_header);
7116 		break;
7117 	case SPRI_RC: /* report capabilities */
7118 		total_len = sizeof(struct scsi_per_res_cap);
7119 		break;
7120 	case SPRI_RS: /* read full status */
7121 	default:
7122 		mtx_unlock(&softc->ctl_lock);
7123 		ctl_set_invalid_field(ctsio,
7124 				      /*sks_valid*/ 1,
7125 				      /*command*/ 1,
7126 				      /*field*/ 1,
7127 				      /*bit_valid*/ 1,
7128 				      /*bit*/ 0);
7129 		ctl_done((union ctl_io *)ctsio);
7130 		return (CTL_RETVAL_COMPLETE);
7131 		break; /* NOTREACHED */
7132 	}
7133 	mtx_unlock(&softc->ctl_lock);
7134 
7135 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK);
7136 	if (ctsio->kern_data_ptr == NULL) {
7137 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
7138 		ctsio->scsi_status = SCSI_STATUS_BUSY;
7139 		ctl_done((union ctl_io *)ctsio);
7140 		return (CTL_RETVAL_COMPLETE);
7141 	}
7142 
7143 	if (total_len < alloc_len) {
7144 		ctsio->residual = alloc_len - total_len;
7145 		ctsio->kern_data_len = total_len;
7146 		ctsio->kern_total_len = total_len;
7147 	} else {
7148 		ctsio->residual = 0;
7149 		ctsio->kern_data_len = alloc_len;
7150 		ctsio->kern_total_len = alloc_len;
7151 	}
7152 
7153 	ctsio->kern_data_resid = 0;
7154 	ctsio->kern_rel_offset = 0;
7155 	ctsio->kern_sg_entries = 0;
7156 
7157 	memset(ctsio->kern_data_ptr, 0, total_len);
7158 
7159 	mtx_lock(&softc->ctl_lock);
7160 	switch (cdb->action) {
7161 	case SPRI_RK: { // read keys
7162         struct scsi_per_res_in_keys *res_keys;
7163 		int i, key_count;
7164 
7165 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7166 
7167 		/*
7168 		 * We had to drop the lock to allocate our buffer, which
7169 		 * leaves time for someone to come in with another
7170 		 * persistent reservation.  (That is unlikely, though,
7171 		 * since this should be the only persistent reservation
7172 		 * command active right now.)
7173 		 */
7174 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7175 		    (lun->pr_key_count *
7176 		     sizeof(struct scsi_per_res_key)))){
7177 			mtx_unlock(&softc->ctl_lock);
7178 			free(ctsio->kern_data_ptr, M_CTL);
7179 			printf("%s: reservation length changed, retrying\n",
7180 			       __func__);
7181 			goto retry;
7182 		}
7183 
7184 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7185 
7186 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7187 			     lun->pr_key_count, res_keys->header.length);
7188 
7189 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7190 			if (!lun->per_res[i].registered)
7191 				continue;
7192 
7193 			/*
7194 			 * We used lun->pr_key_count to calculate the
7195 			 * size to allocate.  If it turns out the number of
7196 			 * initiators with the registered flag set is
7197 			 * larger than that (i.e. they haven't been kept in
7198 			 * sync), we've got a problem.
7199 			 */
7200 			if (key_count >= lun->pr_key_count) {
7201 #ifdef NEEDTOPORT
7202 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7203 					    CTL_PR_ERROR,
7204 					    csevent_LogType_Fault,
7205 					    csevent_AlertLevel_Yellow,
7206 					    csevent_FRU_ShelfController,
7207 					    csevent_FRU_Firmware,
7208 				        csevent_FRU_Unknown,
7209 					    "registered keys %d >= key "
7210 					    "count %d", key_count,
7211 					    lun->pr_key_count);
7212 #endif
7213 				key_count++;
7214 				continue;
7215 			}
7216 			memcpy(res_keys->keys[key_count].key,
7217 			       lun->per_res[i].res_key.key,
7218 			       ctl_min(sizeof(res_keys->keys[key_count].key),
7219 			       sizeof(lun->per_res[i].res_key)));
7220 			key_count++;
7221 		}
7222 		break;
7223 	}
7224 	case SPRI_RR: { // read reservation
7225 		struct scsi_per_res_in_rsrv *res;
7226 		int tmp_len, header_only;
7227 
7228 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7229 
7230 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7231 
7232 		if (lun->flags & CTL_LUN_PR_RESERVED)
7233 		{
7234 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7235 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7236 				    res->header.length);
7237 			header_only = 0;
7238 		} else {
7239 			tmp_len = sizeof(struct scsi_per_res_in_header);
7240 			scsi_ulto4b(0, res->header.length);
7241 			header_only = 1;
7242 		}
7243 
7244 		/*
7245 		 * We had to drop the lock to allocate our buffer, which
7246 		 * leaves time for someone to come in with another
7247 		 * persistent reservation.  (That is unlikely, though,
7248 		 * since this should be the only persistent reservation
7249 		 * command active right now.)
7250 		 */
7251 		if (tmp_len != total_len) {
7252 			mtx_unlock(&softc->ctl_lock);
7253 			free(ctsio->kern_data_ptr, M_CTL);
7254 			printf("%s: reservation status changed, retrying\n",
7255 			       __func__);
7256 			goto retry;
7257 		}
7258 
7259 		/*
7260 		 * No reservation held, so we're done.
7261 		 */
7262 		if (header_only != 0)
7263 			break;
7264 
7265 		/*
7266 		 * If the registration is an All Registrants type, the key
7267 		 * is 0, since it doesn't really matter.
7268 		 */
7269 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7270 			memcpy(res->data.reservation,
7271 			       &lun->per_res[lun->pr_res_idx].res_key,
7272 			       sizeof(struct scsi_per_res_key));
7273 		}
7274 		res->data.scopetype = lun->res_type;
7275 		break;
7276 	}
7277 	case SPRI_RC:     //report capabilities
7278 	{
7279 		struct scsi_per_res_cap *res_cap;
7280 		uint16_t type_mask;
7281 
7282 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7283 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7284 		res_cap->flags2 |= SPRI_TMV;
7285 		type_mask = SPRI_TM_WR_EX_AR |
7286 			    SPRI_TM_EX_AC_RO |
7287 			    SPRI_TM_WR_EX_RO |
7288 			    SPRI_TM_EX_AC |
7289 			    SPRI_TM_WR_EX |
7290 			    SPRI_TM_EX_AC_AR;
7291 		scsi_ulto2b(type_mask, res_cap->type_mask);
7292 		break;
7293 	}
7294 	case SPRI_RS: //read full status
7295 	default:
7296 		/*
7297 		 * This is a bug, because we just checked for this above,
7298 		 * and should have returned an error.
7299 		 */
7300 		panic("Invalid PR type %x", cdb->action);
7301 		break; /* NOTREACHED */
7302 	}
7303 	mtx_unlock(&softc->ctl_lock);
7304 
7305 	ctsio->be_move_done = ctl_config_move_done;
7306 
7307 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7308 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7309 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7310 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7311 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7312 
7313 	ctl_datamove((union ctl_io *)ctsio);
7314 
7315 	return (CTL_RETVAL_COMPLETE);
7316 }
7317 
7318 /*
7319  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7320  * it should return.
7321  */
7322 static int
7323 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7324 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7325 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7326 		struct scsi_per_res_out_parms* param)
7327 {
7328 	union ctl_ha_msg persis_io;
7329 	int retval, i;
7330 	int isc_retval;
7331 
7332 	retval = 0;
7333 
7334 	if (sa_res_key == 0) {
7335 		mtx_lock(&softc->ctl_lock);
7336 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7337 			/* validate scope and type */
7338 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7339 			     SPR_LU_SCOPE) {
7340 				mtx_unlock(&softc->ctl_lock);
7341 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7342 						      /*sks_valid*/ 1,
7343 						      /*command*/ 1,
7344 						      /*field*/ 2,
7345 						      /*bit_valid*/ 1,
7346 						      /*bit*/ 4);
7347 				ctl_done((union ctl_io *)ctsio);
7348 				return (1);
7349 			}
7350 
7351 		        if (type>8 || type==2 || type==4 || type==0) {
7352 				mtx_unlock(&softc->ctl_lock);
7353 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7354        	           				      /*sks_valid*/ 1,
7355 						      /*command*/ 1,
7356 						      /*field*/ 2,
7357 						      /*bit_valid*/ 1,
7358 						      /*bit*/ 0);
7359 				ctl_done((union ctl_io *)ctsio);
7360 				return (1);
7361 		        }
7362 
7363 			/* temporarily unregister this nexus */
7364 			lun->per_res[residx].registered = 0;
7365 
7366 			/*
7367 			 * Unregister everybody else and build UA for
7368 			 * them
7369 			 */
7370 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7371 				if (lun->per_res[i].registered == 0)
7372 					continue;
7373 
7374 				if (!persis_offset
7375 				 && i <CTL_MAX_INITIATORS)
7376 					lun->pending_sense[i].ua_pending |=
7377 						CTL_UA_REG_PREEMPT;
7378 				else if (persis_offset
7379 				      && i >= persis_offset)
7380 					lun->pending_sense[i-persis_offset
7381 						].ua_pending |=
7382 						CTL_UA_REG_PREEMPT;
7383 				lun->per_res[i].registered = 0;
7384 				memset(&lun->per_res[i].res_key, 0,
7385 				       sizeof(struct scsi_per_res_key));
7386 			}
7387 			lun->per_res[residx].registered = 1;
7388 			lun->pr_key_count = 1;
7389 			lun->res_type = type;
7390 			if (lun->res_type != SPR_TYPE_WR_EX_AR
7391 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7392 				lun->pr_res_idx = residx;
7393 
7394 			mtx_unlock(&softc->ctl_lock);
7395 			/* send msg to other side */
7396 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7397 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7398 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7399 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7400 			persis_io.pr.pr_info.res_type = type;
7401 			memcpy(persis_io.pr.pr_info.sa_res_key,
7402 			       param->serv_act_res_key,
7403 			       sizeof(param->serv_act_res_key));
7404 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7405 			     &persis_io, sizeof(persis_io), 0)) >
7406 			     CTL_HA_STATUS_SUCCESS) {
7407 				printf("CTL:Persis Out error returned "
7408 				       "from ctl_ha_msg_send %d\n",
7409 				       isc_retval);
7410 			}
7411 		} else {
7412 			/* not all registrants */
7413 			mtx_unlock(&softc->ctl_lock);
7414 			free(ctsio->kern_data_ptr, M_CTL);
7415 			ctl_set_invalid_field(ctsio,
7416 					      /*sks_valid*/ 1,
7417 					      /*command*/ 0,
7418 					      /*field*/ 8,
7419 					      /*bit_valid*/ 0,
7420 					      /*bit*/ 0);
7421 			ctl_done((union ctl_io *)ctsio);
7422 			return (1);
7423 		}
7424 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7425 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7426 		int found = 0;
7427 
7428 		mtx_lock(&softc->ctl_lock);
7429 		if (res_key == sa_res_key) {
7430 			/* special case */
7431 			/*
7432 			 * The spec implies this is not good but doesn't
7433 			 * say what to do. There are two choices either
7434 			 * generate a res conflict or check condition
7435 			 * with illegal field in parameter data. Since
7436 			 * that is what is done when the sa_res_key is
7437 			 * zero I'll take that approach since this has
7438 			 * to do with the sa_res_key.
7439 			 */
7440 			mtx_unlock(&softc->ctl_lock);
7441 			free(ctsio->kern_data_ptr, M_CTL);
7442 			ctl_set_invalid_field(ctsio,
7443 					      /*sks_valid*/ 1,
7444 					      /*command*/ 0,
7445 					      /*field*/ 8,
7446 					      /*bit_valid*/ 0,
7447 					      /*bit*/ 0);
7448 			ctl_done((union ctl_io *)ctsio);
7449 			return (1);
7450 		}
7451 
7452 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7453 			if (lun->per_res[i].registered
7454 			 && memcmp(param->serv_act_res_key,
7455 			    lun->per_res[i].res_key.key,
7456 			    sizeof(struct scsi_per_res_key)) != 0)
7457 				continue;
7458 
7459 			found = 1;
7460 			lun->per_res[i].registered = 0;
7461 			memset(&lun->per_res[i].res_key, 0,
7462 			       sizeof(struct scsi_per_res_key));
7463 			lun->pr_key_count--;
7464 
7465 			if (!persis_offset
7466 			 && i < CTL_MAX_INITIATORS)
7467 				lun->pending_sense[i].ua_pending |=
7468 					CTL_UA_REG_PREEMPT;
7469 			else if (persis_offset
7470 			      && i >= persis_offset)
7471 				lun->pending_sense[i-persis_offset].ua_pending|=
7472 					CTL_UA_REG_PREEMPT;
7473 		}
7474 		mtx_unlock(&softc->ctl_lock);
7475 		if (!found) {
7476 			free(ctsio->kern_data_ptr, M_CTL);
7477 			ctl_set_reservation_conflict(ctsio);
7478 			ctl_done((union ctl_io *)ctsio);
7479 			return (CTL_RETVAL_COMPLETE);
7480 		}
7481 		/* send msg to other side */
7482 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7483 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7484 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7485 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7486 		persis_io.pr.pr_info.res_type = type;
7487 		memcpy(persis_io.pr.pr_info.sa_res_key,
7488 		       param->serv_act_res_key,
7489 		       sizeof(param->serv_act_res_key));
7490 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7491 		     &persis_io, sizeof(persis_io), 0)) >
7492 		     CTL_HA_STATUS_SUCCESS) {
7493 			printf("CTL:Persis Out error returned from "
7494 			       "ctl_ha_msg_send %d\n", isc_retval);
7495 		}
7496 	} else {
7497 		/* Reserved but not all registrants */
7498 		/* sa_res_key is res holder */
7499 		if (memcmp(param->serv_act_res_key,
7500                    lun->per_res[lun->pr_res_idx].res_key.key,
7501                    sizeof(struct scsi_per_res_key)) == 0) {
7502 			/* validate scope and type */
7503 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7504 			     SPR_LU_SCOPE) {
7505 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7506 						      /*sks_valid*/ 1,
7507 						      /*command*/ 1,
7508 						      /*field*/ 2,
7509 						      /*bit_valid*/ 1,
7510 						      /*bit*/ 4);
7511 				ctl_done((union ctl_io *)ctsio);
7512 				return (1);
7513 			}
7514 
7515 			if (type>8 || type==2 || type==4 || type==0) {
7516 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7517 						      /*sks_valid*/ 1,
7518 						      /*command*/ 1,
7519 						      /*field*/ 2,
7520 						      /*bit_valid*/ 1,
7521 						      /*bit*/ 0);
7522 				ctl_done((union ctl_io *)ctsio);
7523 				return (1);
7524 			}
7525 
7526 			/*
7527 			 * Do the following:
7528 			 * if sa_res_key != res_key remove all
7529 			 * registrants w/sa_res_key and generate UA
7530 			 * for these registrants(Registrations
7531 			 * Preempted) if it wasn't an exclusive
7532 			 * reservation generate UA(Reservations
7533 			 * Preempted) for all other registered nexuses
7534 			 * if the type has changed. Establish the new
7535 			 * reservation and holder. If res_key and
7536 			 * sa_res_key are the same do the above
7537 			 * except don't unregister the res holder.
7538 			 */
7539 
7540 			/*
7541 			 * Temporarily unregister so it won't get
7542 			 * removed or UA generated
7543 			 */
7544 			lun->per_res[residx].registered = 0;
7545 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7546 				if (lun->per_res[i].registered == 0)
7547 					continue;
7548 
7549 				if (memcmp(param->serv_act_res_key,
7550 				    lun->per_res[i].res_key.key,
7551 				    sizeof(struct scsi_per_res_key)) == 0) {
7552 					lun->per_res[i].registered = 0;
7553 					memset(&lun->per_res[i].res_key,
7554 					       0,
7555 					       sizeof(struct scsi_per_res_key));
7556 					lun->pr_key_count--;
7557 
7558 					if (!persis_offset
7559 					 && i < CTL_MAX_INITIATORS)
7560 						lun->pending_sense[i
7561 							].ua_pending |=
7562 							CTL_UA_REG_PREEMPT;
7563 					else if (persis_offset
7564 					      && i >= persis_offset)
7565 						lun->pending_sense[
7566 						  i-persis_offset].ua_pending |=
7567 						  CTL_UA_REG_PREEMPT;
7568 				} else if (type != lun->res_type
7569 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7570 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7571 						if (!persis_offset
7572 						 && i < CTL_MAX_INITIATORS)
7573 							lun->pending_sense[i
7574 							].ua_pending |=
7575 							CTL_UA_RES_RELEASE;
7576 						else if (persis_offset
7577 						      && i >= persis_offset)
7578 							lun->pending_sense[
7579 							i-persis_offset
7580 							].ua_pending |=
7581 							CTL_UA_RES_RELEASE;
7582 				}
7583 			}
7584 			lun->per_res[residx].registered = 1;
7585 			lun->res_type = type;
7586 			if (lun->res_type != SPR_TYPE_WR_EX_AR
7587 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7588 				lun->pr_res_idx = residx;
7589 			else
7590 				lun->pr_res_idx =
7591 					CTL_PR_ALL_REGISTRANTS;
7592 
7593 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7594 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7595 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7596 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7597 			persis_io.pr.pr_info.res_type = type;
7598 			memcpy(persis_io.pr.pr_info.sa_res_key,
7599 			       param->serv_act_res_key,
7600 			       sizeof(param->serv_act_res_key));
7601 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7602 			     &persis_io, sizeof(persis_io), 0)) >
7603 			     CTL_HA_STATUS_SUCCESS) {
7604 				printf("CTL:Persis Out error returned "
7605 				       "from ctl_ha_msg_send %d\n",
7606 				       isc_retval);
7607 			}
7608 		} else {
7609 			/*
7610 			 * sa_res_key is not the res holder just
7611 			 * remove registrants
7612 			 */
7613 			int found=0;
7614 			mtx_lock(&softc->ctl_lock);
7615 
7616 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7617 				if (memcmp(param->serv_act_res_key,
7618 				    lun->per_res[i].res_key.key,
7619 				    sizeof(struct scsi_per_res_key)) != 0)
7620 					continue;
7621 
7622 				found = 1;
7623 				lun->per_res[i].registered = 0;
7624 				memset(&lun->per_res[i].res_key, 0,
7625 				       sizeof(struct scsi_per_res_key));
7626 				lun->pr_key_count--;
7627 
7628 				if (!persis_offset
7629 				 && i < CTL_MAX_INITIATORS)
7630 					lun->pending_sense[i].ua_pending |=
7631 						CTL_UA_REG_PREEMPT;
7632 				else if (persis_offset
7633 				      && i >= persis_offset)
7634 					lun->pending_sense[
7635 						i-persis_offset].ua_pending |=
7636 						CTL_UA_REG_PREEMPT;
7637 			}
7638 
7639 			if (!found) {
7640 				mtx_unlock(&softc->ctl_lock);
7641 				free(ctsio->kern_data_ptr, M_CTL);
7642 				ctl_set_reservation_conflict(ctsio);
7643 				ctl_done((union ctl_io *)ctsio);
7644 		        	return (1);
7645 			}
7646 			mtx_unlock(&softc->ctl_lock);
7647 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7648 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7649 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7650 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7651 			persis_io.pr.pr_info.res_type = type;
7652 			memcpy(persis_io.pr.pr_info.sa_res_key,
7653 			       param->serv_act_res_key,
7654 			       sizeof(param->serv_act_res_key));
7655 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7656 			     &persis_io, sizeof(persis_io), 0)) >
7657 			     CTL_HA_STATUS_SUCCESS) {
7658 				printf("CTL:Persis Out error returned "
7659 				       "from ctl_ha_msg_send %d\n",
7660 				isc_retval);
7661 			}
7662 		}
7663 	}
7664 
7665 	lun->PRGeneration++;
7666 
7667 	return (retval);
7668 }
7669 
7670 static void
7671 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7672 {
7673 	int i;
7674 
7675 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7676 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7677 	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
7678 		   msg->pr.pr_info.sa_res_key,
7679 		   sizeof(struct scsi_per_res_key)) != 0) {
7680 		uint64_t sa_res_key;
7681 		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7682 
7683 		if (sa_res_key == 0) {
7684 			/* temporarily unregister this nexus */
7685 			lun->per_res[msg->pr.pr_info.residx].registered = 0;
7686 
7687 			/*
7688 			 * Unregister everybody else and build UA for
7689 			 * them
7690 			 */
7691 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7692 				if (lun->per_res[i].registered == 0)
7693 					continue;
7694 
7695 				if (!persis_offset
7696 				 && i < CTL_MAX_INITIATORS)
7697 					lun->pending_sense[i].ua_pending |=
7698 						CTL_UA_REG_PREEMPT;
7699 				else if (persis_offset && i >= persis_offset)
7700 					lun->pending_sense[i -
7701 						persis_offset].ua_pending |=
7702 						CTL_UA_REG_PREEMPT;
7703 				lun->per_res[i].registered = 0;
7704 				memset(&lun->per_res[i].res_key, 0,
7705 				       sizeof(struct scsi_per_res_key));
7706 			}
7707 
7708 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
7709 			lun->pr_key_count = 1;
7710 			lun->res_type = msg->pr.pr_info.res_type;
7711 			if (lun->res_type != SPR_TYPE_WR_EX_AR
7712 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7713 				lun->pr_res_idx = msg->pr.pr_info.residx;
7714 		} else {
7715 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7716 				if (memcmp(msg->pr.pr_info.sa_res_key,
7717 		                   lun->per_res[i].res_key.key,
7718 		                   sizeof(struct scsi_per_res_key)) != 0)
7719 					continue;
7720 
7721 				lun->per_res[i].registered = 0;
7722 				memset(&lun->per_res[i].res_key, 0,
7723 				       sizeof(struct scsi_per_res_key));
7724 				lun->pr_key_count--;
7725 
7726 				if (!persis_offset
7727 				 && i < persis_offset)
7728 					lun->pending_sense[i].ua_pending |=
7729 						CTL_UA_REG_PREEMPT;
7730 				else if (persis_offset
7731 				      && i >= persis_offset)
7732 					lun->pending_sense[i -
7733 						persis_offset].ua_pending |=
7734 						CTL_UA_REG_PREEMPT;
7735 			}
7736 		}
7737 	} else {
7738 		/*
7739 		 * Temporarily unregister so it won't get removed
7740 		 * or UA generated
7741 		 */
7742 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
7743 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7744 			if (lun->per_res[i].registered == 0)
7745 				continue;
7746 
7747 			if (memcmp(msg->pr.pr_info.sa_res_key,
7748 	                   lun->per_res[i].res_key.key,
7749 	                   sizeof(struct scsi_per_res_key)) == 0) {
7750 				lun->per_res[i].registered = 0;
7751 				memset(&lun->per_res[i].res_key, 0,
7752 				       sizeof(struct scsi_per_res_key));
7753 				lun->pr_key_count--;
7754 				if (!persis_offset
7755 				 && i < CTL_MAX_INITIATORS)
7756 					lun->pending_sense[i].ua_pending |=
7757 						CTL_UA_REG_PREEMPT;
7758 				else if (persis_offset
7759 				      && i >= persis_offset)
7760 					lun->pending_sense[i -
7761 						persis_offset].ua_pending |=
7762 						CTL_UA_REG_PREEMPT;
7763 			} else if (msg->pr.pr_info.res_type != lun->res_type
7764 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
7765 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
7766 					if (!persis_offset
7767 					 && i < persis_offset)
7768 						lun->pending_sense[i
7769 							].ua_pending |=
7770 							CTL_UA_RES_RELEASE;
7771 					else if (persis_offset
7772 					      && i >= persis_offset)
7773 					lun->pending_sense[i -
7774 						persis_offset].ua_pending |=
7775 						CTL_UA_RES_RELEASE;
7776 			}
7777 		}
7778 		lun->per_res[msg->pr.pr_info.residx].registered = 1;
7779 		lun->res_type = msg->pr.pr_info.res_type;
7780 		if (lun->res_type != SPR_TYPE_WR_EX_AR
7781 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
7782 			lun->pr_res_idx = msg->pr.pr_info.residx;
7783 		else
7784 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7785 	}
7786 	lun->PRGeneration++;
7787 
7788 }
7789 
7790 
7791 int
7792 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
7793 {
7794 	int retval;
7795 	int isc_retval;
7796 	u_int32_t param_len;
7797 	struct scsi_per_res_out *cdb;
7798 	struct ctl_lun *lun;
7799 	struct scsi_per_res_out_parms* param;
7800 	struct ctl_softc *softc;
7801 	uint32_t residx;
7802 	uint64_t res_key, sa_res_key;
7803 	uint8_t type;
7804 	union ctl_ha_msg persis_io;
7805 	int    i;
7806 
7807 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
7808 
7809 	retval = CTL_RETVAL_COMPLETE;
7810 
7811 	softc = control_softc;
7812 
7813 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
7814 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7815 
7816 	/*
7817 	 * We only support whole-LUN scope.  The scope & type are ignored for
7818 	 * register, register and ignore existing key and clear.
7819 	 * We sometimes ignore scope and type on preempts too!!
7820 	 * Verify reservation type here as well.
7821 	 */
7822 	type = cdb->scope_type & SPR_TYPE_MASK;
7823 	if ((cdb->action == SPRO_RESERVE)
7824 	 || (cdb->action == SPRO_RELEASE)) {
7825 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
7826 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7827 					      /*sks_valid*/ 1,
7828 					      /*command*/ 1,
7829 					      /*field*/ 2,
7830 					      /*bit_valid*/ 1,
7831 					      /*bit*/ 4);
7832 			ctl_done((union ctl_io *)ctsio);
7833 			return (CTL_RETVAL_COMPLETE);
7834 		}
7835 
7836 		if (type>8 || type==2 || type==4 || type==0) {
7837 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7838 					      /*sks_valid*/ 1,
7839 					      /*command*/ 1,
7840 					      /*field*/ 2,
7841 					      /*bit_valid*/ 1,
7842 					      /*bit*/ 0);
7843 			ctl_done((union ctl_io *)ctsio);
7844 			return (CTL_RETVAL_COMPLETE);
7845 		}
7846 	}
7847 
7848 	switch (cdb->action & SPRO_ACTION_MASK) {
7849 	case SPRO_REGISTER:
7850 	case SPRO_RESERVE:
7851 	case SPRO_RELEASE:
7852 	case SPRO_CLEAR:
7853 	case SPRO_PREEMPT:
7854 	case SPRO_REG_IGNO:
7855 		break;
7856 	case SPRO_REG_MOVE:
7857 	case SPRO_PRE_ABO:
7858 	default:
7859 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7860 				      /*sks_valid*/ 1,
7861 				      /*command*/ 1,
7862 				      /*field*/ 1,
7863 				      /*bit_valid*/ 1,
7864 				      /*bit*/ 0);
7865 		ctl_done((union ctl_io *)ctsio);
7866 		return (CTL_RETVAL_COMPLETE);
7867 		break; /* NOTREACHED */
7868 	}
7869 
7870 	param_len = scsi_4btoul(cdb->length);
7871 
7872 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
7873 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
7874 		if (ctsio->kern_data_ptr == NULL) {
7875 			ctl_set_busy(ctsio);
7876 			ctl_done((union ctl_io *)ctsio);
7877 			return (CTL_RETVAL_COMPLETE);
7878 		}
7879 		ctsio->kern_data_len = param_len;
7880 		ctsio->kern_total_len = param_len;
7881 		ctsio->kern_data_resid = 0;
7882 		ctsio->kern_rel_offset = 0;
7883 		ctsio->kern_sg_entries = 0;
7884 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7885 		ctsio->be_move_done = ctl_config_move_done;
7886 		ctl_datamove((union ctl_io *)ctsio);
7887 
7888 		return (CTL_RETVAL_COMPLETE);
7889 	}
7890 
7891 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
7892 
7893 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7894 	res_key = scsi_8btou64(param->res_key.key);
7895 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
7896 
7897 	/*
7898 	 * Validate the reservation key here except for SPRO_REG_IGNO
7899 	 * This must be done for all other service actions
7900 	 */
7901 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
7902 		mtx_lock(&softc->ctl_lock);
7903 		if (lun->per_res[residx].registered) {
7904 		    if (memcmp(param->res_key.key,
7905 			       lun->per_res[residx].res_key.key,
7906 			       ctl_min(sizeof(param->res_key),
7907 			       sizeof(lun->per_res[residx].res_key))) != 0) {
7908 				/*
7909 				 * The current key passed in doesn't match
7910 				 * the one the initiator previously
7911 				 * registered.
7912 				 */
7913 				mtx_unlock(&softc->ctl_lock);
7914 				free(ctsio->kern_data_ptr, M_CTL);
7915 				ctl_set_reservation_conflict(ctsio);
7916 				ctl_done((union ctl_io *)ctsio);
7917 				return (CTL_RETVAL_COMPLETE);
7918 			}
7919 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
7920 		    /*
7921 			 * We are not registered
7922 			 */
7923 			mtx_unlock(&softc->ctl_lock);
7924 			free(ctsio->kern_data_ptr, M_CTL);
7925 			ctl_set_reservation_conflict(ctsio);
7926 			ctl_done((union ctl_io *)ctsio);
7927 			return (CTL_RETVAL_COMPLETE);
7928 		} else if (res_key != 0) {
7929 			/*
7930 			 * We are not registered and trying to register but
7931 			 * the register key isn't zero.
7932 			 */
7933 			mtx_unlock(&softc->ctl_lock);
7934 			free(ctsio->kern_data_ptr, M_CTL);
7935 			ctl_set_reservation_conflict(ctsio);
7936 			ctl_done((union ctl_io *)ctsio);
7937 			return (CTL_RETVAL_COMPLETE);
7938 		}
7939 		mtx_unlock(&softc->ctl_lock);
7940 	}
7941 
7942 	switch (cdb->action & SPRO_ACTION_MASK) {
7943 	case SPRO_REGISTER:
7944 	case SPRO_REG_IGNO: {
7945 
7946 #if 0
7947 		printf("Registration received\n");
7948 #endif
7949 
7950 		/*
7951 		 * We don't support any of these options, as we report in
7952 		 * the read capabilities request (see
7953 		 * ctl_persistent_reserve_in(), above).
7954 		 */
7955 		if ((param->flags & SPR_SPEC_I_PT)
7956 		 || (param->flags & SPR_ALL_TG_PT)
7957 		 || (param->flags & SPR_APTPL)) {
7958 			int bit_ptr;
7959 
7960 			if (param->flags & SPR_APTPL)
7961 				bit_ptr = 0;
7962 			else if (param->flags & SPR_ALL_TG_PT)
7963 				bit_ptr = 2;
7964 			else /* SPR_SPEC_I_PT */
7965 				bit_ptr = 3;
7966 
7967 			free(ctsio->kern_data_ptr, M_CTL);
7968 			ctl_set_invalid_field(ctsio,
7969 					      /*sks_valid*/ 1,
7970 					      /*command*/ 0,
7971 					      /*field*/ 20,
7972 					      /*bit_valid*/ 1,
7973 					      /*bit*/ bit_ptr);
7974 			ctl_done((union ctl_io *)ctsio);
7975 			return (CTL_RETVAL_COMPLETE);
7976 		}
7977 
7978 		mtx_lock(&softc->ctl_lock);
7979 
7980 		/*
7981 		 * The initiator wants to clear the
7982 		 * key/unregister.
7983 		 */
7984 		if (sa_res_key == 0) {
7985 			if ((res_key == 0
7986 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
7987 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
7988 			  && !lun->per_res[residx].registered)) {
7989 				mtx_unlock(&softc->ctl_lock);
7990 				goto done;
7991 			}
7992 
7993 			lun->per_res[residx].registered = 0;
7994 			memset(&lun->per_res[residx].res_key,
7995 			       0, sizeof(lun->per_res[residx].res_key));
7996 			lun->pr_key_count--;
7997 
7998 			if (residx == lun->pr_res_idx) {
7999 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8000 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8001 
8002 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8003 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8004 				 && lun->pr_key_count) {
8005 					/*
8006 					 * If the reservation is a registrants
8007 					 * only type we need to generate a UA
8008 					 * for other registered inits.  The
8009 					 * sense code should be RESERVATIONS
8010 					 * RELEASED
8011 					 */
8012 
8013 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8014 						if (lun->per_res[
8015 						    i+persis_offset].registered
8016 						    == 0)
8017 							continue;
8018 						lun->pending_sense[i
8019 							].ua_pending |=
8020 							CTL_UA_RES_RELEASE;
8021 					}
8022 				}
8023 				lun->res_type = 0;
8024 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8025 				if (lun->pr_key_count==0) {
8026 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8027 					lun->res_type = 0;
8028 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8029 				}
8030 			}
8031 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8032 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8033 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8034 			persis_io.pr.pr_info.residx = residx;
8035 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8036 			     &persis_io, sizeof(persis_io), 0 )) >
8037 			     CTL_HA_STATUS_SUCCESS) {
8038 				printf("CTL:Persis Out error returned from "
8039 				       "ctl_ha_msg_send %d\n", isc_retval);
8040 			}
8041 			mtx_unlock(&softc->ctl_lock);
8042 		} else /* sa_res_key != 0 */ {
8043 
8044 			/*
8045 			 * If we aren't registered currently then increment
8046 			 * the key count and set the registered flag.
8047 			 */
8048 			if (!lun->per_res[residx].registered) {
8049 				lun->pr_key_count++;
8050 				lun->per_res[residx].registered = 1;
8051 			}
8052 
8053 			memcpy(&lun->per_res[residx].res_key,
8054 			       param->serv_act_res_key,
8055 			       ctl_min(sizeof(param->serv_act_res_key),
8056 			       sizeof(lun->per_res[residx].res_key)));
8057 
8058 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8059 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8060 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8061 			persis_io.pr.pr_info.residx = residx;
8062 			memcpy(persis_io.pr.pr_info.sa_res_key,
8063 			       param->serv_act_res_key,
8064 			       sizeof(param->serv_act_res_key));
8065 			mtx_unlock(&softc->ctl_lock);
8066 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8067 			     &persis_io, sizeof(persis_io), 0)) >
8068 			     CTL_HA_STATUS_SUCCESS) {
8069 				printf("CTL:Persis Out error returned from "
8070 				       "ctl_ha_msg_send %d\n", isc_retval);
8071 			}
8072 		}
8073 		lun->PRGeneration++;
8074 
8075 		break;
8076 	}
8077 	case SPRO_RESERVE:
8078 #if 0
8079                 printf("Reserve executed type %d\n", type);
8080 #endif
8081 		mtx_lock(&softc->ctl_lock);
8082 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8083 			/*
8084 			 * if this isn't the reservation holder and it's
8085 			 * not a "all registrants" type or if the type is
8086 			 * different then we have a conflict
8087 			 */
8088 			if ((lun->pr_res_idx != residx
8089 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8090 			 || lun->res_type != type) {
8091 				mtx_unlock(&softc->ctl_lock);
8092 				free(ctsio->kern_data_ptr, M_CTL);
8093 				ctl_set_reservation_conflict(ctsio);
8094 				ctl_done((union ctl_io *)ctsio);
8095 				return (CTL_RETVAL_COMPLETE);
8096 			}
8097 		} else /* create a reservation */ {
8098 			/*
8099 			 * If it's not an "all registrants" type record
8100 			 * reservation holder
8101 			 */
8102 			if (type != SPR_TYPE_WR_EX_AR
8103 			 && type != SPR_TYPE_EX_AC_AR)
8104 				lun->pr_res_idx = residx; /* Res holder */
8105 			else
8106 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8107 
8108 			lun->flags |= CTL_LUN_PR_RESERVED;
8109 			lun->res_type = type;
8110 
8111 			mtx_unlock(&softc->ctl_lock);
8112 
8113 			/* send msg to other side */
8114 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8115 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8116 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8117 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8118 			persis_io.pr.pr_info.res_type = type;
8119 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8120 			     &persis_io, sizeof(persis_io), 0)) >
8121 			     CTL_HA_STATUS_SUCCESS) {
8122 				printf("CTL:Persis Out error returned from "
8123 				       "ctl_ha_msg_send %d\n", isc_retval);
8124 			}
8125 		}
8126 		break;
8127 
8128 	case SPRO_RELEASE:
8129 		mtx_lock(&softc->ctl_lock);
8130 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8131 			/* No reservation exists return good status */
8132 			mtx_unlock(&softc->ctl_lock);
8133 			goto done;
8134 		}
8135 		/*
8136 		 * Is this nexus a reservation holder?
8137 		 */
8138 		if (lun->pr_res_idx != residx
8139 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8140 			/*
8141 			 * not a res holder return good status but
8142 			 * do nothing
8143 			 */
8144 			mtx_unlock(&softc->ctl_lock);
8145 			goto done;
8146 		}
8147 
8148 		if (lun->res_type != type) {
8149 			mtx_unlock(&softc->ctl_lock);
8150 			free(ctsio->kern_data_ptr, M_CTL);
8151 			ctl_set_illegal_pr_release(ctsio);
8152 			ctl_done((union ctl_io *)ctsio);
8153 			return (CTL_RETVAL_COMPLETE);
8154 		}
8155 
8156 		/* okay to release */
8157 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8158 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8159 		lun->res_type = 0;
8160 
8161 		/*
8162 		 * if this isn't an exclusive access
8163 		 * res generate UA for all other
8164 		 * registrants.
8165 		 */
8166 		if (type != SPR_TYPE_EX_AC
8167 		 && type != SPR_TYPE_WR_EX) {
8168 			/*
8169 			 * temporarily unregister so we don't generate UA
8170 			 */
8171 			lun->per_res[residx].registered = 0;
8172 
8173 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8174 				if (lun->per_res[i+persis_offset].registered
8175 				    == 0)
8176 					continue;
8177 				lun->pending_sense[i].ua_pending |=
8178 					CTL_UA_RES_RELEASE;
8179 			}
8180 
8181 			lun->per_res[residx].registered = 1;
8182 		}
8183 		mtx_unlock(&softc->ctl_lock);
8184 		/* Send msg to other side */
8185 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8186 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8187 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8188 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8189 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8190 			printf("CTL:Persis Out error returned from "
8191 			       "ctl_ha_msg_send %d\n", isc_retval);
8192 		}
8193 		break;
8194 
8195 	case SPRO_CLEAR:
8196 		/* send msg to other side */
8197 
8198 		mtx_lock(&softc->ctl_lock);
8199 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8200 		lun->res_type = 0;
8201 		lun->pr_key_count = 0;
8202 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8203 
8204 
8205 		memset(&lun->per_res[residx].res_key,
8206 		       0, sizeof(lun->per_res[residx].res_key));
8207 		lun->per_res[residx].registered = 0;
8208 
8209 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8210 			if (lun->per_res[i].registered) {
8211 				if (!persis_offset && i < CTL_MAX_INITIATORS)
8212 					lun->pending_sense[i].ua_pending |=
8213 						CTL_UA_RES_PREEMPT;
8214 				else if (persis_offset && i >= persis_offset)
8215 					lun->pending_sense[i-persis_offset
8216 					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8217 
8218 				memset(&lun->per_res[i].res_key,
8219 				       0, sizeof(struct scsi_per_res_key));
8220 				lun->per_res[i].registered = 0;
8221 			}
8222 		lun->PRGeneration++;
8223 		mtx_unlock(&softc->ctl_lock);
8224 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8225 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8226 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8227 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8228 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8229 			printf("CTL:Persis Out error returned from "
8230 			       "ctl_ha_msg_send %d\n", isc_retval);
8231 		}
8232 		break;
8233 
8234 	case SPRO_PREEMPT: {
8235 		int nretval;
8236 
8237 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8238 					  residx, ctsio, cdb, param);
8239 		if (nretval != 0)
8240 			return (CTL_RETVAL_COMPLETE);
8241 		break;
8242 	}
8243 	case SPRO_REG_MOVE:
8244 	case SPRO_PRE_ABO:
8245 	default:
8246 		free(ctsio->kern_data_ptr, M_CTL);
8247 		ctl_set_invalid_field(/*ctsio*/ ctsio,
8248 				      /*sks_valid*/ 1,
8249 				      /*command*/ 1,
8250 				      /*field*/ 1,
8251 				      /*bit_valid*/ 1,
8252 				      /*bit*/ 0);
8253 		ctl_done((union ctl_io *)ctsio);
8254 		return (CTL_RETVAL_COMPLETE);
8255 		break; /* NOTREACHED */
8256 	}
8257 
8258 done:
8259 	free(ctsio->kern_data_ptr, M_CTL);
8260 	ctl_set_success(ctsio);
8261 	ctl_done((union ctl_io *)ctsio);
8262 
8263 	return (retval);
8264 }
8265 
8266 /*
8267  * This routine is for handling a message from the other SC pertaining to
8268  * persistent reserve out. All the error checking will have been done
8269  * so only perorming the action need be done here to keep the two
8270  * in sync.
8271  */
8272 static void
8273 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8274 {
8275 	struct ctl_lun *lun;
8276 	struct ctl_softc *softc;
8277 	int i;
8278 
8279 	softc = control_softc;
8280 
8281 	mtx_lock(&softc->ctl_lock);
8282 
8283 	lun = softc->ctl_luns[msg->hdr.nexus.targ_lun];
8284 	switch(msg->pr.pr_info.action) {
8285 	case CTL_PR_REG_KEY:
8286 		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8287 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8288 			lun->pr_key_count++;
8289 		}
8290 		lun->PRGeneration++;
8291 		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8292 		       msg->pr.pr_info.sa_res_key,
8293 		       sizeof(struct scsi_per_res_key));
8294 		break;
8295 
8296 	case CTL_PR_UNREG_KEY:
8297 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8298 		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8299 		       0, sizeof(struct scsi_per_res_key));
8300 		lun->pr_key_count--;
8301 
8302 		/* XXX Need to see if the reservation has been released */
8303 		/* if so do we need to generate UA? */
8304 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8305 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8306 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8307 
8308 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8309 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8310 			 && lun->pr_key_count) {
8311 				/*
8312 				 * If the reservation is a registrants
8313 				 * only type we need to generate a UA
8314 				 * for other registered inits.  The
8315 				 * sense code should be RESERVATIONS
8316 				 * RELEASED
8317 				 */
8318 
8319 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8320 					if (lun->per_res[i+
8321 					    persis_offset].registered == 0)
8322 						continue;
8323 
8324 					lun->pending_sense[i
8325 						].ua_pending |=
8326 						CTL_UA_RES_RELEASE;
8327 				}
8328 			}
8329 			lun->res_type = 0;
8330 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8331 			if (lun->pr_key_count==0) {
8332 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8333 				lun->res_type = 0;
8334 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8335 			}
8336 		}
8337 		lun->PRGeneration++;
8338 		break;
8339 
8340 	case CTL_PR_RESERVE:
8341 		lun->flags |= CTL_LUN_PR_RESERVED;
8342 		lun->res_type = msg->pr.pr_info.res_type;
8343 		lun->pr_res_idx = msg->pr.pr_info.residx;
8344 
8345 		break;
8346 
8347 	case CTL_PR_RELEASE:
8348 		/*
8349 		 * if this isn't an exclusive access res generate UA for all
8350 		 * other registrants.
8351 		 */
8352 		if (lun->res_type != SPR_TYPE_EX_AC
8353 		 && lun->res_type != SPR_TYPE_WR_EX) {
8354 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8355 				if (lun->per_res[i+persis_offset].registered)
8356 					lun->pending_sense[i].ua_pending |=
8357 						CTL_UA_RES_RELEASE;
8358 		}
8359 
8360 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8361 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8362 		lun->res_type = 0;
8363 		break;
8364 
8365 	case CTL_PR_PREEMPT:
8366 		ctl_pro_preempt_other(lun, msg);
8367 		break;
8368 	case CTL_PR_CLEAR:
8369 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8370 		lun->res_type = 0;
8371 		lun->pr_key_count = 0;
8372 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8373 
8374 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8375 			if (lun->per_res[i].registered == 0)
8376 				continue;
8377 			if (!persis_offset
8378 			 && i < CTL_MAX_INITIATORS)
8379 				lun->pending_sense[i].ua_pending |=
8380 					CTL_UA_RES_PREEMPT;
8381 			else if (persis_offset
8382 			      && i >= persis_offset)
8383    				lun->pending_sense[i-persis_offset].ua_pending|=
8384 					CTL_UA_RES_PREEMPT;
8385 			memset(&lun->per_res[i].res_key, 0,
8386 			       sizeof(struct scsi_per_res_key));
8387 			lun->per_res[i].registered = 0;
8388 		}
8389 		lun->PRGeneration++;
8390 		break;
8391 	}
8392 
8393 	mtx_unlock(&softc->ctl_lock);
8394 }
8395 
8396 int
8397 ctl_read_write(struct ctl_scsiio *ctsio)
8398 {
8399 	struct ctl_lun *lun;
8400 	struct ctl_lba_len lbalen;
8401 	uint64_t lba;
8402 	uint32_t num_blocks;
8403 	int reladdr, fua, dpo, ebp;
8404 	int retval;
8405 	int isread;
8406 
8407 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8408 
8409 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8410 
8411 	reladdr = 0;
8412 	fua = 0;
8413 	dpo = 0;
8414 	ebp = 0;
8415 
8416 	retval = CTL_RETVAL_COMPLETE;
8417 
8418 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8419 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8420 	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8421 		uint32_t residx;
8422 
8423 		/*
8424 		 * XXX KDM need a lock here.
8425 		 */
8426 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8427 		if ((lun->res_type == SPR_TYPE_EX_AC
8428 		  && residx != lun->pr_res_idx)
8429 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8430 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8431 		  && !lun->per_res[residx].registered)) {
8432 			ctl_set_reservation_conflict(ctsio);
8433 			ctl_done((union ctl_io *)ctsio);
8434 			return (CTL_RETVAL_COMPLETE);
8435 	        }
8436 	}
8437 
8438 	switch (ctsio->cdb[0]) {
8439 	case READ_6:
8440 	case WRITE_6: {
8441 		struct scsi_rw_6 *cdb;
8442 
8443 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8444 
8445 		lba = scsi_3btoul(cdb->addr);
8446 		/* only 5 bits are valid in the most significant address byte */
8447 		lba &= 0x1fffff;
8448 		num_blocks = cdb->length;
8449 		/*
8450 		 * This is correct according to SBC-2.
8451 		 */
8452 		if (num_blocks == 0)
8453 			num_blocks = 256;
8454 		break;
8455 	}
8456 	case READ_10:
8457 	case WRITE_10: {
8458 		struct scsi_rw_10 *cdb;
8459 
8460 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8461 
8462 		if (cdb->byte2 & SRW10_RELADDR)
8463 			reladdr = 1;
8464 		if (cdb->byte2 & SRW10_FUA)
8465 			fua = 1;
8466 		if (cdb->byte2 & SRW10_DPO)
8467 			dpo = 1;
8468 
8469 		if ((cdb->opcode == WRITE_10)
8470 		 && (cdb->byte2 & SRW10_EBP))
8471 			ebp = 1;
8472 
8473 		lba = scsi_4btoul(cdb->addr);
8474 		num_blocks = scsi_2btoul(cdb->length);
8475 		break;
8476 	}
8477 	case WRITE_VERIFY_10: {
8478 		struct scsi_write_verify_10 *cdb;
8479 
8480 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8481 
8482 		/*
8483 		 * XXX KDM we should do actual write verify support at some
8484 		 * point.  This is obviously fake, we're just translating
8485 		 * things to a write.  So we don't even bother checking the
8486 		 * BYTCHK field, since we don't do any verification.  If
8487 		 * the user asks for it, we'll just pretend we did it.
8488 		 */
8489 		if (cdb->byte2 & SWV_DPO)
8490 			dpo = 1;
8491 
8492 		lba = scsi_4btoul(cdb->addr);
8493 		num_blocks = scsi_2btoul(cdb->length);
8494 		break;
8495 	}
8496 	case READ_12:
8497 	case WRITE_12: {
8498 		struct scsi_rw_12 *cdb;
8499 
8500 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8501 
8502 		if (cdb->byte2 & SRW12_RELADDR)
8503 			reladdr = 1;
8504 		if (cdb->byte2 & SRW12_FUA)
8505 			fua = 1;
8506 		if (cdb->byte2 & SRW12_DPO)
8507 			dpo = 1;
8508 		lba = scsi_4btoul(cdb->addr);
8509 		num_blocks = scsi_4btoul(cdb->length);
8510 		break;
8511 	}
8512 	case WRITE_VERIFY_12: {
8513 		struct scsi_write_verify_12 *cdb;
8514 
8515 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8516 
8517 		if (cdb->byte2 & SWV_DPO)
8518 			dpo = 1;
8519 
8520 		lba = scsi_4btoul(cdb->addr);
8521 		num_blocks = scsi_4btoul(cdb->length);
8522 
8523 		break;
8524 	}
8525 	case READ_16:
8526 	case WRITE_16: {
8527 		struct scsi_rw_16 *cdb;
8528 
8529 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8530 
8531 		if (cdb->byte2 & SRW12_RELADDR)
8532 			reladdr = 1;
8533 		if (cdb->byte2 & SRW12_FUA)
8534 			fua = 1;
8535 		if (cdb->byte2 & SRW12_DPO)
8536 			dpo = 1;
8537 
8538 		lba = scsi_8btou64(cdb->addr);
8539 		num_blocks = scsi_4btoul(cdb->length);
8540 		break;
8541 	}
8542 	case WRITE_VERIFY_16: {
8543 		struct scsi_write_verify_16 *cdb;
8544 
8545 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8546 
8547 		if (cdb->byte2 & SWV_DPO)
8548 			dpo = 1;
8549 
8550 		lba = scsi_8btou64(cdb->addr);
8551 		num_blocks = scsi_4btoul(cdb->length);
8552 		break;
8553 	}
8554 	default:
8555 		/*
8556 		 * We got a command we don't support.  This shouldn't
8557 		 * happen, commands should be filtered out above us.
8558 		 */
8559 		ctl_set_invalid_opcode(ctsio);
8560 		ctl_done((union ctl_io *)ctsio);
8561 
8562 		return (CTL_RETVAL_COMPLETE);
8563 		break; /* NOTREACHED */
8564 	}
8565 
8566 	/*
8567 	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8568 	 * interesting for us, but if RAIDCore is in write-back mode,
8569 	 * getting it to do write-through for a particular transaction may
8570 	 * not be possible.
8571 	 */
8572 	/*
8573 	 * We don't support relative addressing.  That also requires
8574 	 * supporting linked commands, which we don't do.
8575 	 */
8576 	if (reladdr != 0) {
8577 		ctl_set_invalid_field(ctsio,
8578 				      /*sks_valid*/ 1,
8579 				      /*command*/ 1,
8580 				      /*field*/ 1,
8581 				      /*bit_valid*/ 1,
8582 				      /*bit*/ 0);
8583 		ctl_done((union ctl_io *)ctsio);
8584 		return (CTL_RETVAL_COMPLETE);
8585 	}
8586 
8587 	/*
8588 	 * The first check is to make sure we're in bounds, the second
8589 	 * check is to catch wrap-around problems.  If the lba + num blocks
8590 	 * is less than the lba, then we've wrapped around and the block
8591 	 * range is invalid anyway.
8592 	 */
8593 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8594 	 || ((lba + num_blocks) < lba)) {
8595 		ctl_set_lba_out_of_range(ctsio);
8596 		ctl_done((union ctl_io *)ctsio);
8597 		return (CTL_RETVAL_COMPLETE);
8598 	}
8599 
8600 	/*
8601 	 * According to SBC-3, a transfer length of 0 is not an error.
8602 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8603 	 * translates to 256 blocks for those commands.
8604 	 */
8605 	if (num_blocks == 0) {
8606 		ctl_set_success(ctsio);
8607 		ctl_done((union ctl_io *)ctsio);
8608 		return (CTL_RETVAL_COMPLETE);
8609 	}
8610 
8611 	lbalen.lba = lba;
8612 	lbalen.len = num_blocks;
8613 	memcpy(ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes, &lbalen,
8614 	       sizeof(lbalen));
8615 
8616 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8617 
8618 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8619 
8620 	return (retval);
8621 }
8622 
8623 int
8624 ctl_report_luns(struct ctl_scsiio *ctsio)
8625 {
8626 	struct scsi_report_luns *cdb;
8627 	struct scsi_report_luns_data *lun_data;
8628 	struct ctl_lun *lun, *request_lun;
8629 	int num_luns, retval;
8630 	uint32_t alloc_len, lun_datalen;
8631 	int num_filled, well_known;
8632 	uint32_t initidx;
8633 
8634 	retval = CTL_RETVAL_COMPLETE;
8635 	well_known = 0;
8636 
8637 	cdb = (struct scsi_report_luns *)ctsio->cdb;
8638 
8639 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8640 
8641 	mtx_lock(&control_softc->ctl_lock);
8642 	num_luns = control_softc->num_luns;
8643 	mtx_unlock(&control_softc->ctl_lock);
8644 
8645 	switch (cdb->select_report) {
8646 	case RPL_REPORT_DEFAULT:
8647 	case RPL_REPORT_ALL:
8648 		break;
8649 	case RPL_REPORT_WELLKNOWN:
8650 		well_known = 1;
8651 		num_luns = 0;
8652 		break;
8653 	default:
8654 		ctl_set_invalid_field(ctsio,
8655 				      /*sks_valid*/ 1,
8656 				      /*command*/ 1,
8657 				      /*field*/ 2,
8658 				      /*bit_valid*/ 0,
8659 				      /*bit*/ 0);
8660 		ctl_done((union ctl_io *)ctsio);
8661 		return (retval);
8662 		break; /* NOTREACHED */
8663 	}
8664 
8665 	alloc_len = scsi_4btoul(cdb->length);
8666 	/*
8667 	 * The initiator has to allocate at least 16 bytes for this request,
8668 	 * so he can at least get the header and the first LUN.  Otherwise
8669 	 * we reject the request (per SPC-3 rev 14, section 6.21).
8670 	 */
8671 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
8672 	    sizeof(struct scsi_report_luns_lundata))) {
8673 		ctl_set_invalid_field(ctsio,
8674 				      /*sks_valid*/ 1,
8675 				      /*command*/ 1,
8676 				      /*field*/ 6,
8677 				      /*bit_valid*/ 0,
8678 				      /*bit*/ 0);
8679 		ctl_done((union ctl_io *)ctsio);
8680 		return (retval);
8681 	}
8682 
8683 	request_lun = (struct ctl_lun *)
8684 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8685 
8686 	lun_datalen = sizeof(*lun_data) +
8687 		(num_luns * sizeof(struct scsi_report_luns_lundata));
8688 
8689 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK);
8690 	if (ctsio->kern_data_ptr == NULL) {
8691 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
8692 		ctsio->scsi_status = SCSI_STATUS_BUSY;
8693 		ctl_done((union ctl_io *)ctsio);
8694 		return (CTL_RETVAL_COMPLETE);
8695 	}
8696 
8697 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
8698 	ctsio->kern_sg_entries = 0;
8699 
8700 	if (lun_datalen < alloc_len) {
8701 		ctsio->residual = alloc_len - lun_datalen;
8702 		ctsio->kern_data_len = lun_datalen;
8703 		ctsio->kern_total_len = lun_datalen;
8704 	} else {
8705 		ctsio->residual = 0;
8706 		ctsio->kern_data_len = alloc_len;
8707 		ctsio->kern_total_len = alloc_len;
8708 	}
8709 	ctsio->kern_data_resid = 0;
8710 	ctsio->kern_rel_offset = 0;
8711 	ctsio->kern_sg_entries = 0;
8712 
8713 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8714 
8715 	memset(lun_data, 0, lun_datalen);
8716 
8717 	/*
8718 	 * We set this to the actual data length, regardless of how much
8719 	 * space we actually have to return results.  If the user looks at
8720 	 * this value, he'll know whether or not he allocated enough space
8721 	 * and reissue the command if necessary.  We don't support well
8722 	 * known logical units, so if the user asks for that, return none.
8723 	 */
8724 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
8725 
8726 	mtx_lock(&control_softc->ctl_lock);
8727 	for (num_filled = 0, lun = STAILQ_FIRST(&control_softc->lun_list);
8728 	     (lun != NULL) && (num_filled < num_luns);
8729 	     lun = STAILQ_NEXT(lun, links)) {
8730 
8731 		if (lun->lun <= 0xff) {
8732 			/*
8733 			 * Peripheral addressing method, bus number 0.
8734 			 */
8735 			lun_data->luns[num_filled].lundata[0] =
8736 				RPL_LUNDATA_ATYP_PERIPH;
8737 			lun_data->luns[num_filled].lundata[1] = lun->lun;
8738 			num_filled++;
8739 		} else if (lun->lun <= 0x3fff) {
8740 			/*
8741 			 * Flat addressing method.
8742 			 */
8743 			lun_data->luns[num_filled].lundata[0] =
8744 				RPL_LUNDATA_ATYP_FLAT |
8745 				(lun->lun & RPL_LUNDATA_FLAT_LUN_MASK);
8746 #ifdef OLDCTLHEADERS
8747 				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
8748 				(lun->lun & SRLD_BUS_LUN_MASK);
8749 #endif
8750 			lun_data->luns[num_filled].lundata[1] =
8751 #ifdef OLDCTLHEADERS
8752 				lun->lun >> SRLD_BUS_LUN_BITS;
8753 #endif
8754 				lun->lun >> RPL_LUNDATA_FLAT_LUN_BITS;
8755 			num_filled++;
8756 		} else {
8757 			printf("ctl_report_luns: bogus LUN number %jd, "
8758 			       "skipping\n", (intmax_t)lun->lun);
8759 		}
8760 		/*
8761 		 * According to SPC-3, rev 14 section 6.21:
8762 		 *
8763 		 * "The execution of a REPORT LUNS command to any valid and
8764 		 * installed logical unit shall clear the REPORTED LUNS DATA
8765 		 * HAS CHANGED unit attention condition for all logical
8766 		 * units of that target with respect to the requesting
8767 		 * initiator. A valid and installed logical unit is one
8768 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
8769 		 * INQUIRY data (see 6.4.2)."
8770 		 *
8771 		 * If request_lun is NULL, the LUN this report luns command
8772 		 * was issued to is either disabled or doesn't exist. In that
8773 		 * case, we shouldn't clear any pending lun change unit
8774 		 * attention.
8775 		 */
8776 		if (request_lun != NULL)
8777 			lun->pending_sense[initidx].ua_pending &=
8778 				~CTL_UA_LUN_CHANGE;
8779 	}
8780 	mtx_unlock(&control_softc->ctl_lock);
8781 
8782 	/*
8783 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
8784 	 * this request.
8785 	 */
8786 	ctsio->scsi_status = SCSI_STATUS_OK;
8787 
8788 	ctsio->be_move_done = ctl_config_move_done;
8789 	ctl_datamove((union ctl_io *)ctsio);
8790 
8791 	return (retval);
8792 }
8793 
8794 int
8795 ctl_request_sense(struct ctl_scsiio *ctsio)
8796 {
8797 	struct scsi_request_sense *cdb;
8798 	struct scsi_sense_data *sense_ptr;
8799 	struct ctl_lun *lun;
8800 	uint32_t initidx;
8801 	int have_error;
8802 	scsi_sense_data_type sense_format;
8803 
8804 	cdb = (struct scsi_request_sense *)ctsio->cdb;
8805 
8806 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8807 
8808 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
8809 
8810 	/*
8811 	 * Determine which sense format the user wants.
8812 	 */
8813 	if (cdb->byte2 & SRS_DESC)
8814 		sense_format = SSD_TYPE_DESC;
8815 	else
8816 		sense_format = SSD_TYPE_FIXED;
8817 
8818 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
8819 	if (ctsio->kern_data_ptr == NULL) {
8820 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
8821 		ctsio->scsi_status = SCSI_STATUS_BUSY;
8822 		ctl_done((union ctl_io *)ctsio);
8823 		return (CTL_RETVAL_COMPLETE);
8824 	}
8825 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
8826 	ctsio->kern_sg_entries = 0;
8827 
8828 	/*
8829 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
8830 	 * larger than the largest allowed value for the length field in the
8831 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
8832 	 */
8833 	ctsio->residual = 0;
8834 	ctsio->kern_data_len = cdb->length;
8835 	ctsio->kern_total_len = cdb->length;
8836 
8837 	ctsio->kern_data_resid = 0;
8838 	ctsio->kern_rel_offset = 0;
8839 	ctsio->kern_sg_entries = 0;
8840 
8841 	/*
8842 	 * If we don't have a LUN, we don't have any pending sense.
8843 	 */
8844 	if (lun == NULL)
8845 		goto no_sense;
8846 
8847 	have_error = 0;
8848 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8849 	/*
8850 	 * Check for pending sense, and then for pending unit attentions.
8851 	 * Pending sense gets returned first, then pending unit attentions.
8852 	 */
8853 	mtx_lock(&lun->ctl_softc->ctl_lock);
8854 	if (ctl_is_set(lun->have_ca, initidx)) {
8855 		scsi_sense_data_type stored_format;
8856 
8857 		/*
8858 		 * Check to see which sense format was used for the stored
8859 		 * sense data.
8860 		 */
8861 		stored_format = scsi_sense_type(
8862 		    &lun->pending_sense[initidx].sense);
8863 
8864 		/*
8865 		 * If the user requested a different sense format than the
8866 		 * one we stored, then we need to convert it to the other
8867 		 * format.  If we're going from descriptor to fixed format
8868 		 * sense data, we may lose things in translation, depending
8869 		 * on what options were used.
8870 		 *
8871 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
8872 		 * for some reason we'll just copy it out as-is.
8873 		 */
8874 		if ((stored_format == SSD_TYPE_FIXED)
8875 		 && (sense_format == SSD_TYPE_DESC))
8876 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
8877 			    &lun->pending_sense[initidx].sense,
8878 			    (struct scsi_sense_data_desc *)sense_ptr);
8879 		else if ((stored_format == SSD_TYPE_DESC)
8880 		      && (sense_format == SSD_TYPE_FIXED))
8881 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
8882 			    &lun->pending_sense[initidx].sense,
8883 			    (struct scsi_sense_data_fixed *)sense_ptr);
8884 		else
8885 			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
8886 			       ctl_min(sizeof(*sense_ptr),
8887 			       sizeof(lun->pending_sense[initidx].sense)));
8888 
8889 		ctl_clear_mask(lun->have_ca, initidx);
8890 		have_error = 1;
8891 	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
8892 		ctl_ua_type ua_type;
8893 
8894 		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
8895 				       sense_ptr, sense_format);
8896 		if (ua_type != CTL_UA_NONE) {
8897 			have_error = 1;
8898 			/* We're reporting this UA, so clear it */
8899 			lun->pending_sense[initidx].ua_pending &= ~ua_type;
8900 		}
8901 	}
8902 	mtx_unlock(&lun->ctl_softc->ctl_lock);
8903 
8904 	/*
8905 	 * We already have a pending error, return it.
8906 	 */
8907 	if (have_error != 0) {
8908 		/*
8909 		 * We report the SCSI status as OK, since the status of the
8910 		 * request sense command itself is OK.
8911 		 */
8912 		ctsio->scsi_status = SCSI_STATUS_OK;
8913 
8914 		/*
8915 		 * We report 0 for the sense length, because we aren't doing
8916 		 * autosense in this case.  We're reporting sense as
8917 		 * parameter data.
8918 		 */
8919 		ctsio->sense_len = 0;
8920 
8921 		ctsio->be_move_done = ctl_config_move_done;
8922 		ctl_datamove((union ctl_io *)ctsio);
8923 
8924 		return (CTL_RETVAL_COMPLETE);
8925 	}
8926 
8927 no_sense:
8928 
8929 	/*
8930 	 * No sense information to report, so we report that everything is
8931 	 * okay.
8932 	 */
8933 	ctl_set_sense_data(sense_ptr,
8934 			   lun,
8935 			   sense_format,
8936 			   /*current_error*/ 1,
8937 			   /*sense_key*/ SSD_KEY_NO_SENSE,
8938 			   /*asc*/ 0x00,
8939 			   /*ascq*/ 0x00,
8940 			   SSD_ELEM_NONE);
8941 
8942 	ctsio->scsi_status = SCSI_STATUS_OK;
8943 
8944 	/*
8945 	 * We report 0 for the sense length, because we aren't doing
8946 	 * autosense in this case.  We're reporting sense as parameter data.
8947 	 */
8948 	ctsio->sense_len = 0;
8949 	ctsio->be_move_done = ctl_config_move_done;
8950 	ctl_datamove((union ctl_io *)ctsio);
8951 
8952 	return (CTL_RETVAL_COMPLETE);
8953 }
8954 
8955 int
8956 ctl_tur(struct ctl_scsiio *ctsio)
8957 {
8958 	struct ctl_lun *lun;
8959 
8960 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8961 
8962 	CTL_DEBUG_PRINT(("ctl_tur\n"));
8963 
8964 	if (lun == NULL)
8965 		return (-EINVAL);
8966 
8967 	ctsio->scsi_status = SCSI_STATUS_OK;
8968 	ctsio->io_hdr.status = CTL_SUCCESS;
8969 
8970 	ctl_done((union ctl_io *)ctsio);
8971 
8972 	return (CTL_RETVAL_COMPLETE);
8973 }
8974 
8975 #ifdef notyet
8976 static int
8977 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
8978 {
8979 
8980 }
8981 #endif
8982 
8983 static int
8984 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
8985 {
8986 	struct scsi_vpd_supported_pages *pages;
8987 	int sup_page_size;
8988 	struct ctl_lun *lun;
8989 
8990 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8991 
8992 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) +
8993 		SCSI_EVPD_NUM_SUPPORTED_PAGES;
8994 	/*
8995 	 * XXX KDM GFP_???  We probably don't want to wait here,
8996 	 * unless we end up having a process/thread context.
8997 	 */
8998 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK);
8999 	if (ctsio->kern_data_ptr == NULL) {
9000 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
9001 		ctsio->scsi_status = SCSI_STATUS_BUSY;
9002 		ctl_done((union ctl_io *)ctsio);
9003 		return (CTL_RETVAL_COMPLETE);
9004 	}
9005 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9006 	ctsio->kern_sg_entries = 0;
9007 
9008 	if (sup_page_size < alloc_len) {
9009 		ctsio->residual = alloc_len - sup_page_size;
9010 		ctsio->kern_data_len = sup_page_size;
9011 		ctsio->kern_total_len = sup_page_size;
9012 	} else {
9013 		ctsio->residual = 0;
9014 		ctsio->kern_data_len = alloc_len;
9015 		ctsio->kern_total_len = alloc_len;
9016 	}
9017 	ctsio->kern_data_resid = 0;
9018 	ctsio->kern_rel_offset = 0;
9019 	ctsio->kern_sg_entries = 0;
9020 
9021 	memset(pages, 0, sup_page_size);
9022 
9023 	/*
9024 	 * The control device is always connected.  The disk device, on the
9025 	 * other hand, may not be online all the time.  Need to change this
9026 	 * to figure out whether the disk device is actually online or not.
9027 	 */
9028 	if (lun != NULL)
9029 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9030 				lun->be_lun->lun_type;
9031 	else
9032 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9033 
9034 	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9035 	/* Supported VPD pages */
9036 	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9037 	/* Serial Number */
9038 	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9039 	/* Device Identification */
9040 	pages->page_list[2] = SVPD_DEVICE_ID;
9041 
9042 	ctsio->scsi_status = SCSI_STATUS_OK;
9043 
9044 	ctsio->be_move_done = ctl_config_move_done;
9045 	ctl_datamove((union ctl_io *)ctsio);
9046 
9047 	return (CTL_RETVAL_COMPLETE);
9048 }
9049 
9050 static int
9051 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9052 {
9053 	struct scsi_vpd_unit_serial_number *sn_ptr;
9054 	struct ctl_lun *lun;
9055 #ifndef CTL_USE_BACKEND_SN
9056 	char tmpstr[32];
9057 #endif
9058 
9059 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9060 
9061 	/* XXX KDM which malloc flags here?? */
9062 	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK);
9063 	if (ctsio->kern_data_ptr == NULL) {
9064 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
9065 		ctsio->scsi_status = SCSI_STATUS_BUSY;
9066 		ctl_done((union ctl_io *)ctsio);
9067 		return (CTL_RETVAL_COMPLETE);
9068 	}
9069 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9070 	ctsio->kern_sg_entries = 0;
9071 
9072 	if (sizeof(*sn_ptr) < alloc_len) {
9073 		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9074 		ctsio->kern_data_len = sizeof(*sn_ptr);
9075 		ctsio->kern_total_len = sizeof(*sn_ptr);
9076 	} else {
9077 		ctsio->residual = 0;
9078 		ctsio->kern_data_len = alloc_len;
9079 		ctsio->kern_total_len = alloc_len;
9080 	}
9081 	ctsio->kern_data_resid = 0;
9082 	ctsio->kern_rel_offset = 0;
9083 	ctsio->kern_sg_entries = 0;
9084 
9085 	memset(sn_ptr, 0, sizeof(*sn_ptr));
9086 
9087 	/*
9088 	 * The control device is always connected.  The disk device, on the
9089 	 * other hand, may not be online all the time.  Need to change this
9090 	 * to figure out whether the disk device is actually online or not.
9091 	 */
9092 	if (lun != NULL)
9093 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9094 				  lun->be_lun->lun_type;
9095 	else
9096 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9097 
9098 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9099 	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9100 #ifdef CTL_USE_BACKEND_SN
9101 	/*
9102 	 * If we don't have a LUN, we just leave the serial number as
9103 	 * all spaces.
9104 	 */
9105 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9106 	if (lun != NULL) {
9107 		strncpy((char *)sn_ptr->serial_num,
9108 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9109 	}
9110 #else
9111 	/*
9112 	 * Note that we're using a non-unique serial number here,
9113 	 */
9114 	snprintf(tmpstr, sizeof(tmpstr), "MYSERIALNUMIS000");
9115 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9116 	strncpy(sn_ptr->serial_num, tmpstr, ctl_min(CTL_SN_LEN,
9117 		ctl_min(sizeof(tmpstr), sizeof(*sn_ptr) - 4)));
9118 #endif
9119 	ctsio->scsi_status = SCSI_STATUS_OK;
9120 
9121 	ctsio->be_move_done = ctl_config_move_done;
9122 	ctl_datamove((union ctl_io *)ctsio);
9123 
9124 	return (CTL_RETVAL_COMPLETE);
9125 }
9126 
9127 
9128 static int
9129 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9130 {
9131 	struct scsi_vpd_device_id *devid_ptr;
9132 	struct scsi_vpd_id_descriptor *desc, *desc1;
9133 	struct scsi_vpd_id_descriptor *desc2, *desc3; /* for types 4h and 5h */
9134 	struct scsi_vpd_id_t10 *t10id;
9135 	struct ctl_softc *ctl_softc;
9136 	struct ctl_lun *lun;
9137 	struct ctl_frontend *fe;
9138 #ifndef CTL_USE_BACKEND_SN
9139 	char tmpstr[32];
9140 #endif /* CTL_USE_BACKEND_SN */
9141 	int devid_len;
9142 
9143 	ctl_softc = control_softc;
9144 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9145 
9146 	devid_len = sizeof(struct scsi_vpd_device_id) +
9147 		sizeof(struct scsi_vpd_id_descriptor) +
9148 		sizeof(struct scsi_vpd_id_t10) + CTL_DEVID_LEN +
9149 		sizeof(struct scsi_vpd_id_descriptor) + CTL_WWPN_LEN +
9150 		sizeof(struct scsi_vpd_id_descriptor) +
9151 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9152 		sizeof(struct scsi_vpd_id_descriptor) +
9153 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9154 
9155 	/* XXX KDM which malloc flags here ?? */
9156 	ctsio->kern_data_ptr = malloc(devid_len, M_CTL, M_WAITOK);
9157 	if (ctsio->kern_data_ptr == NULL) {
9158 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
9159 		ctsio->scsi_status = SCSI_STATUS_BUSY;
9160 		ctl_done((union ctl_io *)ctsio);
9161 		return (CTL_RETVAL_COMPLETE);
9162 	}
9163 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9164 	ctsio->kern_sg_entries = 0;
9165 
9166 	if (devid_len < alloc_len) {
9167 		ctsio->residual = alloc_len - devid_len;
9168 		ctsio->kern_data_len = devid_len;
9169 		ctsio->kern_total_len = devid_len;
9170 	} else {
9171 		ctsio->residual = 0;
9172 		ctsio->kern_data_len = alloc_len;
9173 		ctsio->kern_total_len = alloc_len;
9174 	}
9175 	ctsio->kern_data_resid = 0;
9176 	ctsio->kern_rel_offset = 0;
9177 	ctsio->kern_sg_entries = 0;
9178 
9179 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9180 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
9181 	desc1 = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9182 		sizeof(struct scsi_vpd_id_t10) + CTL_DEVID_LEN);
9183 	desc2 = (struct scsi_vpd_id_descriptor *)(&desc1->identifier[0] +
9184 	          CTL_WWPN_LEN);
9185 	desc3 = (struct scsi_vpd_id_descriptor *)(&desc2->identifier[0] +
9186 	         sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9187 	memset(devid_ptr, 0, devid_len);
9188 
9189 	/*
9190 	 * The control device is always connected.  The disk device, on the
9191 	 * other hand, may not be online all the time.
9192 	 */
9193 	if (lun != NULL)
9194 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9195 				     lun->be_lun->lun_type;
9196 	else
9197 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9198 
9199 	devid_ptr->page_code = SVPD_DEVICE_ID;
9200 
9201 	scsi_ulto2b(devid_len - 4, devid_ptr->length);
9202 
9203 	mtx_lock(&ctl_softc->ctl_lock);
9204 
9205 	fe = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9206 
9207 	/*
9208 	 * For Fibre channel,
9209 	 */
9210 	if (fe->port_type == CTL_PORT_FC)
9211 	{
9212 		desc->proto_codeset = (SCSI_PROTO_FC << 4) |
9213 				      SVPD_ID_CODESET_ASCII;
9214         	desc1->proto_codeset = (SCSI_PROTO_FC << 4) |
9215 		              SVPD_ID_CODESET_BINARY;
9216 	}
9217 	else
9218 	{
9219 		desc->proto_codeset = (SCSI_PROTO_SPI << 4) |
9220 				      SVPD_ID_CODESET_ASCII;
9221         	desc1->proto_codeset = (SCSI_PROTO_SPI << 4) |
9222 		              SVPD_ID_CODESET_BINARY;
9223 	}
9224 	desc2->proto_codeset = desc3->proto_codeset = desc1->proto_codeset;
9225 	mtx_unlock(&ctl_softc->ctl_lock);
9226 
9227 	/*
9228 	 * We're using a LUN association here.  i.e., this device ID is a
9229 	 * per-LUN identifier.
9230 	 */
9231 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
9232 	desc->length = sizeof(*t10id) + CTL_DEVID_LEN;
9233 	strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
9234 
9235 	/*
9236 	 * desc1 is for the WWPN which is a port asscociation.
9237 	 */
9238 	desc1->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT | SVPD_ID_TYPE_NAA;
9239 	desc1->length = CTL_WWPN_LEN;
9240 	/* XXX Call Reggie's get_WWNN func here then add port # to the end */
9241 	/* For testing just create the WWPN */
9242 #if 0
9243 	ddb_GetWWNN((char *)desc1->identifier);
9244 
9245 	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9246 	/* This is so Copancontrol will return something sane */
9247 	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9248 	    ctsio->io_hdr.nexus.targ_port!=8)
9249 		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port-1;
9250 	else
9251 		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port;
9252 #endif
9253 
9254 	be64enc(desc1->identifier, fe->wwpn);
9255 
9256 	/*
9257 	 * desc2 is for the Relative Target Port(type 4h) identifier
9258 	 */
9259 	desc2->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9260 	                 | SVPD_ID_TYPE_RELTARG;
9261 	desc2->length = 4;
9262 //#if 0
9263 	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9264 	/* This is so Copancontrol will return something sane */
9265 	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9266 	    ctsio->io_hdr.nexus.targ_port!=8)
9267 		desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port - 1;
9268 	else
9269 	        desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port;
9270 //#endif
9271 
9272 	/*
9273 	 * desc3 is for the Target Port Group(type 5h) identifier
9274 	 */
9275 	desc3->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9276 	                 | SVPD_ID_TYPE_TPORTGRP;
9277 	desc3->length = 4;
9278 	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS || ctl_is_single)
9279 		desc3->identifier[3] = 1;
9280 	else
9281 		desc3->identifier[3] = 2;
9282 
9283 #ifdef CTL_USE_BACKEND_SN
9284 	/*
9285 	 * If we've actually got a backend, copy the device id from the
9286 	 * per-LUN data.  Otherwise, set it to all spaces.
9287 	 */
9288 	if (lun != NULL) {
9289 		/*
9290 		 * Copy the backend's LUN ID.
9291 		 */
9292 		strncpy((char *)t10id->vendor_spec_id,
9293 			(char *)lun->be_lun->device_id, CTL_DEVID_LEN);
9294 	} else {
9295 		/*
9296 		 * No backend, set this to spaces.
9297 		 */
9298 		memset(t10id->vendor_spec_id, 0x20, CTL_DEVID_LEN);
9299 	}
9300 #else
9301 	snprintf(tmpstr, sizeof(tmpstr), "MYDEVICEIDIS%4d",
9302 		 (lun != NULL) ?  (int)lun->lun : 0);
9303 	strncpy(t10id->vendor_spec_id, tmpstr, ctl_min(CTL_DEVID_LEN,
9304 		sizeof(tmpstr)));
9305 #endif
9306 
9307 	ctsio->scsi_status = SCSI_STATUS_OK;
9308 
9309 	ctsio->be_move_done = ctl_config_move_done;
9310 	ctl_datamove((union ctl_io *)ctsio);
9311 
9312 	return (CTL_RETVAL_COMPLETE);
9313 }
9314 
9315 static int
9316 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9317 {
9318 	struct scsi_inquiry *cdb;
9319 	int alloc_len, retval;
9320 
9321 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9322 
9323 	retval = CTL_RETVAL_COMPLETE;
9324 
9325 	alloc_len = scsi_2btoul(cdb->length);
9326 
9327 	switch (cdb->page_code) {
9328 	case SVPD_SUPPORTED_PAGES:
9329 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9330 		break;
9331 	case SVPD_UNIT_SERIAL_NUMBER:
9332 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9333 		break;
9334 	case SVPD_DEVICE_ID:
9335 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9336 		break;
9337 	default:
9338 		ctl_set_invalid_field(ctsio,
9339 				      /*sks_valid*/ 1,
9340 				      /*command*/ 1,
9341 				      /*field*/ 2,
9342 				      /*bit_valid*/ 0,
9343 				      /*bit*/ 0);
9344 		ctl_done((union ctl_io *)ctsio);
9345 		retval = CTL_RETVAL_COMPLETE;
9346 		break;
9347 	}
9348 
9349 	return (retval);
9350 }
9351 
9352 static int
9353 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9354 {
9355 	struct scsi_inquiry_data *inq_ptr;
9356 	struct scsi_inquiry *cdb;
9357 	struct ctl_softc *ctl_softc;
9358 	struct ctl_lun *lun;
9359 	uint32_t alloc_len;
9360 	int is_fc;
9361 
9362 	ctl_softc = control_softc;
9363 
9364 	/*
9365 	 * Figure out whether we're talking to a Fibre Channel port or not.
9366 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
9367 	 * SCSI front ends.
9368 	 */
9369 	mtx_lock(&ctl_softc->ctl_lock);
9370 	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
9371 	    CTL_PORT_FC)
9372 		is_fc = 0;
9373 	else
9374 		is_fc = 1;
9375 	mtx_unlock(&ctl_softc->ctl_lock);
9376 
9377 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9378 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9379 	alloc_len = scsi_2btoul(cdb->length);
9380 
9381 	/*
9382 	 * We malloc the full inquiry data size here and fill it
9383 	 * in.  If the user only asks for less, we'll give him
9384 	 * that much.
9385 	 */
9386 	/* XXX KDM what malloc flags should we use here?? */
9387 	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK);
9388 	if (ctsio->kern_data_ptr == NULL) {
9389 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
9390 		ctsio->scsi_status = SCSI_STATUS_BUSY;
9391 		ctl_done((union ctl_io *)ctsio);
9392 		return (CTL_RETVAL_COMPLETE);
9393 	}
9394 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9395 	ctsio->kern_sg_entries = 0;
9396 	ctsio->kern_data_resid = 0;
9397 	ctsio->kern_rel_offset = 0;
9398 
9399 	if (sizeof(*inq_ptr) < alloc_len) {
9400 		ctsio->residual = alloc_len - sizeof(*inq_ptr);
9401 		ctsio->kern_data_len = sizeof(*inq_ptr);
9402 		ctsio->kern_total_len = sizeof(*inq_ptr);
9403 	} else {
9404 		ctsio->residual = 0;
9405 		ctsio->kern_data_len = alloc_len;
9406 		ctsio->kern_total_len = alloc_len;
9407 	}
9408 
9409 	memset(inq_ptr, 0, sizeof(*inq_ptr));
9410 
9411 	/*
9412 	 * If we have a LUN configured, report it as connected.  Otherwise,
9413 	 * report that it is offline or no device is supported, depending
9414 	 * on the value of inquiry_pq_no_lun.
9415 	 *
9416 	 * According to the spec (SPC-4 r34), the peripheral qualifier
9417 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9418 	 *
9419 	 * "A peripheral device having the specified peripheral device type
9420 	 * is not connected to this logical unit. However, the device
9421 	 * server is capable of supporting the specified peripheral device
9422 	 * type on this logical unit."
9423 	 *
9424 	 * According to the same spec, the peripheral qualifier
9425 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
9426 	 *
9427 	 * "The device server is not capable of supporting a peripheral
9428 	 * device on this logical unit. For this peripheral qualifier the
9429 	 * peripheral device type shall be set to 1Fh. All other peripheral
9430 	 * device type values are reserved for this peripheral qualifier."
9431 	 *
9432 	 * Given the text, it would seem that we probably want to report that
9433 	 * the LUN is offline here.  There is no LUN connected, but we can
9434 	 * support a LUN at the given LUN number.
9435 	 *
9436 	 * In the real world, though, it sounds like things are a little
9437 	 * different:
9438 	 *
9439 	 * - Linux, when presented with a LUN with the offline peripheral
9440 	 *   qualifier, will create an sg driver instance for it.  So when
9441 	 *   you attach it to CTL, you wind up with a ton of sg driver
9442 	 *   instances.  (One for every LUN that Linux bothered to probe.)
9443 	 *   Linux does this despite the fact that it issues a REPORT LUNs
9444 	 *   to LUN 0 to get the inventory of supported LUNs.
9445 	 *
9446 	 * - There is other anecdotal evidence (from Emulex folks) about
9447 	 *   arrays that use the offline peripheral qualifier for LUNs that
9448 	 *   are on the "passive" path in an active/passive array.
9449 	 *
9450 	 * So the solution is provide a hopefully reasonable default
9451 	 * (return bad/no LUN) and allow the user to change the behavior
9452 	 * with a tunable/sysctl variable.
9453 	 */
9454 	if (lun != NULL)
9455 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9456 				  lun->be_lun->lun_type;
9457 	else if (ctl_softc->inquiry_pq_no_lun == 0)
9458 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9459 	else
9460 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9461 
9462 	/* RMB in byte 2 is 0 */
9463 	inq_ptr->version = SCSI_REV_SPC3;
9464 
9465 	/*
9466 	 * According to SAM-3, even if a device only supports a single
9467 	 * level of LUN addressing, it should still set the HISUP bit:
9468 	 *
9469 	 * 4.9.1 Logical unit numbers overview
9470 	 *
9471 	 * All logical unit number formats described in this standard are
9472 	 * hierarchical in structure even when only a single level in that
9473 	 * hierarchy is used. The HISUP bit shall be set to one in the
9474 	 * standard INQUIRY data (see SPC-2) when any logical unit number
9475 	 * format described in this standard is used.  Non-hierarchical
9476 	 * formats are outside the scope of this standard.
9477 	 *
9478 	 * Therefore we set the HiSup bit here.
9479 	 *
9480 	 * The reponse format is 2, per SPC-3.
9481 	 */
9482 	inq_ptr->response_format = SID_HiSup | 2;
9483 
9484 	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
9485 	CTL_DEBUG_PRINT(("additional_length = %d\n",
9486 			 inq_ptr->additional_length));
9487 
9488 	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
9489 	/* 16 bit addressing */
9490 	if (is_fc == 0)
9491 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
9492 	/* XXX set the SID_MultiP bit here if we're actually going to
9493 	   respond on multiple ports */
9494 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
9495 
9496 	/* 16 bit data bus, synchronous transfers */
9497 	/* XXX these flags don't apply for FC */
9498 	if (is_fc == 0)
9499 		inq_ptr->flags = SID_WBus16 | SID_Sync;
9500 	/*
9501 	 * XXX KDM do we want to support tagged queueing on the control
9502 	 * device at all?
9503 	 */
9504 	if ((lun == NULL)
9505 	 || (lun->be_lun->lun_type != T_PROCESSOR))
9506 		inq_ptr->flags |= SID_CmdQue;
9507 	/*
9508 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
9509 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
9510 	 * name and 4 bytes for the revision.
9511 	 */
9512 	strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
9513 	if (lun == NULL) {
9514 		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
9515 	} else {
9516 		switch (lun->be_lun->lun_type) {
9517 		case T_DIRECT:
9518 			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
9519 			break;
9520 		case T_PROCESSOR:
9521 			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
9522 			break;
9523 		default:
9524 			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
9525 			break;
9526 		}
9527 	}
9528 
9529 	/*
9530 	 * XXX make this a macro somewhere so it automatically gets
9531 	 * incremented when we make changes.
9532 	 */
9533 	strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
9534 
9535 	/*
9536 	 * For parallel SCSI, we support double transition and single
9537 	 * transition clocking.  We also support QAS (Quick Arbitration
9538 	 * and Selection) and Information Unit transfers on both the
9539 	 * control and array devices.
9540 	 */
9541 	if (is_fc == 0)
9542 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
9543 				    SID_SPI_IUS;
9544 
9545 	/* SAM-3 */
9546 	scsi_ulto2b(0x0060, inq_ptr->version1);
9547 	/* SPC-3 (no version claimed) XXX should we claim a version? */
9548 	scsi_ulto2b(0x0300, inq_ptr->version2);
9549 	if (is_fc) {
9550 		/* FCP-2 ANSI INCITS.350:2003 */
9551 		scsi_ulto2b(0x0917, inq_ptr->version3);
9552 	} else {
9553 		/* SPI-4 ANSI INCITS.362:200x */
9554 		scsi_ulto2b(0x0B56, inq_ptr->version3);
9555 	}
9556 
9557 	if (lun == NULL) {
9558 		/* SBC-2 (no version claimed) XXX should we claim a version? */
9559 		scsi_ulto2b(0x0320, inq_ptr->version4);
9560 	} else {
9561 		switch (lun->be_lun->lun_type) {
9562 		case T_DIRECT:
9563 			/*
9564 			 * SBC-2 (no version claimed) XXX should we claim a
9565 			 * version?
9566 			 */
9567 			scsi_ulto2b(0x0320, inq_ptr->version4);
9568 			break;
9569 		case T_PROCESSOR:
9570 		default:
9571 			break;
9572 		}
9573 	}
9574 
9575 	ctsio->scsi_status = SCSI_STATUS_OK;
9576 	if (ctsio->kern_data_len > 0) {
9577 		ctsio->be_move_done = ctl_config_move_done;
9578 		ctl_datamove((union ctl_io *)ctsio);
9579 	} else {
9580 		ctsio->io_hdr.status = CTL_SUCCESS;
9581 		ctl_done((union ctl_io *)ctsio);
9582 	}
9583 
9584 	return (CTL_RETVAL_COMPLETE);
9585 }
9586 
9587 int
9588 ctl_inquiry(struct ctl_scsiio *ctsio)
9589 {
9590 	struct scsi_inquiry *cdb;
9591 	int retval;
9592 
9593 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9594 
9595 	retval = 0;
9596 
9597 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
9598 
9599 	/*
9600 	 * Right now, we don't support the CmdDt inquiry information.
9601 	 * This would be nice to support in the future.  When we do
9602 	 * support it, we should change this test so that it checks to make
9603 	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
9604 	 */
9605 #ifdef notyet
9606 	if (((cdb->byte2 & SI_EVPD)
9607 	 && (cdb->byte2 & SI_CMDDT)))
9608 #endif
9609 	if (cdb->byte2 & SI_CMDDT) {
9610 		/*
9611 		 * Point to the SI_CMDDT bit.  We might change this
9612 		 * when we support SI_CMDDT, but since both bits would be
9613 		 * "wrong", this should probably just stay as-is then.
9614 		 */
9615 		ctl_set_invalid_field(ctsio,
9616 				      /*sks_valid*/ 1,
9617 				      /*command*/ 1,
9618 				      /*field*/ 1,
9619 				      /*bit_valid*/ 1,
9620 				      /*bit*/ 1);
9621 		ctl_done((union ctl_io *)ctsio);
9622 		return (CTL_RETVAL_COMPLETE);
9623 	}
9624 	if (cdb->byte2 & SI_EVPD)
9625 		retval = ctl_inquiry_evpd(ctsio);
9626 #ifdef notyet
9627 	else if (cdb->byte2 & SI_CMDDT)
9628 		retval = ctl_inquiry_cmddt(ctsio);
9629 #endif
9630 	else
9631 		retval = ctl_inquiry_std(ctsio);
9632 
9633 	return (retval);
9634 }
9635 
9636 /*
9637  * For known CDB types, parse the LBA and length.
9638  */
9639 static int
9640 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
9641 {
9642 	if (io->io_hdr.io_type != CTL_IO_SCSI)
9643 		return (1);
9644 
9645 	switch (io->scsiio.cdb[0]) {
9646 	case READ_6:
9647 	case WRITE_6: {
9648 		struct scsi_rw_6 *cdb;
9649 
9650 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
9651 
9652 		*lba = scsi_3btoul(cdb->addr);
9653 		/* only 5 bits are valid in the most significant address byte */
9654 		*lba &= 0x1fffff;
9655 		*len = cdb->length;
9656 		break;
9657 	}
9658 	case READ_10:
9659 	case WRITE_10: {
9660 		struct scsi_rw_10 *cdb;
9661 
9662 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
9663 
9664 		*lba = scsi_4btoul(cdb->addr);
9665 		*len = scsi_2btoul(cdb->length);
9666 		break;
9667 	}
9668 	case WRITE_VERIFY_10: {
9669 		struct scsi_write_verify_10 *cdb;
9670 
9671 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
9672 
9673 		*lba = scsi_4btoul(cdb->addr);
9674 		*len = scsi_2btoul(cdb->length);
9675 		break;
9676 	}
9677 	case READ_12:
9678 	case WRITE_12: {
9679 		struct scsi_rw_12 *cdb;
9680 
9681 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
9682 
9683 		*lba = scsi_4btoul(cdb->addr);
9684 		*len = scsi_4btoul(cdb->length);
9685 		break;
9686 	}
9687 	case WRITE_VERIFY_12: {
9688 		struct scsi_write_verify_12 *cdb;
9689 
9690 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
9691 
9692 		*lba = scsi_4btoul(cdb->addr);
9693 		*len = scsi_4btoul(cdb->length);
9694 		break;
9695 	}
9696 	case READ_16:
9697 	case WRITE_16: {
9698 		struct scsi_rw_16 *cdb;
9699 
9700 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
9701 
9702 		*lba = scsi_8btou64(cdb->addr);
9703 		*len = scsi_4btoul(cdb->length);
9704 		break;
9705 	}
9706 	case WRITE_VERIFY_16: {
9707 		struct scsi_write_verify_16 *cdb;
9708 
9709 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
9710 
9711 
9712 		*lba = scsi_8btou64(cdb->addr);
9713 		*len = scsi_4btoul(cdb->length);
9714 		break;
9715 	}
9716 	default:
9717 		return (1);
9718 		break; /* NOTREACHED */
9719 	}
9720 
9721 	return (0);
9722 }
9723 
9724 static ctl_action
9725 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
9726 {
9727 	uint64_t endlba1, endlba2;
9728 
9729 	endlba1 = lba1 + len1 - 1;
9730 	endlba2 = lba2 + len2 - 1;
9731 
9732 	if ((endlba1 < lba2)
9733 	 || (endlba2 < lba1))
9734 		return (CTL_ACTION_PASS);
9735 	else
9736 		return (CTL_ACTION_BLOCK);
9737 }
9738 
9739 static ctl_action
9740 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
9741 {
9742 	uint64_t lba1, lba2;
9743 	uint32_t len1, len2;
9744 	int retval;
9745 
9746 	retval = ctl_get_lba_len(io1, &lba1, &len1);
9747 	if (retval != 0)
9748 		return (CTL_ACTION_ERROR);
9749 
9750 	retval = ctl_get_lba_len(io2, &lba2, &len2);
9751 	if (retval != 0)
9752 		return (CTL_ACTION_ERROR);
9753 
9754 	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
9755 }
9756 
9757 static ctl_action
9758 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
9759 {
9760 	struct ctl_cmd_entry *pending_entry, *ooa_entry;
9761 	ctl_serialize_action *serialize_row;
9762 
9763 	/*
9764 	 * The initiator attempted multiple untagged commands at the same
9765 	 * time.  Can't do that.
9766 	 */
9767 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
9768 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
9769 	 && ((pending_io->io_hdr.nexus.targ_port ==
9770 	      ooa_io->io_hdr.nexus.targ_port)
9771 	  && (pending_io->io_hdr.nexus.initid.id ==
9772 	      ooa_io->io_hdr.nexus.initid.id))
9773 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
9774 		return (CTL_ACTION_OVERLAP);
9775 
9776 	/*
9777 	 * The initiator attempted to send multiple tagged commands with
9778 	 * the same ID.  (It's fine if different initiators have the same
9779 	 * tag ID.)
9780 	 *
9781 	 * Even if all of those conditions are true, we don't kill the I/O
9782 	 * if the command ahead of us has been aborted.  We won't end up
9783 	 * sending it to the FETD, and it's perfectly legal to resend a
9784 	 * command with the same tag number as long as the previous
9785 	 * instance of this tag number has been aborted somehow.
9786 	 */
9787 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
9788 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
9789 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
9790 	 && ((pending_io->io_hdr.nexus.targ_port ==
9791 	      ooa_io->io_hdr.nexus.targ_port)
9792 	  && (pending_io->io_hdr.nexus.initid.id ==
9793 	      ooa_io->io_hdr.nexus.initid.id))
9794 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
9795 		return (CTL_ACTION_OVERLAP_TAG);
9796 
9797 	/*
9798 	 * If we get a head of queue tag, SAM-3 says that we should
9799 	 * immediately execute it.
9800 	 *
9801 	 * What happens if this command would normally block for some other
9802 	 * reason?  e.g. a request sense with a head of queue tag
9803 	 * immediately after a write.  Normally that would block, but this
9804 	 * will result in its getting executed immediately...
9805 	 *
9806 	 * We currently return "pass" instead of "skip", so we'll end up
9807 	 * going through the rest of the queue to check for overlapped tags.
9808 	 *
9809 	 * XXX KDM check for other types of blockage first??
9810 	 */
9811 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
9812 		return (CTL_ACTION_PASS);
9813 
9814 	/*
9815 	 * Ordered tags have to block until all items ahead of them
9816 	 * have completed.  If we get called with an ordered tag, we always
9817 	 * block, if something else is ahead of us in the queue.
9818 	 */
9819 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
9820 		return (CTL_ACTION_BLOCK);
9821 
9822 	/*
9823 	 * Simple tags get blocked until all head of queue and ordered tags
9824 	 * ahead of them have completed.  I'm lumping untagged commands in
9825 	 * with simple tags here.  XXX KDM is that the right thing to do?
9826 	 */
9827 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
9828 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
9829 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
9830 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
9831 		return (CTL_ACTION_BLOCK);
9832 
9833 	pending_entry = &ctl_cmd_table[pending_io->scsiio.cdb[0]];
9834 	ooa_entry = &ctl_cmd_table[ooa_io->scsiio.cdb[0]];
9835 
9836 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
9837 
9838 	switch (serialize_row[pending_entry->seridx]) {
9839 	case CTL_SER_BLOCK:
9840 		return (CTL_ACTION_BLOCK);
9841 		break; /* NOTREACHED */
9842 	case CTL_SER_EXTENT:
9843 		return (ctl_extent_check(pending_io, ooa_io));
9844 		break; /* NOTREACHED */
9845 	case CTL_SER_PASS:
9846 		return (CTL_ACTION_PASS);
9847 		break; /* NOTREACHED */
9848 	case CTL_SER_SKIP:
9849 		return (CTL_ACTION_SKIP);
9850 		break;
9851 	default:
9852 		panic("invalid serialization value %d",
9853 		      serialize_row[pending_entry->seridx]);
9854 		break; /* NOTREACHED */
9855 	}
9856 
9857 	return (CTL_ACTION_ERROR);
9858 }
9859 
9860 /*
9861  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
9862  * Assumptions:
9863  * - caller holds ctl_lock
9864  * - pending_io is generally either incoming, or on the blocked queue
9865  * - starting I/O is the I/O we want to start the check with.
9866  */
9867 static ctl_action
9868 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
9869 	      union ctl_io *starting_io)
9870 {
9871 	union ctl_io *ooa_io;
9872 	ctl_action action;
9873 
9874 	/*
9875 	 * Run back along the OOA queue, starting with the current
9876 	 * blocked I/O and going through every I/O before it on the
9877 	 * queue.  If starting_io is NULL, we'll just end up returning
9878 	 * CTL_ACTION_PASS.
9879 	 */
9880 	for (ooa_io = starting_io; ooa_io != NULL;
9881 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
9882 	     ooa_links)){
9883 
9884 		/*
9885 		 * This routine just checks to see whether
9886 		 * cur_blocked is blocked by ooa_io, which is ahead
9887 		 * of it in the queue.  It doesn't queue/dequeue
9888 		 * cur_blocked.
9889 		 */
9890 		action = ctl_check_for_blockage(pending_io, ooa_io);
9891 		switch (action) {
9892 		case CTL_ACTION_BLOCK:
9893 		case CTL_ACTION_OVERLAP:
9894 		case CTL_ACTION_OVERLAP_TAG:
9895 		case CTL_ACTION_SKIP:
9896 		case CTL_ACTION_ERROR:
9897 			return (action);
9898 			break; /* NOTREACHED */
9899 		case CTL_ACTION_PASS:
9900 			break;
9901 		default:
9902 			panic("invalid action %d", action);
9903 			break;  /* NOTREACHED */
9904 		}
9905 	}
9906 
9907 	return (CTL_ACTION_PASS);
9908 }
9909 
9910 /*
9911  * Assumptions:
9912  * - An I/O has just completed, and has been removed from the per-LUN OOA
9913  *   queue, so some items on the blocked queue may now be unblocked.
9914  * - The caller holds ctl_softc->ctl_lock
9915  */
9916 static int
9917 ctl_check_blocked(struct ctl_lun *lun)
9918 {
9919 	union ctl_io *cur_blocked, *next_blocked;
9920 
9921 	/*
9922 	 * Run forward from the head of the blocked queue, checking each
9923 	 * entry against the I/Os prior to it on the OOA queue to see if
9924 	 * there is still any blockage.
9925 	 *
9926 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
9927 	 * with our removing a variable on it while it is traversing the
9928 	 * list.
9929 	 */
9930 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
9931 	     cur_blocked != NULL; cur_blocked = next_blocked) {
9932 		union ctl_io *prev_ooa;
9933 		ctl_action action;
9934 
9935 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
9936 							  blocked_links);
9937 
9938 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
9939 						      ctl_ooaq, ooa_links);
9940 
9941 		/*
9942 		 * If cur_blocked happens to be the first item in the OOA
9943 		 * queue now, prev_ooa will be NULL, and the action
9944 		 * returned will just be CTL_ACTION_PASS.
9945 		 */
9946 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
9947 
9948 		switch (action) {
9949 		case CTL_ACTION_BLOCK:
9950 			/* Nothing to do here, still blocked */
9951 			break;
9952 		case CTL_ACTION_OVERLAP:
9953 		case CTL_ACTION_OVERLAP_TAG:
9954 			/*
9955 			 * This shouldn't happen!  In theory we've already
9956 			 * checked this command for overlap...
9957 			 */
9958 			break;
9959 		case CTL_ACTION_PASS:
9960 		case CTL_ACTION_SKIP: {
9961 			struct ctl_softc *softc;
9962 			struct ctl_cmd_entry *entry;
9963 			uint32_t initidx;
9964 			uint8_t opcode;
9965 			int isc_retval;
9966 
9967 			/*
9968 			 * The skip case shouldn't happen, this transaction
9969 			 * should have never made it onto the blocked queue.
9970 			 */
9971 			/*
9972 			 * This I/O is no longer blocked, we can remove it
9973 			 * from the blocked queue.  Since this is a TAILQ
9974 			 * (doubly linked list), we can do O(1) removals
9975 			 * from any place on the list.
9976 			 */
9977 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
9978 				     blocked_links);
9979 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
9980 
9981 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
9982 				/*
9983 				 * Need to send IO back to original side to
9984 				 * run
9985 				 */
9986 				union ctl_ha_msg msg_info;
9987 
9988 				msg_info.hdr.original_sc =
9989 					cur_blocked->io_hdr.original_sc;
9990 				msg_info.hdr.serializing_sc = cur_blocked;
9991 				msg_info.hdr.msg_type = CTL_MSG_R2R;
9992 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
9993 				     &msg_info, sizeof(msg_info), 0)) >
9994 				     CTL_HA_STATUS_SUCCESS) {
9995 					printf("CTL:Check Blocked error from "
9996 					       "ctl_ha_msg_send %d\n",
9997 					       isc_retval);
9998 				}
9999 				break;
10000 			}
10001 			opcode = cur_blocked->scsiio.cdb[0];
10002 			entry = &ctl_cmd_table[opcode];
10003 			softc = control_softc;
10004 
10005 			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10006 
10007 			/*
10008 			 * Check this I/O for LUN state changes that may
10009 			 * have happened while this command was blocked.
10010 			 * The LUN state may have been changed by a command
10011 			 * ahead of us in the queue, so we need to re-check
10012 			 * for any states that can be caused by SCSI
10013 			 * commands.
10014 			 */
10015 			if (ctl_scsiio_lun_check(softc, lun, entry,
10016 						 &cur_blocked->scsiio) == 0) {
10017 				cur_blocked->io_hdr.flags |=
10018 				                      CTL_FLAG_IS_WAS_ON_RTR;
10019 				STAILQ_INSERT_TAIL(&lun->ctl_softc->rtr_queue,
10020 						   &cur_blocked->io_hdr, links);
10021 				/*
10022 				 * In the non CTL_DONE_THREAD case, we need
10023 				 * to wake up the work thread here.  When
10024 				 * we're processing completed requests from
10025 				 * the work thread context, we'll pop back
10026 				 * around and end up pulling things off the
10027 				 * RtR queue.  When we aren't processing
10028 				 * things from the work thread context,
10029 				 * though, we won't ever check the RtR queue.
10030 				 * So we need to wake up the thread to clear
10031 				 * things off the queue.  Otherwise this
10032 				 * transaction will just sit on the RtR queue
10033 				 * until a new I/O comes in.  (Which may or
10034 				 * may not happen...)
10035 				 */
10036 #ifndef CTL_DONE_THREAD
10037 				ctl_wakeup_thread();
10038 #endif
10039 			} else
10040 				ctl_done_lock(cur_blocked, /*have_lock*/ 1);
10041 			break;
10042 		}
10043 		default:
10044 			/*
10045 			 * This probably shouldn't happen -- we shouldn't
10046 			 * get CTL_ACTION_ERROR, or anything else.
10047 			 */
10048 			break;
10049 		}
10050 	}
10051 
10052 	return (CTL_RETVAL_COMPLETE);
10053 }
10054 
10055 /*
10056  * This routine (with one exception) checks LUN flags that can be set by
10057  * commands ahead of us in the OOA queue.  These flags have to be checked
10058  * when a command initially comes in, and when we pull a command off the
10059  * blocked queue and are preparing to execute it.  The reason we have to
10060  * check these flags for commands on the blocked queue is that the LUN
10061  * state may have been changed by a command ahead of us while we're on the
10062  * blocked queue.
10063  *
10064  * Ordering is somewhat important with these checks, so please pay
10065  * careful attention to the placement of any new checks.
10066  */
10067 static int
10068 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10069 		     struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10070 {
10071 	int retval;
10072 
10073 	retval = 0;
10074 
10075 	/*
10076 	 * If this shelf is a secondary shelf controller, we have to reject
10077 	 * any media access commands.
10078 	 */
10079 #if 0
10080 	/* No longer needed for HA */
10081 	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10082 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10083 		ctl_set_lun_standby(ctsio);
10084 		retval = 1;
10085 		goto bailout;
10086 	}
10087 #endif
10088 
10089 	/*
10090 	 * Check for a reservation conflict.  If this command isn't allowed
10091 	 * even on reserved LUNs, and if this initiator isn't the one who
10092 	 * reserved us, reject the command with a reservation conflict.
10093 	 */
10094 	if ((lun->flags & CTL_LUN_RESERVED)
10095 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10096 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10097 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10098 		 || (ctsio->io_hdr.nexus.targ_target.id !=
10099 		     lun->rsv_nexus.targ_target.id)) {
10100 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10101 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10102 			retval = 1;
10103 			goto bailout;
10104 		}
10105 	}
10106 
10107 	if ( (lun->flags & CTL_LUN_PR_RESERVED)
10108 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10109 		uint32_t residx;
10110 
10111 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10112 		/*
10113 		 * if we aren't registered or it's a res holder type
10114 		 * reservation and this isn't the res holder then set a
10115 		 * conflict.
10116 		 * NOTE: Commands which might be allowed on write exclusive
10117 		 * type reservations are checked in the particular command
10118 		 * for a conflict. Read and SSU are the only ones.
10119 		 */
10120 		if (!lun->per_res[residx].registered
10121 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10122 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10123 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10124 			retval = 1;
10125 			goto bailout;
10126 		}
10127 
10128 	}
10129 
10130 	if ((lun->flags & CTL_LUN_OFFLINE)
10131 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10132 		ctl_set_lun_not_ready(ctsio);
10133 		retval = 1;
10134 		goto bailout;
10135 	}
10136 
10137 	/*
10138 	 * If the LUN is stopped, see if this particular command is allowed
10139 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10140 	 */
10141 	if ((lun->flags & CTL_LUN_STOPPED)
10142 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10143 		/* "Logical unit not ready, initializing cmd. required" */
10144 		ctl_set_lun_stopped(ctsio);
10145 		retval = 1;
10146 		goto bailout;
10147 	}
10148 
10149 	if ((lun->flags & CTL_LUN_INOPERABLE)
10150 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10151 		/* "Medium format corrupted" */
10152 		ctl_set_medium_format_corrupted(ctsio);
10153 		retval = 1;
10154 		goto bailout;
10155 	}
10156 
10157 bailout:
10158 	return (retval);
10159 
10160 }
10161 
10162 static void
10163 ctl_failover_io(union ctl_io *io, int have_lock)
10164 {
10165 	ctl_set_busy(&io->scsiio);
10166 	ctl_done_lock(io, have_lock);
10167 }
10168 
10169 static void
10170 ctl_failover(void)
10171 {
10172 	struct ctl_lun *lun;
10173 	struct ctl_softc *ctl_softc;
10174 	union ctl_io *next_io, *pending_io;
10175 	union ctl_io *io;
10176 	int lun_idx;
10177 	int i;
10178 
10179 	ctl_softc = control_softc;
10180 
10181 	mtx_lock(&ctl_softc->ctl_lock);
10182 	/*
10183 	 * Remove any cmds from the other SC from the rtr queue.  These
10184 	 * will obviously only be for LUNs for which we're the primary.
10185 	 * We can't send status or get/send data for these commands.
10186 	 * Since they haven't been executed yet, we can just remove them.
10187 	 * We'll either abort them or delete them below, depending on
10188 	 * which HA mode we're in.
10189 	 */
10190 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10191 	     io != NULL; io = next_io) {
10192 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10193 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10194 			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10195 				      ctl_io_hdr, links);
10196 	}
10197 
10198 	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
10199 		lun = ctl_softc->ctl_luns[lun_idx];
10200 		if (lun==NULL)
10201 			continue;
10202 
10203 		/*
10204 		 * Processor LUNs are primary on both sides.
10205 		 * XXX will this always be true?
10206 		 */
10207 		if (lun->be_lun->lun_type == T_PROCESSOR)
10208 			continue;
10209 
10210 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
10211 		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10212 			printf("FAILOVER: primary lun %d\n", lun_idx);
10213 		        /*
10214 			 * Remove all commands from the other SC. First from the
10215 			 * blocked queue then from the ooa queue. Once we have
10216 			 * removed them. Call ctl_check_blocked to see if there
10217 			 * is anything that can run.
10218 			 */
10219 			for (io = (union ctl_io *)TAILQ_FIRST(
10220 			     &lun->blocked_queue); io != NULL; io = next_io) {
10221 
10222 		        	next_io = (union ctl_io *)TAILQ_NEXT(
10223 				    &io->io_hdr, blocked_links);
10224 
10225 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10226 					TAILQ_REMOVE(&lun->blocked_queue,
10227 						     &io->io_hdr,blocked_links);
10228 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10229 					TAILQ_REMOVE(&lun->ooa_queue,
10230 						     &io->io_hdr, ooa_links);
10231 
10232 					ctl_free_io_internal(io, 1);
10233 				}
10234 			}
10235 
10236 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10237 	     		     io != NULL; io = next_io) {
10238 
10239 		        	next_io = (union ctl_io *)TAILQ_NEXT(
10240 				    &io->io_hdr, ooa_links);
10241 
10242 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10243 
10244 					TAILQ_REMOVE(&lun->ooa_queue,
10245 						&io->io_hdr,
10246 					     	ooa_links);
10247 
10248 					ctl_free_io_internal(io, 1);
10249 				}
10250 			}
10251 			ctl_check_blocked(lun);
10252 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10253 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10254 
10255 			printf("FAILOVER: primary lun %d\n", lun_idx);
10256 			/*
10257 			 * Abort all commands from the other SC.  We can't
10258 			 * send status back for them now.  These should get
10259 			 * cleaned up when they are completed or come out
10260 			 * for a datamove operation.
10261 			 */
10262 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10263 	     		     io != NULL; io = next_io) {
10264 		        	next_io = (union ctl_io *)TAILQ_NEXT(
10265 					&io->io_hdr, ooa_links);
10266 
10267 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10268 					io->io_hdr.flags |= CTL_FLAG_ABORT;
10269 			}
10270 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10271 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10272 
10273 			printf("FAILOVER: secondary lun %d\n", lun_idx);
10274 
10275 			lun->flags |= CTL_LUN_PRIMARY_SC;
10276 
10277 			/*
10278 			 * We send all I/O that was sent to this controller
10279 			 * and redirected to the other side back with
10280 			 * busy status, and have the initiator retry it.
10281 			 * Figuring out how much data has been transferred,
10282 			 * etc. and picking up where we left off would be
10283 			 * very tricky.
10284 			 *
10285 			 * XXX KDM need to remove I/O from the blocked
10286 			 * queue as well!
10287 			 */
10288 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
10289 			     &lun->ooa_queue); pending_io != NULL;
10290 			     pending_io = next_io) {
10291 
10292 				next_io =  (union ctl_io *)TAILQ_NEXT(
10293 					&pending_io->io_hdr, ooa_links);
10294 
10295 				pending_io->io_hdr.flags &=
10296 					~CTL_FLAG_SENT_2OTHER_SC;
10297 
10298 				if (pending_io->io_hdr.flags &
10299 				    CTL_FLAG_IO_ACTIVE) {
10300 					pending_io->io_hdr.flags |=
10301 						CTL_FLAG_FAILOVER;
10302 				} else {
10303 					ctl_set_busy(&pending_io->scsiio);
10304 					ctl_done_lock(pending_io,
10305 						      /*have_lock*/1);
10306 				}
10307 			}
10308 
10309 			/*
10310 			 * Build Unit Attention
10311 			 */
10312 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10313 				lun->pending_sense[i].ua_pending |=
10314 				                     CTL_UA_ASYM_ACC_CHANGE;
10315 			}
10316 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10317 			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10318 			printf("FAILOVER: secondary lun %d\n", lun_idx);
10319 			/*
10320 			 * if the first io on the OOA is not on the RtR queue
10321 			 * add it.
10322 			 */
10323 			lun->flags |= CTL_LUN_PRIMARY_SC;
10324 
10325 			pending_io = (union ctl_io *)TAILQ_FIRST(
10326 			    &lun->ooa_queue);
10327 			if (pending_io==NULL) {
10328 				printf("Nothing on OOA queue\n");
10329 				continue;
10330 			}
10331 
10332 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10333 			if ((pending_io->io_hdr.flags &
10334 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
10335 				pending_io->io_hdr.flags |=
10336 				    CTL_FLAG_IS_WAS_ON_RTR;
10337 				STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
10338 						   &pending_io->io_hdr, links);
10339 			}
10340 #if 0
10341 			else
10342 			{
10343 				printf("Tag 0x%04x is running\n",
10344 				      pending_io->scsiio.tag_num);
10345 			}
10346 #endif
10347 
10348 			next_io = (union ctl_io *)TAILQ_NEXT(
10349 			    &pending_io->io_hdr, ooa_links);
10350 			for (pending_io=next_io; pending_io != NULL;
10351 			     pending_io = next_io) {
10352 				pending_io->io_hdr.flags &=
10353 				    ~CTL_FLAG_SENT_2OTHER_SC;
10354 				next_io = (union ctl_io *)TAILQ_NEXT(
10355 					&pending_io->io_hdr, ooa_links);
10356 				if (pending_io->io_hdr.flags &
10357 				    CTL_FLAG_IS_WAS_ON_RTR) {
10358 #if 0
10359 				        printf("Tag 0x%04x is running\n",
10360 				      		pending_io->scsiio.tag_num);
10361 #endif
10362 					continue;
10363 				}
10364 
10365 				switch (ctl_check_ooa(lun, pending_io,
10366 			            (union ctl_io *)TAILQ_PREV(
10367 				    &pending_io->io_hdr, ctl_ooaq,
10368 				    ooa_links))) {
10369 
10370 				case CTL_ACTION_BLOCK:
10371 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
10372 							  &pending_io->io_hdr,
10373 							  blocked_links);
10374 					pending_io->io_hdr.flags |=
10375 					    CTL_FLAG_BLOCKED;
10376 					break;
10377 				case CTL_ACTION_PASS:
10378 				case CTL_ACTION_SKIP:
10379 					pending_io->io_hdr.flags |=
10380 					    CTL_FLAG_IS_WAS_ON_RTR;
10381 					STAILQ_INSERT_TAIL(
10382 					    &ctl_softc->rtr_queue,
10383 					    &pending_io->io_hdr, links);
10384 					break;
10385 				case CTL_ACTION_OVERLAP:
10386 					ctl_set_overlapped_cmd(
10387 					    (struct ctl_scsiio *)pending_io);
10388 					ctl_done_lock(pending_io,
10389 						      /*have_lock*/ 1);
10390 					break;
10391 				case CTL_ACTION_OVERLAP_TAG:
10392 					ctl_set_overlapped_tag(
10393 					    (struct ctl_scsiio *)pending_io,
10394 					    pending_io->scsiio.tag_num & 0xff);
10395 					ctl_done_lock(pending_io,
10396 						      /*have_lock*/ 1);
10397 					break;
10398 				case CTL_ACTION_ERROR:
10399 				default:
10400 					ctl_set_internal_failure(
10401 						(struct ctl_scsiio *)pending_io,
10402 						0,  // sks_valid
10403 						0); //retry count
10404 					ctl_done_lock(pending_io,
10405 						      /*have_lock*/ 1);
10406 					break;
10407 				}
10408 			}
10409 
10410 			/*
10411 			 * Build Unit Attention
10412 			 */
10413 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10414 				lun->pending_sense[i].ua_pending |=
10415 				                     CTL_UA_ASYM_ACC_CHANGE;
10416 			}
10417 		} else {
10418 			panic("Unhandled HA mode failover, LUN flags = %#x, "
10419 			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
10420 		}
10421 	}
10422 	ctl_pause_rtr = 0;
10423 	mtx_unlock(&ctl_softc->ctl_lock);
10424 }
10425 
10426 static int
10427 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
10428 {
10429 	struct ctl_lun *lun;
10430 	struct ctl_cmd_entry *entry;
10431 	uint8_t opcode;
10432 	uint32_t initidx;
10433 	int retval;
10434 
10435 	retval = 0;
10436 
10437 	lun = NULL;
10438 
10439 	opcode = ctsio->cdb[0];
10440 
10441 	mtx_lock(&ctl_softc->ctl_lock);
10442 
10443 	if ((ctsio->io_hdr.nexus.targ_lun < CTL_MAX_LUNS)
10444 	 && (ctl_softc->ctl_luns[ctsio->io_hdr.nexus.targ_lun] != NULL)) {
10445 		lun = ctl_softc->ctl_luns[ctsio->io_hdr.nexus.targ_lun];
10446 		/*
10447 		 * If the LUN is invalid, pretend that it doesn't exist.
10448 		 * It will go away as soon as all pending I/O has been
10449 		 * completed.
10450 		 */
10451 		if (lun->flags & CTL_LUN_DISABLED) {
10452 			lun = NULL;
10453 		} else {
10454 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
10455 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
10456 				lun->be_lun;
10457 			if (lun->be_lun->lun_type == T_PROCESSOR) {
10458 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
10459 			}
10460 		}
10461 	} else {
10462 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
10463 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
10464 	}
10465 
10466 	entry = &ctl_cmd_table[opcode];
10467 
10468 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
10469 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
10470 
10471 	/*
10472 	 * Check to see whether we can send this command to LUNs that don't
10473 	 * exist.  This should pretty much only be the case for inquiry
10474 	 * and request sense.  Further checks, below, really require having
10475 	 * a LUN, so we can't really check the command anymore.  Just put
10476 	 * it on the rtr queue.
10477 	 */
10478 	if (lun == NULL) {
10479 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
10480 			goto queue_rtr;
10481 
10482 		ctl_set_unsupported_lun(ctsio);
10483 		mtx_unlock(&ctl_softc->ctl_lock);
10484 		ctl_done((union ctl_io *)ctsio);
10485 		goto bailout;
10486 	} else {
10487 		/*
10488 		 * Every I/O goes into the OOA queue for a particular LUN, and
10489 		 * stays there until completion.
10490 		 */
10491 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
10492 
10493 		/*
10494 		 * Make sure we support this particular command on this LUN.
10495 		 * e.g., we don't support writes to the control LUN.
10496 		 */
10497 		switch (lun->be_lun->lun_type) {
10498 		case T_PROCESSOR:
10499 		 	if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
10500 			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
10501 			      == 0)) {
10502 				ctl_set_invalid_opcode(ctsio);
10503 				mtx_unlock(&ctl_softc->ctl_lock);
10504 				ctl_done((union ctl_io *)ctsio);
10505 				goto bailout;
10506 			}
10507 			break;
10508 		case T_DIRECT:
10509 			if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
10510 			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
10511 			      == 0)){
10512 				ctl_set_invalid_opcode(ctsio);
10513 				mtx_unlock(&ctl_softc->ctl_lock);
10514 				ctl_done((union ctl_io *)ctsio);
10515 				goto bailout;
10516 			}
10517 			break;
10518 		default:
10519 			printf("Unsupported CTL LUN type %d\n",
10520 			       lun->be_lun->lun_type);
10521 			panic("Unsupported CTL LUN type %d\n",
10522 			      lun->be_lun->lun_type);
10523 			break; /* NOTREACHED */
10524 		}
10525 	}
10526 
10527 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10528 
10529 	/*
10530 	 * If we've got a request sense, it'll clear the contingent
10531 	 * allegiance condition.  Otherwise, if we have a CA condition for
10532 	 * this initiator, clear it, because it sent down a command other
10533 	 * than request sense.
10534 	 */
10535 	if ((opcode != REQUEST_SENSE)
10536 	 && (ctl_is_set(lun->have_ca, initidx)))
10537 		ctl_clear_mask(lun->have_ca, initidx);
10538 
10539 	/*
10540 	 * If the command has this flag set, it handles its own unit
10541 	 * attention reporting, we shouldn't do anything.  Otherwise we
10542 	 * check for any pending unit attentions, and send them back to the
10543 	 * initiator.  We only do this when a command initially comes in,
10544 	 * not when we pull it off the blocked queue.
10545 	 *
10546 	 * According to SAM-3, section 5.3.2, the order that things get
10547 	 * presented back to the host is basically unit attentions caused
10548 	 * by some sort of reset event, busy status, reservation conflicts
10549 	 * or task set full, and finally any other status.
10550 	 *
10551 	 * One issue here is that some of the unit attentions we report
10552 	 * don't fall into the "reset" category (e.g. "reported luns data
10553 	 * has changed").  So reporting it here, before the reservation
10554 	 * check, may be technically wrong.  I guess the only thing to do
10555 	 * would be to check for and report the reset events here, and then
10556 	 * check for the other unit attention types after we check for a
10557 	 * reservation conflict.
10558 	 *
10559 	 * XXX KDM need to fix this
10560 	 */
10561 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
10562 		ctl_ua_type ua_type;
10563 
10564 		ua_type = lun->pending_sense[initidx].ua_pending;
10565 		if (ua_type != CTL_UA_NONE) {
10566 			scsi_sense_data_type sense_format;
10567 
10568 			if (lun != NULL)
10569 				sense_format = (lun->flags &
10570 				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
10571 				    SSD_TYPE_FIXED;
10572 			else
10573 				sense_format = SSD_TYPE_FIXED;
10574 
10575 			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
10576 					       sense_format);
10577 			if (ua_type != CTL_UA_NONE) {
10578 				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
10579 				ctsio->io_hdr.status = CTL_SCSI_ERROR |
10580 						       CTL_AUTOSENSE;
10581 				ctsio->sense_len = SSD_FULL_SIZE;
10582 				lun->pending_sense[initidx].ua_pending &=
10583 					~ua_type;
10584 				mtx_unlock(&ctl_softc->ctl_lock);
10585 				ctl_done((union ctl_io *)ctsio);
10586 				goto bailout;
10587 			}
10588 		}
10589 	}
10590 
10591 
10592 	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
10593 		mtx_unlock(&ctl_softc->ctl_lock);
10594 		ctl_done((union ctl_io *)ctsio);
10595 		goto bailout;
10596 	}
10597 
10598 	/*
10599 	 * XXX CHD this is where we want to send IO to other side if
10600 	 * this LUN is secondary on this SC. We will need to make a copy
10601 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
10602 	 * the copy we send as FROM_OTHER.
10603 	 * We also need to stuff the address of the original IO so we can
10604 	 * find it easily. Something similar will need be done on the other
10605 	 * side so when we are done we can find the copy.
10606 	 */
10607 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10608 		union ctl_ha_msg msg_info;
10609 		int isc_retval;
10610 
10611 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
10612 
10613 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
10614 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
10615 #if 0
10616 		printf("1. ctsio %p\n", ctsio);
10617 #endif
10618 		msg_info.hdr.serializing_sc = NULL;
10619 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
10620 		msg_info.scsi.tag_num = ctsio->tag_num;
10621 		msg_info.scsi.tag_type = ctsio->tag_type;
10622 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
10623 
10624 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10625 
10626 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10627 		    (void *)&msg_info, sizeof(msg_info), 0)) >
10628 		    CTL_HA_STATUS_SUCCESS) {
10629 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
10630 			       isc_retval);
10631 			printf("CTL:opcode is %x\n",opcode);
10632 		} else {
10633 #if 0
10634 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
10635 #endif
10636 		}
10637 
10638 		/*
10639 		 * XXX KDM this I/O is off the incoming queue, but hasn't
10640 		 * been inserted on any other queue.  We may need to come
10641 		 * up with a holding queue while we wait for serialization
10642 		 * so that we have an idea of what we're waiting for from
10643 		 * the other side.
10644 		 */
10645 		goto bailout_unlock;
10646 	}
10647 
10648 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
10649 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
10650 			      ctl_ooaq, ooa_links))) {
10651 	case CTL_ACTION_BLOCK:
10652 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
10653 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
10654 				  blocked_links);
10655 		goto bailout_unlock;
10656 		break; /* NOTREACHED */
10657 	case CTL_ACTION_PASS:
10658 	case CTL_ACTION_SKIP:
10659 		goto queue_rtr;
10660 		break; /* NOTREACHED */
10661 	case CTL_ACTION_OVERLAP:
10662 		ctl_set_overlapped_cmd(ctsio);
10663 		mtx_unlock(&ctl_softc->ctl_lock);
10664 		ctl_done((union ctl_io *)ctsio);
10665 		goto bailout;
10666 		break; /* NOTREACHED */
10667 	case CTL_ACTION_OVERLAP_TAG:
10668 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
10669 		mtx_unlock(&ctl_softc->ctl_lock);
10670 		ctl_done((union ctl_io *)ctsio);
10671 		goto bailout;
10672 		break; /* NOTREACHED */
10673 	case CTL_ACTION_ERROR:
10674 	default:
10675 		ctl_set_internal_failure(ctsio,
10676 					 /*sks_valid*/ 0,
10677 					 /*retry_count*/ 0);
10678 		mtx_unlock(&ctl_softc->ctl_lock);
10679 		ctl_done((union ctl_io *)ctsio);
10680 		goto bailout;
10681 		break; /* NOTREACHED */
10682 	}
10683 
10684 	goto bailout_unlock;
10685 
10686 queue_rtr:
10687 	ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
10688 	STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue, &ctsio->io_hdr, links);
10689 
10690 bailout_unlock:
10691 	mtx_unlock(&ctl_softc->ctl_lock);
10692 
10693 bailout:
10694 	return (retval);
10695 }
10696 
10697 static int
10698 ctl_scsiio(struct ctl_scsiio *ctsio)
10699 {
10700 	int retval;
10701 	struct ctl_cmd_entry *entry;
10702 
10703 	retval = CTL_RETVAL_COMPLETE;
10704 
10705 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
10706 
10707 	entry = &ctl_cmd_table[ctsio->cdb[0]];
10708 
10709 	/*
10710 	 * If this I/O has been aborted, just send it straight to
10711 	 * ctl_done() without executing it.
10712 	 */
10713 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
10714 		ctl_done((union ctl_io *)ctsio);
10715 		goto bailout;
10716 	}
10717 
10718 	/*
10719 	 * All the checks should have been handled by ctl_scsiio_precheck().
10720 	 * We should be clear now to just execute the I/O.
10721 	 */
10722 	retval = entry->execute(ctsio);
10723 
10724 bailout:
10725 	return (retval);
10726 }
10727 
10728 /*
10729  * Since we only implement one target right now, a bus reset simply resets
10730  * our single target.
10731  */
10732 static int
10733 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
10734 {
10735 	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
10736 }
10737 
10738 static int
10739 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
10740 		 ctl_ua_type ua_type)
10741 {
10742 	struct ctl_lun *lun;
10743 	int retval;
10744 
10745 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
10746 		union ctl_ha_msg msg_info;
10747 
10748 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
10749 		msg_info.hdr.nexus = io->io_hdr.nexus;
10750 		if (ua_type==CTL_UA_TARG_RESET)
10751 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
10752 		else
10753 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
10754 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
10755 		msg_info.hdr.original_sc = NULL;
10756 		msg_info.hdr.serializing_sc = NULL;
10757 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10758 		    (void *)&msg_info, sizeof(msg_info), 0)) {
10759 		}
10760 	}
10761 	retval = 0;
10762 
10763 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
10764 		retval += ctl_lun_reset(lun, io, ua_type);
10765 
10766 	return (retval);
10767 }
10768 
10769 /*
10770  * The LUN should always be set.  The I/O is optional, and is used to
10771  * distinguish between I/Os sent by this initiator, and by other
10772  * initiators.  We set unit attention for initiators other than this one.
10773  * SAM-3 is vague on this point.  It does say that a unit attention should
10774  * be established for other initiators when a LUN is reset (see section
10775  * 5.7.3), but it doesn't specifically say that the unit attention should
10776  * be established for this particular initiator when a LUN is reset.  Here
10777  * is the relevant text, from SAM-3 rev 8:
10778  *
10779  * 5.7.2 When a SCSI initiator port aborts its own tasks
10780  *
10781  * When a SCSI initiator port causes its own task(s) to be aborted, no
10782  * notification that the task(s) have been aborted shall be returned to
10783  * the SCSI initiator port other than the completion response for the
10784  * command or task management function action that caused the task(s) to
10785  * be aborted and notification(s) associated with related effects of the
10786  * action (e.g., a reset unit attention condition).
10787  *
10788  * XXX KDM for now, we're setting unit attention for all initiators.
10789  */
10790 static int
10791 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
10792 {
10793 	union ctl_io *xio;
10794 #if 0
10795 	uint32_t initindex;
10796 #endif
10797 	int i;
10798 
10799 	/*
10800 	 * Run through the OOA queue and abort each I/O.
10801 	 */
10802 #if 0
10803 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
10804 #endif
10805 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
10806 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
10807 		xio->io_hdr.flags |= CTL_FLAG_ABORT;
10808 	}
10809 
10810 	/*
10811 	 * This version sets unit attention for every
10812 	 */
10813 #if 0
10814 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
10815 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10816 		if (initindex == i)
10817 			continue;
10818 		lun->pending_sense[i].ua_pending |= ua_type;
10819 	}
10820 #endif
10821 
10822 	/*
10823 	 * A reset (any kind, really) clears reservations established with
10824 	 * RESERVE/RELEASE.  It does not clear reservations established
10825 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
10826 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
10827 	 * reservations made with the RESERVE/RELEASE commands, because
10828 	 * those commands are obsolete in SPC-3.
10829 	 */
10830 	lun->flags &= ~CTL_LUN_RESERVED;
10831 
10832 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10833 		ctl_clear_mask(lun->have_ca, i);
10834 		lun->pending_sense[i].ua_pending |= ua_type;
10835 	}
10836 
10837 	return (0);
10838 }
10839 
10840 static int
10841 ctl_abort_task(union ctl_io *io)
10842 {
10843 	union ctl_io *xio;
10844 	struct ctl_lun *lun;
10845 	struct ctl_softc *ctl_softc;
10846 #if 0
10847 	struct sbuf sb;
10848 	char printbuf[128];
10849 #endif
10850 	int found;
10851 
10852 	ctl_softc = control_softc;
10853 	found = 0;
10854 
10855 	/*
10856 	 * Look up the LUN.
10857 	 */
10858 	if ((io->io_hdr.nexus.targ_lun < CTL_MAX_LUNS)
10859 	 && (ctl_softc->ctl_luns[io->io_hdr.nexus.targ_lun] != NULL))
10860 		lun = ctl_softc->ctl_luns[io->io_hdr.nexus.targ_lun];
10861 	else
10862 		goto bailout;
10863 
10864 #if 0
10865 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
10866 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
10867 #endif
10868 
10869 	/*
10870 	 * Run through the OOA queue and attempt to find the given I/O.
10871 	 * The target port, initiator ID, tag type and tag number have to
10872 	 * match the values that we got from the initiator.  If we have an
10873 	 * untagged command to abort, simply abort the first untagged command
10874 	 * we come to.  We only allow one untagged command at a time of course.
10875 	 */
10876 #if 0
10877 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
10878 #endif
10879 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
10880 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
10881 #if 0
10882 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
10883 
10884 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
10885 			    lun->lun, xio->scsiio.tag_num,
10886 			    xio->scsiio.tag_type,
10887 			    (xio->io_hdr.blocked_links.tqe_prev
10888 			    == NULL) ? "" : " BLOCKED",
10889 			    (xio->io_hdr.flags &
10890 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
10891 			    (xio->io_hdr.flags &
10892 			    CTL_FLAG_ABORT) ? " ABORT" : ""),
10893 			    (xio->io_hdr.flags &
10894 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : "");
10895 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
10896 		sbuf_finish(&sb);
10897 		printf("%s\n", sbuf_data(&sb));
10898 #endif
10899 
10900 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
10901 		 && (xio->io_hdr.nexus.initid.id ==
10902 		     io->io_hdr.nexus.initid.id)) {
10903 			/*
10904 			 * If the abort says that the task is untagged, the
10905 			 * task in the queue must be untagged.  Otherwise,
10906 			 * we just check to see whether the tag numbers
10907 			 * match.  This is because the QLogic firmware
10908 			 * doesn't pass back the tag type in an abort
10909 			 * request.
10910 			 */
10911 #if 0
10912 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
10913 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
10914 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
10915 #endif
10916 			/*
10917 			 * XXX KDM we've got problems with FC, because it
10918 			 * doesn't send down a tag type with aborts.  So we
10919 			 * can only really go by the tag number...
10920 			 * This may cause problems with parallel SCSI.
10921 			 * Need to figure that out!!
10922 			 */
10923 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
10924 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
10925 				found = 1;
10926 				if ((io->io_hdr.flags &
10927 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
10928 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
10929 					union ctl_ha_msg msg_info;
10930 
10931 					io->io_hdr.flags |=
10932 					                CTL_FLAG_SENT_2OTHER_SC;
10933 					msg_info.hdr.nexus = io->io_hdr.nexus;
10934 					msg_info.task.task_action =
10935 						CTL_TASK_ABORT_TASK;
10936 					msg_info.task.tag_num =
10937 						io->taskio.tag_num;
10938 					msg_info.task.tag_type =
10939 						io->taskio.tag_type;
10940 					msg_info.hdr.msg_type =
10941 						CTL_MSG_MANAGE_TASKS;
10942 					msg_info.hdr.original_sc = NULL;
10943 					msg_info.hdr.serializing_sc = NULL;
10944 #if 0
10945 					printf("Sent Abort to other side\n");
10946 #endif
10947 					if (CTL_HA_STATUS_SUCCESS !=
10948 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10949 		    				(void *)&msg_info,
10950 						sizeof(msg_info), 0)) {
10951 					}
10952 				}
10953 #if 0
10954 				printf("ctl_abort_task: found I/O to abort\n");
10955 #endif
10956 				break;
10957 			}
10958 		}
10959 	}
10960 
10961 bailout:
10962 
10963 	if (found == 0) {
10964 		/*
10965 		 * This isn't really an error.  It's entirely possible for
10966 		 * the abort and command completion to cross on the wire.
10967 		 * This is more of an informative/diagnostic error.
10968 		 */
10969 #if 0
10970 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
10971 		       "%d:%d:%d:%d tag %d type %d\n",
10972 		       io->io_hdr.nexus.initid.id,
10973 		       io->io_hdr.nexus.targ_port,
10974 		       io->io_hdr.nexus.targ_target.id,
10975 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
10976 		       io->taskio.tag_type);
10977 #endif
10978 		return (1);
10979 	} else
10980 		return (0);
10981 }
10982 
10983 /*
10984  * Assumptions:  caller holds ctl_softc->ctl_lock
10985  *
10986  * This routine cannot block!  It must be callable from an interrupt
10987  * handler as well as from the work thread.
10988  */
10989 static void
10990 ctl_run_task_queue(struct ctl_softc *ctl_softc)
10991 {
10992 	union ctl_io *io, *next_io;
10993 
10994 	CTL_DEBUG_PRINT(("ctl_run_task_queue\n"));
10995 
10996 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->task_queue);
10997 	     io != NULL; io = next_io) {
10998 		int retval;
10999 		const char *task_desc;
11000 
11001 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11002 
11003 		retval = 0;
11004 
11005 		switch (io->io_hdr.io_type) {
11006 		case CTL_IO_TASK: {
11007 			task_desc = ctl_scsi_task_string(&io->taskio);
11008 			if (task_desc != NULL) {
11009 #ifdef NEEDTOPORT
11010 				csevent_log(CSC_CTL | CSC_SHELF_SW |
11011 					    CTL_TASK_REPORT,
11012 					    csevent_LogType_Trace,
11013 					    csevent_Severity_Information,
11014 					    csevent_AlertLevel_Green,
11015 					    csevent_FRU_Firmware,
11016 					    csevent_FRU_Unknown,
11017 					    "CTL: received task: %s",task_desc);
11018 #endif
11019 			} else {
11020 #ifdef NEEDTOPORT
11021 				csevent_log(CSC_CTL | CSC_SHELF_SW |
11022 					    CTL_TASK_REPORT,
11023 					    csevent_LogType_Trace,
11024 					    csevent_Severity_Information,
11025 					    csevent_AlertLevel_Green,
11026 					    csevent_FRU_Firmware,
11027 					    csevent_FRU_Unknown,
11028 					    "CTL: received unknown task "
11029 					    "type: %d (%#x)",
11030 					    io->taskio.task_action,
11031 					    io->taskio.task_action);
11032 #endif
11033 			}
11034 			switch (io->taskio.task_action) {
11035 			case CTL_TASK_ABORT_TASK:
11036 				retval = ctl_abort_task(io);
11037 				break;
11038 			case CTL_TASK_ABORT_TASK_SET:
11039 				break;
11040 			case CTL_TASK_CLEAR_ACA:
11041 				break;
11042 			case CTL_TASK_CLEAR_TASK_SET:
11043 				break;
11044 			case CTL_TASK_LUN_RESET: {
11045 				struct ctl_lun *lun;
11046 				uint32_t targ_lun;
11047 				int retval;
11048 
11049 				targ_lun = io->io_hdr.nexus.targ_lun;
11050 
11051 				if ((targ_lun < CTL_MAX_LUNS)
11052 				 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11053 					lun = ctl_softc->ctl_luns[targ_lun];
11054 				else {
11055 					retval = 1;
11056 					break;
11057 				}
11058 
11059 				if (!(io->io_hdr.flags &
11060 				    CTL_FLAG_FROM_OTHER_SC)) {
11061 					union ctl_ha_msg msg_info;
11062 
11063 					io->io_hdr.flags |=
11064 						CTL_FLAG_SENT_2OTHER_SC;
11065 					msg_info.hdr.msg_type =
11066 						CTL_MSG_MANAGE_TASKS;
11067 					msg_info.hdr.nexus = io->io_hdr.nexus;
11068 					msg_info.task.task_action =
11069 						CTL_TASK_LUN_RESET;
11070 					msg_info.hdr.original_sc = NULL;
11071 					msg_info.hdr.serializing_sc = NULL;
11072 					if (CTL_HA_STATUS_SUCCESS !=
11073 					    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11074 					    (void *)&msg_info,
11075 					    sizeof(msg_info), 0)) {
11076 					}
11077 				}
11078 
11079 				retval = ctl_lun_reset(lun, io,
11080 						       CTL_UA_LUN_RESET);
11081 				break;
11082 			}
11083 			case CTL_TASK_TARGET_RESET:
11084 				retval = ctl_target_reset(ctl_softc, io,
11085 							  CTL_UA_TARG_RESET);
11086 				break;
11087 			case CTL_TASK_BUS_RESET:
11088 				retval = ctl_bus_reset(ctl_softc, io);
11089 				break;
11090 			case CTL_TASK_PORT_LOGIN:
11091 				break;
11092 			case CTL_TASK_PORT_LOGOUT:
11093 				break;
11094 			default:
11095 				printf("ctl_run_task_queue: got unknown task "
11096 				       "management event %d\n",
11097 				       io->taskio.task_action);
11098 				break;
11099 			}
11100 			if (retval == 0)
11101 				io->io_hdr.status = CTL_SUCCESS;
11102 			else
11103 				io->io_hdr.status = CTL_ERROR;
11104 
11105 			STAILQ_REMOVE(&ctl_softc->task_queue, &io->io_hdr,
11106 				      ctl_io_hdr, links);
11107 			/*
11108 			 * This will queue this I/O to the done queue, but the
11109 			 * work thread won't be able to process it until we
11110 			 * return and the lock is released.
11111 			 */
11112 			ctl_done_lock(io, /*have_lock*/ 1);
11113 			break;
11114 		}
11115 		default: {
11116 
11117 			printf("%s: invalid I/O type %d msg %d cdb %x"
11118 			       " iptl: %ju:%d:%ju:%d tag 0x%04x\n",
11119 			       __func__, io->io_hdr.io_type,
11120 			       io->io_hdr.msg_type, io->scsiio.cdb[0],
11121 			       (uintmax_t)io->io_hdr.nexus.initid.id,
11122 			       io->io_hdr.nexus.targ_port,
11123 			       (uintmax_t)io->io_hdr.nexus.targ_target.id,
11124 			       io->io_hdr.nexus.targ_lun,
11125 			       (io->io_hdr.io_type == CTL_IO_TASK) ?
11126 			       io->taskio.tag_num : io->scsiio.tag_num);
11127 			STAILQ_REMOVE(&ctl_softc->task_queue, &io->io_hdr,
11128 				      ctl_io_hdr, links);
11129 			ctl_free_io_internal(io, 1);
11130 			break;
11131 		}
11132 		}
11133 	}
11134 
11135 	ctl_softc->flags &= ~CTL_FLAG_TASK_PENDING;
11136 }
11137 
11138 /*
11139  * For HA operation.  Handle commands that come in from the other
11140  * controller.
11141  */
11142 static void
11143 ctl_handle_isc(union ctl_io *io)
11144 {
11145 	int free_io;
11146 	struct ctl_lun *lun;
11147 	struct ctl_softc *ctl_softc;
11148 
11149 	ctl_softc = control_softc;
11150 
11151 	lun = ctl_softc->ctl_luns[io->io_hdr.nexus.targ_lun];
11152 
11153 	switch (io->io_hdr.msg_type) {
11154 	case CTL_MSG_SERIALIZE:
11155 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio,
11156 						     /*have_lock*/ 0);
11157 		break;
11158 	case CTL_MSG_R2R: {
11159 		uint8_t opcode;
11160 		struct ctl_cmd_entry *entry;
11161 
11162 		/*
11163 		 * This is only used in SER_ONLY mode.
11164 		 */
11165 		free_io = 0;
11166 		opcode = io->scsiio.cdb[0];
11167 		entry = &ctl_cmd_table[opcode];
11168 		mtx_lock(&ctl_softc->ctl_lock);
11169 		if (ctl_scsiio_lun_check(ctl_softc, lun,
11170 		    entry, (struct ctl_scsiio *)io) != 0) {
11171 			ctl_done_lock(io, /*have_lock*/ 1);
11172 			mtx_unlock(&ctl_softc->ctl_lock);
11173 			break;
11174 		}
11175 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11176 		STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
11177 				   &io->io_hdr, links);
11178 		mtx_unlock(&ctl_softc->ctl_lock);
11179 		break;
11180 	}
11181 	case CTL_MSG_FINISH_IO:
11182 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
11183 			free_io = 0;
11184 			ctl_done_lock(io, /*have_lock*/ 0);
11185 		} else {
11186 			free_io = 1;
11187 			mtx_lock(&ctl_softc->ctl_lock);
11188 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11189 				     ooa_links);
11190 			STAILQ_REMOVE(&ctl_softc->task_queue,
11191 				      &io->io_hdr, ctl_io_hdr, links);
11192 			ctl_check_blocked(lun);
11193 			mtx_unlock(&ctl_softc->ctl_lock);
11194 		}
11195 		break;
11196 	case CTL_MSG_PERS_ACTION:
11197 		ctl_hndl_per_res_out_on_other_sc(
11198 			(union ctl_ha_msg *)&io->presio.pr_msg);
11199 		free_io = 1;
11200 		break;
11201 	case CTL_MSG_BAD_JUJU:
11202 		free_io = 0;
11203 		ctl_done_lock(io, /*have_lock*/ 0);
11204 		break;
11205 	case CTL_MSG_DATAMOVE:
11206 		/* Only used in XFER mode */
11207 		free_io = 0;
11208 		ctl_datamove_remote(io);
11209 		break;
11210 	case CTL_MSG_DATAMOVE_DONE:
11211 		/* Only used in XFER mode */
11212 		free_io = 0;
11213 		io->scsiio.be_move_done(io);
11214 		break;
11215 	default:
11216 		free_io = 1;
11217 		printf("%s: Invalid message type %d\n",
11218 		       __func__, io->io_hdr.msg_type);
11219 		break;
11220 	}
11221 	if (free_io)
11222 		ctl_free_io_internal(io, 0);
11223 
11224 }
11225 
11226 
11227 /*
11228  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11229  * there is no match.
11230  */
11231 static ctl_lun_error_pattern
11232 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11233 {
11234 	struct ctl_cmd_entry *entry;
11235 	ctl_lun_error_pattern filtered_pattern, pattern;
11236 	uint8_t opcode;
11237 
11238 	pattern = desc->error_pattern;
11239 
11240 	/*
11241 	 * XXX KDM we need more data passed into this function to match a
11242 	 * custom pattern, and we actually need to implement custom pattern
11243 	 * matching.
11244 	 */
11245 	if (pattern & CTL_LUN_PAT_CMD)
11246 		return (CTL_LUN_PAT_CMD);
11247 
11248 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11249 		return (CTL_LUN_PAT_ANY);
11250 
11251 	opcode = ctsio->cdb[0];
11252 	entry = &ctl_cmd_table[opcode];
11253 
11254 	filtered_pattern = entry->pattern & pattern;
11255 
11256 	/*
11257 	 * If the user requested specific flags in the pattern (e.g.
11258 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11259 	 * flags.
11260 	 *
11261 	 * If the user did not specify any flags, it doesn't matter whether
11262 	 * or not the command supports the flags.
11263 	 */
11264 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11265 	     (pattern & ~CTL_LUN_PAT_MASK))
11266 		return (CTL_LUN_PAT_NONE);
11267 
11268 	/*
11269 	 * If the user asked for a range check, see if the requested LBA
11270 	 * range overlaps with this command's LBA range.
11271 	 */
11272 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
11273 		uint64_t lba1;
11274 		uint32_t len1;
11275 		ctl_action action;
11276 		int retval;
11277 
11278 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
11279 		if (retval != 0)
11280 			return (CTL_LUN_PAT_NONE);
11281 
11282 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
11283 					      desc->lba_range.len);
11284 		/*
11285 		 * A "pass" means that the LBA ranges don't overlap, so
11286 		 * this doesn't match the user's range criteria.
11287 		 */
11288 		if (action == CTL_ACTION_PASS)
11289 			return (CTL_LUN_PAT_NONE);
11290 	}
11291 
11292 	return (filtered_pattern);
11293 }
11294 
11295 /*
11296  * Called with the CTL lock held.
11297  */
11298 static void
11299 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
11300 {
11301 	struct ctl_error_desc *desc, *desc2;
11302 
11303 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
11304 		ctl_lun_error_pattern pattern;
11305 		/*
11306 		 * Check to see whether this particular command matches
11307 		 * the pattern in the descriptor.
11308 		 */
11309 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
11310 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
11311 			continue;
11312 
11313 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
11314 		case CTL_LUN_INJ_ABORTED:
11315 			ctl_set_aborted(&io->scsiio);
11316 			break;
11317 		case CTL_LUN_INJ_MEDIUM_ERR:
11318 			ctl_set_medium_error(&io->scsiio);
11319 			break;
11320 		case CTL_LUN_INJ_UA:
11321 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
11322 			 * OCCURRED */
11323 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
11324 			break;
11325 		case CTL_LUN_INJ_CUSTOM:
11326 			/*
11327 			 * We're assuming the user knows what he is doing.
11328 			 * Just copy the sense information without doing
11329 			 * checks.
11330 			 */
11331 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
11332 			      ctl_min(sizeof(desc->custom_sense),
11333 				      sizeof(io->scsiio.sense_data)));
11334 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
11335 			io->scsiio.sense_len = SSD_FULL_SIZE;
11336 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11337 			break;
11338 		case CTL_LUN_INJ_NONE:
11339 		default:
11340 			/*
11341 			 * If this is an error injection type we don't know
11342 			 * about, clear the continuous flag (if it is set)
11343 			 * so it will get deleted below.
11344 			 */
11345 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
11346 			break;
11347 		}
11348 		/*
11349 		 * By default, each error injection action is a one-shot
11350 		 */
11351 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
11352 			continue;
11353 
11354 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
11355 
11356 		free(desc, M_CTL);
11357 	}
11358 }
11359 
11360 #ifdef CTL_IO_DELAY
11361 static void
11362 ctl_datamove_timer_wakeup(void *arg)
11363 {
11364 	union ctl_io *io;
11365 
11366 	io = (union ctl_io *)arg;
11367 
11368 	ctl_datamove(io);
11369 }
11370 #endif /* CTL_IO_DELAY */
11371 
11372 /*
11373  * Assumption:  caller does NOT hold ctl_lock
11374  */
11375 void
11376 ctl_datamove(union ctl_io *io)
11377 {
11378 	void (*fe_datamove)(union ctl_io *io);
11379 
11380 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
11381 
11382 #ifdef CTL_TIME_IO
11383 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
11384 		char str[256];
11385 		char path_str[64];
11386 		struct sbuf sb;
11387 
11388 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
11389 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
11390 
11391 		sbuf_cat(&sb, path_str);
11392 		switch (io->io_hdr.io_type) {
11393 		case CTL_IO_SCSI:
11394 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
11395 			sbuf_printf(&sb, "\n");
11396 			sbuf_cat(&sb, path_str);
11397 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
11398 				    io->scsiio.tag_num, io->scsiio.tag_type);
11399 			break;
11400 		case CTL_IO_TASK:
11401 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
11402 				    "Tag Type: %d\n", io->taskio.task_action,
11403 				    io->taskio.tag_num, io->taskio.tag_type);
11404 			break;
11405 		default:
11406 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11407 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11408 			break;
11409 		}
11410 		sbuf_cat(&sb, path_str);
11411 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
11412 			    (intmax_t)time_uptime - io->io_hdr.start_time);
11413 		sbuf_finish(&sb);
11414 		printf("%s", sbuf_data(&sb));
11415 	}
11416 #endif /* CTL_TIME_IO */
11417 
11418 	mtx_lock(&control_softc->ctl_lock);
11419 #ifdef CTL_IO_DELAY
11420 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
11421 		struct ctl_lun *lun;
11422 
11423 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
11424 
11425 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
11426 	} else {
11427 		struct ctl_lun *lun;
11428 
11429 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
11430 		if ((lun != NULL)
11431 		 && (lun->delay_info.datamove_delay > 0)) {
11432 			struct callout *callout;
11433 
11434 			callout = (struct callout *)&io->io_hdr.timer_bytes;
11435 			callout_init(callout, /*mpsafe*/ 1);
11436 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
11437 			callout_reset(callout,
11438 				      lun->delay_info.datamove_delay * hz,
11439 				      ctl_datamove_timer_wakeup, io);
11440 			if (lun->delay_info.datamove_type ==
11441 			    CTL_DELAY_TYPE_ONESHOT)
11442 				lun->delay_info.datamove_delay = 0;
11443 			mtx_unlock(&control_softc->ctl_lock);
11444 			return;
11445 		}
11446 	}
11447 #endif
11448 	/*
11449 	 * If we have any pending task management commands, process them
11450 	 * first.  This is necessary to eliminate a race condition with the
11451 	 * FETD:
11452 	 *
11453 	 * - FETD submits a task management command, like an abort.
11454 	 * - Back end calls fe_datamove() to move the data for the aborted
11455 	 *   command.  The FETD can't really accept it, but if it did, it
11456 	 *   would end up transmitting data for a command that the initiator
11457 	 *   told us to abort.
11458 	 *
11459 	 * We close the race by processing all pending task management
11460 	 * commands here (we can't block!), and then check this I/O to see
11461 	 * if it has been aborted.  If so, return it to the back end with
11462 	 * bad status, so the back end can say return an error to the back end
11463 	 * and then when the back end returns an error, we can return the
11464 	 * aborted command to the FETD, so it can clean up its resources.
11465 	 */
11466 	if (control_softc->flags & CTL_FLAG_TASK_PENDING)
11467 		ctl_run_task_queue(control_softc);
11468 
11469 	/*
11470 	 * This command has been aborted.  Set the port status, so we fail
11471 	 * the data move.
11472 	 */
11473 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
11474 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
11475 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
11476 		       io->io_hdr.nexus.targ_port,
11477 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
11478 		       io->io_hdr.nexus.targ_lun);
11479 		io->io_hdr.status = CTL_CMD_ABORTED;
11480 		io->io_hdr.port_status = 31337;
11481 		mtx_unlock(&control_softc->ctl_lock);
11482 		/*
11483 		 * Note that the backend, in this case, will get the
11484 		 * callback in its context.  In other cases it may get
11485 		 * called in the frontend's interrupt thread context.
11486 		 */
11487 		io->scsiio.be_move_done(io);
11488 		return;
11489 	}
11490 
11491 	/*
11492 	 * If we're in XFER mode and this I/O is from the other shelf
11493 	 * controller, we need to send the DMA to the other side to
11494 	 * actually transfer the data to/from the host.  In serialize only
11495 	 * mode the transfer happens below CTL and ctl_datamove() is only
11496 	 * called on the machine that originally received the I/O.
11497 	 */
11498 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
11499 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11500 		union ctl_ha_msg msg;
11501 		uint32_t sg_entries_sent;
11502 		int do_sg_copy;
11503 		int i;
11504 
11505 		memset(&msg, 0, sizeof(msg));
11506 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
11507 		msg.hdr.original_sc = io->io_hdr.original_sc;
11508 		msg.hdr.serializing_sc = io;
11509 		msg.hdr.nexus = io->io_hdr.nexus;
11510 		msg.dt.flags = io->io_hdr.flags;
11511 		/*
11512 		 * We convert everything into a S/G list here.  We can't
11513 		 * pass by reference, only by value between controllers.
11514 		 * So we can't pass a pointer to the S/G list, only as many
11515 		 * S/G entries as we can fit in here.  If it's possible for
11516 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
11517 		 * then we need to break this up into multiple transfers.
11518 		 */
11519 		if (io->scsiio.kern_sg_entries == 0) {
11520 			msg.dt.kern_sg_entries = 1;
11521 			/*
11522 			 * If this is in cached memory, flush the cache
11523 			 * before we send the DMA request to the other
11524 			 * controller.  We want to do this in either the
11525 			 * read or the write case.  The read case is
11526 			 * straightforward.  In the write case, we want to
11527 			 * make sure nothing is in the local cache that
11528 			 * could overwrite the DMAed data.
11529 			 */
11530 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
11531 				/*
11532 				 * XXX KDM use bus_dmamap_sync() here.
11533 				 */
11534 			}
11535 
11536 			/*
11537 			 * Convert to a physical address if this is a
11538 			 * virtual address.
11539 			 */
11540 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
11541 				msg.dt.sg_list[0].addr =
11542 					io->scsiio.kern_data_ptr;
11543 			} else {
11544 				/*
11545 				 * XXX KDM use busdma here!
11546 				 */
11547 #if 0
11548 				msg.dt.sg_list[0].addr = (void *)
11549 					vtophys(io->scsiio.kern_data_ptr);
11550 #endif
11551 			}
11552 
11553 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
11554 			do_sg_copy = 0;
11555 		} else {
11556 			struct ctl_sg_entry *sgl;
11557 
11558 			do_sg_copy = 1;
11559 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
11560 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
11561 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
11562 				/*
11563 				 * XXX KDM use bus_dmamap_sync() here.
11564 				 */
11565 			}
11566 		}
11567 
11568 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
11569 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
11570 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
11571 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
11572 		msg.dt.sg_sequence = 0;
11573 
11574 		/*
11575 		 * Loop until we've sent all of the S/G entries.  On the
11576 		 * other end, we'll recompose these S/G entries into one
11577 		 * contiguous list before passing it to the
11578 		 */
11579 		for (sg_entries_sent = 0; sg_entries_sent <
11580 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
11581 			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
11582 				sizeof(msg.dt.sg_list[0])),
11583 				msg.dt.kern_sg_entries - sg_entries_sent);
11584 
11585 			if (do_sg_copy != 0) {
11586 				struct ctl_sg_entry *sgl;
11587 				int j;
11588 
11589 				sgl = (struct ctl_sg_entry *)
11590 					io->scsiio.kern_data_ptr;
11591 				/*
11592 				 * If this is in cached memory, flush the cache
11593 				 * before we send the DMA request to the other
11594 				 * controller.  We want to do this in either
11595 				 * the * read or the write case.  The read
11596 				 * case is straightforward.  In the write
11597 				 * case, we want to make sure nothing is
11598 				 * in the local cache that could overwrite
11599 				 * the DMAed data.
11600 				 */
11601 
11602 				for (i = sg_entries_sent, j = 0;
11603 				     i < msg.dt.cur_sg_entries; i++, j++) {
11604 					if ((io->io_hdr.flags &
11605 					     CTL_FLAG_NO_DATASYNC) == 0) {
11606 						/*
11607 						 * XXX KDM use bus_dmamap_sync()
11608 						 */
11609 					}
11610 					if ((io->io_hdr.flags &
11611 					     CTL_FLAG_BUS_ADDR) == 0) {
11612 						/*
11613 						 * XXX KDM use busdma.
11614 						 */
11615 #if 0
11616 						msg.dt.sg_list[j].addr =(void *)
11617 						       vtophys(sgl[i].addr);
11618 #endif
11619 					} else {
11620 						msg.dt.sg_list[j].addr =
11621 							sgl[i].addr;
11622 					}
11623 					msg.dt.sg_list[j].len = sgl[i].len;
11624 				}
11625 			}
11626 
11627 			sg_entries_sent += msg.dt.cur_sg_entries;
11628 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
11629 				msg.dt.sg_last = 1;
11630 			else
11631 				msg.dt.sg_last = 0;
11632 
11633 			/*
11634 			 * XXX KDM drop and reacquire the lock here?
11635 			 */
11636 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
11637 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
11638 				/*
11639 				 * XXX do something here.
11640 				 */
11641 			}
11642 
11643 			msg.dt.sent_sg_entries = sg_entries_sent;
11644 		}
11645 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11646 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
11647 			ctl_failover_io(io, /*have_lock*/ 1);
11648 
11649 	} else {
11650 
11651 		/*
11652 		 * Lookup the fe_datamove() function for this particular
11653 		 * front end.
11654 		 */
11655 		fe_datamove =
11656 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
11657 		mtx_unlock(&control_softc->ctl_lock);
11658 
11659 		fe_datamove(io);
11660 	}
11661 }
11662 
11663 static void
11664 ctl_send_datamove_done(union ctl_io *io, int have_lock)
11665 {
11666 	union ctl_ha_msg msg;
11667 	int isc_status;
11668 
11669 	memset(&msg, 0, sizeof(msg));
11670 
11671 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
11672 	msg.hdr.original_sc = io;
11673 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
11674 	msg.hdr.nexus = io->io_hdr.nexus;
11675 	msg.hdr.status = io->io_hdr.status;
11676 	msg.scsi.tag_num = io->scsiio.tag_num;
11677 	msg.scsi.tag_type = io->scsiio.tag_type;
11678 	msg.scsi.scsi_status = io->scsiio.scsi_status;
11679 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
11680 	       sizeof(io->scsiio.sense_data));
11681 	msg.scsi.sense_len = io->scsiio.sense_len;
11682 	msg.scsi.sense_residual = io->scsiio.sense_residual;
11683 	msg.scsi.fetd_status = io->io_hdr.port_status;
11684 	msg.scsi.residual = io->scsiio.residual;
11685 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11686 
11687 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
11688 		ctl_failover_io(io, /*have_lock*/ have_lock);
11689 		return;
11690 	}
11691 
11692 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
11693 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
11694 		/* XXX do something if this fails */
11695 	}
11696 
11697 }
11698 
11699 /*
11700  * The DMA to the remote side is done, now we need to tell the other side
11701  * we're done so it can continue with its data movement.
11702  */
11703 static void
11704 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
11705 {
11706 	union ctl_io *io;
11707 
11708 	io = rq->context;
11709 
11710 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
11711 		printf("%s: ISC DMA write failed with error %d", __func__,
11712 		       rq->ret);
11713 		ctl_set_internal_failure(&io->scsiio,
11714 					 /*sks_valid*/ 1,
11715 					 /*retry_count*/ rq->ret);
11716 	}
11717 
11718 	ctl_dt_req_free(rq);
11719 
11720 	/*
11721 	 * In this case, we had to malloc the memory locally.  Free it.
11722 	 */
11723 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
11724 		int i;
11725 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
11726 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
11727 	}
11728 	/*
11729 	 * The data is in local and remote memory, so now we need to send
11730 	 * status (good or back) back to the other side.
11731 	 */
11732 	ctl_send_datamove_done(io, /*have_lock*/ 0);
11733 }
11734 
11735 /*
11736  * We've moved the data from the host/controller into local memory.  Now we
11737  * need to push it over to the remote controller's memory.
11738  */
11739 static int
11740 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
11741 {
11742 	int retval;
11743 
11744 	retval = 0;
11745 
11746 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
11747 					  ctl_datamove_remote_write_cb);
11748 
11749 	return (retval);
11750 }
11751 
11752 static void
11753 ctl_datamove_remote_write(union ctl_io *io)
11754 {
11755 	int retval;
11756 	void (*fe_datamove)(union ctl_io *io);
11757 
11758 	/*
11759 	 * - Get the data from the host/HBA into local memory.
11760 	 * - DMA memory from the local controller to the remote controller.
11761 	 * - Send status back to the remote controller.
11762 	 */
11763 
11764 	retval = ctl_datamove_remote_sgl_setup(io);
11765 	if (retval != 0)
11766 		return;
11767 
11768 	/* Switch the pointer over so the FETD knows what to do */
11769 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
11770 
11771 	/*
11772 	 * Use a custom move done callback, since we need to send completion
11773 	 * back to the other controller, not to the backend on this side.
11774 	 */
11775 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
11776 
11777 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
11778 
11779 	fe_datamove(io);
11780 
11781 	return;
11782 
11783 }
11784 
11785 static int
11786 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
11787 {
11788 #if 0
11789 	char str[256];
11790 	char path_str[64];
11791 	struct sbuf sb;
11792 #endif
11793 
11794 	/*
11795 	 * In this case, we had to malloc the memory locally.  Free it.
11796 	 */
11797 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
11798 		int i;
11799 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
11800 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
11801 	}
11802 
11803 #if 0
11804 	scsi_path_string(io, path_str, sizeof(path_str));
11805 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
11806 	sbuf_cat(&sb, path_str);
11807 	scsi_command_string(&io->scsiio, NULL, &sb);
11808 	sbuf_printf(&sb, "\n");
11809 	sbuf_cat(&sb, path_str);
11810 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
11811 		    io->scsiio.tag_num, io->scsiio.tag_type);
11812 	sbuf_cat(&sb, path_str);
11813 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
11814 		    io->io_hdr.flags, io->io_hdr.status);
11815 	sbuf_finish(&sb);
11816 	printk("%s", sbuf_data(&sb));
11817 #endif
11818 
11819 
11820 	/*
11821 	 * The read is done, now we need to send status (good or bad) back
11822 	 * to the other side.
11823 	 */
11824 	ctl_send_datamove_done(io, /*have_lock*/ 0);
11825 
11826 	return (0);
11827 }
11828 
11829 static void
11830 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
11831 {
11832 	union ctl_io *io;
11833 	void (*fe_datamove)(union ctl_io *io);
11834 
11835 	io = rq->context;
11836 
11837 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
11838 		printf("%s: ISC DMA read failed with error %d", __func__,
11839 		       rq->ret);
11840 		ctl_set_internal_failure(&io->scsiio,
11841 					 /*sks_valid*/ 1,
11842 					 /*retry_count*/ rq->ret);
11843 	}
11844 
11845 	ctl_dt_req_free(rq);
11846 
11847 	/* Switch the pointer over so the FETD knows what to do */
11848 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
11849 
11850 	/*
11851 	 * Use a custom move done callback, since we need to send completion
11852 	 * back to the other controller, not to the backend on this side.
11853 	 */
11854 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
11855 
11856 	/* XXX KDM add checks like the ones in ctl_datamove? */
11857 
11858 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
11859 
11860 	fe_datamove(io);
11861 }
11862 
11863 static int
11864 ctl_datamove_remote_sgl_setup(union ctl_io *io)
11865 {
11866 	struct ctl_sg_entry *local_sglist, *remote_sglist;
11867 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
11868 	struct ctl_softc *softc;
11869 	int retval;
11870 	int i;
11871 
11872 	retval = 0;
11873 	softc = control_softc;
11874 
11875 	local_sglist = io->io_hdr.local_sglist;
11876 	local_dma_sglist = io->io_hdr.local_dma_sglist;
11877 	remote_sglist = io->io_hdr.remote_sglist;
11878 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
11879 
11880 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
11881 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
11882 			local_sglist[i].len = remote_sglist[i].len;
11883 
11884 			/*
11885 			 * XXX Detect the situation where the RS-level I/O
11886 			 * redirector on the other side has already read the
11887 			 * data off of the AOR RS on this side, and
11888 			 * transferred it to remote (mirror) memory on the
11889 			 * other side.  Since we already have the data in
11890 			 * memory here, we just need to use it.
11891 			 *
11892 			 * XXX KDM this can probably be removed once we
11893 			 * get the cache device code in and take the
11894 			 * current AOR implementation out.
11895 			 */
11896 #ifdef NEEDTOPORT
11897 			if ((remote_sglist[i].addr >=
11898 			     (void *)vtophys(softc->mirr->addr))
11899 			 && (remote_sglist[i].addr <
11900 			     ((void *)vtophys(softc->mirr->addr) +
11901 			     CacheMirrorOffset))) {
11902 				local_sglist[i].addr = remote_sglist[i].addr -
11903 					CacheMirrorOffset;
11904 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
11905 				     CTL_FLAG_DATA_IN)
11906 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
11907 			} else {
11908 				local_sglist[i].addr = remote_sglist[i].addr +
11909 					CacheMirrorOffset;
11910 			}
11911 #endif
11912 #if 0
11913 			printf("%s: local %p, remote %p, len %d\n",
11914 			       __func__, local_sglist[i].addr,
11915 			       remote_sglist[i].addr, local_sglist[i].len);
11916 #endif
11917 		}
11918 	} else {
11919 		uint32_t len_to_go;
11920 
11921 		/*
11922 		 * In this case, we don't have automatically allocated
11923 		 * memory for this I/O on this controller.  This typically
11924 		 * happens with internal CTL I/O -- e.g. inquiry, mode
11925 		 * sense, etc.  Anything coming from RAIDCore will have
11926 		 * a mirror area available.
11927 		 */
11928 		len_to_go = io->scsiio.kern_data_len;
11929 
11930 		/*
11931 		 * Clear the no datasync flag, we have to use malloced
11932 		 * buffers.
11933 		 */
11934 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
11935 
11936 		/*
11937 		 * The difficult thing here is that the size of the various
11938 		 * S/G segments may be different than the size from the
11939 		 * remote controller.  That'll make it harder when DMAing
11940 		 * the data back to the other side.
11941 		 */
11942 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
11943 		     sizeof(io->io_hdr.remote_sglist[0])) &&
11944 		     (len_to_go > 0); i++) {
11945 			local_sglist[i].len = ctl_min(len_to_go, 131072);
11946 			CTL_SIZE_8B(local_dma_sglist[i].len,
11947 				    local_sglist[i].len);
11948 			local_sglist[i].addr =
11949 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
11950 
11951 			local_dma_sglist[i].addr = local_sglist[i].addr;
11952 
11953 			if (local_sglist[i].addr == NULL) {
11954 				int j;
11955 
11956 				printf("malloc failed for %zd bytes!",
11957 				       local_dma_sglist[i].len);
11958 				for (j = 0; j < i; j++) {
11959 					free(local_sglist[j].addr, M_CTL);
11960 				}
11961 				ctl_set_internal_failure(&io->scsiio,
11962 							 /*sks_valid*/ 1,
11963 							 /*retry_count*/ 4857);
11964 				retval = 1;
11965 				goto bailout_error;
11966 
11967 			}
11968 			/* XXX KDM do we need a sync here? */
11969 
11970 			len_to_go -= local_sglist[i].len;
11971 		}
11972 		/*
11973 		 * Reset the number of S/G entries accordingly.  The
11974 		 * original number of S/G entries is available in
11975 		 * rem_sg_entries.
11976 		 */
11977 		io->scsiio.kern_sg_entries = i;
11978 
11979 #if 0
11980 		printf("%s: kern_sg_entries = %d\n", __func__,
11981 		       io->scsiio.kern_sg_entries);
11982 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
11983 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
11984 			       local_sglist[i].addr, local_sglist[i].len,
11985 			       local_dma_sglist[i].len);
11986 #endif
11987 	}
11988 
11989 
11990 	return (retval);
11991 
11992 bailout_error:
11993 
11994 	ctl_send_datamove_done(io, /*have_lock*/ 0);
11995 
11996 	return (retval);
11997 }
11998 
11999 static int
12000 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12001 			 ctl_ha_dt_cb callback)
12002 {
12003 	struct ctl_ha_dt_req *rq;
12004 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12005 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12006 	uint32_t local_used, remote_used, total_used;
12007 	int retval;
12008 	int i, j;
12009 
12010 	retval = 0;
12011 
12012 	rq = ctl_dt_req_alloc();
12013 
12014 	/*
12015 	 * If we failed to allocate the request, and if the DMA didn't fail
12016 	 * anyway, set busy status.  This is just a resource allocation
12017 	 * failure.
12018 	 */
12019 	if ((rq == NULL)
12020 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12021 		ctl_set_busy(&io->scsiio);
12022 
12023 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12024 
12025 		if (rq != NULL)
12026 			ctl_dt_req_free(rq);
12027 
12028 		/*
12029 		 * The data move failed.  We need to return status back
12030 		 * to the other controller.  No point in trying to DMA
12031 		 * data to the remote controller.
12032 		 */
12033 
12034 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12035 
12036 		retval = 1;
12037 
12038 		goto bailout;
12039 	}
12040 
12041 	local_sglist = io->io_hdr.local_sglist;
12042 	local_dma_sglist = io->io_hdr.local_dma_sglist;
12043 	remote_sglist = io->io_hdr.remote_sglist;
12044 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12045 	local_used = 0;
12046 	remote_used = 0;
12047 	total_used = 0;
12048 
12049 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12050 		rq->ret = CTL_HA_STATUS_SUCCESS;
12051 		rq->context = io;
12052 		callback(rq);
12053 		goto bailout;
12054 	}
12055 
12056 	/*
12057 	 * Pull/push the data over the wire from/to the other controller.
12058 	 * This takes into account the possibility that the local and
12059 	 * remote sglists may not be identical in terms of the size of
12060 	 * the elements and the number of elements.
12061 	 *
12062 	 * One fundamental assumption here is that the length allocated for
12063 	 * both the local and remote sglists is identical.  Otherwise, we've
12064 	 * essentially got a coding error of some sort.
12065 	 */
12066 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12067 		int isc_ret;
12068 		uint32_t cur_len, dma_length;
12069 		uint8_t *tmp_ptr;
12070 
12071 		rq->id = CTL_HA_DATA_CTL;
12072 		rq->command = command;
12073 		rq->context = io;
12074 
12075 		/*
12076 		 * Both pointers should be aligned.  But it is possible
12077 		 * that the allocation length is not.  They should both
12078 		 * also have enough slack left over at the end, though,
12079 		 * to round up to the next 8 byte boundary.
12080 		 */
12081 		cur_len = ctl_min(local_sglist[i].len - local_used,
12082 				  remote_sglist[j].len - remote_used);
12083 
12084 		/*
12085 		 * In this case, we have a size issue and need to decrease
12086 		 * the size, except in the case where we actually have less
12087 		 * than 8 bytes left.  In that case, we need to increase
12088 		 * the DMA length to get the last bit.
12089 		 */
12090 		if ((cur_len & 0x7) != 0) {
12091 			if (cur_len > 0x7) {
12092 				cur_len = cur_len - (cur_len & 0x7);
12093 				dma_length = cur_len;
12094 			} else {
12095 				CTL_SIZE_8B(dma_length, cur_len);
12096 			}
12097 
12098 		} else
12099 			dma_length = cur_len;
12100 
12101 		/*
12102 		 * If we had to allocate memory for this I/O, instead of using
12103 		 * the non-cached mirror memory, we'll need to flush the cache
12104 		 * before trying to DMA to the other controller.
12105 		 *
12106 		 * We could end up doing this multiple times for the same
12107 		 * segment if we have a larger local segment than remote
12108 		 * segment.  That shouldn't be an issue.
12109 		 */
12110 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12111 			/*
12112 			 * XXX KDM use bus_dmamap_sync() here.
12113 			 */
12114 		}
12115 
12116 		rq->size = dma_length;
12117 
12118 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12119 		tmp_ptr += local_used;
12120 
12121 		/* Use physical addresses when talking to ISC hardware */
12122 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12123 			/* XXX KDM use busdma */
12124 #if 0
12125 			rq->local = vtophys(tmp_ptr);
12126 #endif
12127 		} else
12128 			rq->local = tmp_ptr;
12129 
12130 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12131 		tmp_ptr += remote_used;
12132 		rq->remote = tmp_ptr;
12133 
12134 		rq->callback = NULL;
12135 
12136 		local_used += cur_len;
12137 		if (local_used >= local_sglist[i].len) {
12138 			i++;
12139 			local_used = 0;
12140 		}
12141 
12142 		remote_used += cur_len;
12143 		if (remote_used >= remote_sglist[j].len) {
12144 			j++;
12145 			remote_used = 0;
12146 		}
12147 		total_used += cur_len;
12148 
12149 		if (total_used >= io->scsiio.kern_data_len)
12150 			rq->callback = callback;
12151 
12152 		if ((rq->size & 0x7) != 0) {
12153 			printf("%s: warning: size %d is not on 8b boundary\n",
12154 			       __func__, rq->size);
12155 		}
12156 		if (((uintptr_t)rq->local & 0x7) != 0) {
12157 			printf("%s: warning: local %p not on 8b boundary\n",
12158 			       __func__, rq->local);
12159 		}
12160 		if (((uintptr_t)rq->remote & 0x7) != 0) {
12161 			printf("%s: warning: remote %p not on 8b boundary\n",
12162 			       __func__, rq->local);
12163 		}
12164 #if 0
12165 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12166 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12167 		       rq->local, rq->remote, rq->size);
12168 #endif
12169 
12170 		isc_ret = ctl_dt_single(rq);
12171 		if (isc_ret == CTL_HA_STATUS_WAIT)
12172 			continue;
12173 
12174 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12175 			rq->ret = CTL_HA_STATUS_SUCCESS;
12176 		} else {
12177 			rq->ret = isc_ret;
12178 		}
12179 		callback(rq);
12180 		goto bailout;
12181 	}
12182 
12183 bailout:
12184 	return (retval);
12185 
12186 }
12187 
12188 static void
12189 ctl_datamove_remote_read(union ctl_io *io)
12190 {
12191 	int retval;
12192 	int i;
12193 
12194 	/*
12195 	 * This will send an error to the other controller in the case of a
12196 	 * failure.
12197 	 */
12198 	retval = ctl_datamove_remote_sgl_setup(io);
12199 	if (retval != 0)
12200 		return;
12201 
12202 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12203 					  ctl_datamove_remote_read_cb);
12204 	if ((retval != 0)
12205 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12206 		/*
12207 		 * Make sure we free memory if there was an error..  The
12208 		 * ctl_datamove_remote_xfer() function will send the
12209 		 * datamove done message, or call the callback with an
12210 		 * error if there is a problem.
12211 		 */
12212 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12213 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12214 	}
12215 
12216 	return;
12217 }
12218 
12219 /*
12220  * Process a datamove request from the other controller.  This is used for
12221  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12222  * first.  Once that is complete, the data gets DMAed into the remote
12223  * controller's memory.  For reads, we DMA from the remote controller's
12224  * memory into our memory first, and then move it out to the FETD.
12225  *
12226  * Should be called without the ctl_lock held.
12227  */
12228 static void
12229 ctl_datamove_remote(union ctl_io *io)
12230 {
12231 	struct ctl_softc *softc;
12232 
12233 	softc = control_softc;
12234 
12235 	/*
12236 	 * Note that we look for an aborted I/O here, but don't do some of
12237 	 * the other checks that ctl_datamove() normally does.  We don't
12238 	 * need to run the task queue, because this I/O is on the ISC
12239 	 * queue, which is executed by the work thread after the task queue.
12240 	 * We don't need to run the datamove delay code, since that should
12241 	 * have been done if need be on the other controller.
12242 	 */
12243 	mtx_lock(&softc->ctl_lock);
12244 
12245 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12246 
12247 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
12248 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
12249 		       io->io_hdr.nexus.targ_port,
12250 		       io->io_hdr.nexus.targ_target.id,
12251 		       io->io_hdr.nexus.targ_lun);
12252 		io->io_hdr.status = CTL_CMD_ABORTED;
12253 		io->io_hdr.port_status = 31338;
12254 
12255 		mtx_unlock(&softc->ctl_lock);
12256 
12257 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12258 
12259 		return;
12260 	}
12261 
12262 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
12263 		mtx_unlock(&softc->ctl_lock);
12264 		ctl_datamove_remote_write(io);
12265 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
12266 		mtx_unlock(&softc->ctl_lock);
12267 		ctl_datamove_remote_read(io);
12268 	} else {
12269 		union ctl_ha_msg msg;
12270 		struct scsi_sense_data *sense;
12271 		uint8_t sks[3];
12272 		int retry_count;
12273 
12274 		memset(&msg, 0, sizeof(msg));
12275 
12276 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
12277 		msg.hdr.status = CTL_SCSI_ERROR;
12278 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
12279 
12280 		retry_count = 4243;
12281 
12282 		sense = &msg.scsi.sense_data;
12283 		sks[0] = SSD_SCS_VALID;
12284 		sks[1] = (retry_count >> 8) & 0xff;
12285 		sks[2] = retry_count & 0xff;
12286 
12287 		/* "Internal target failure" */
12288 		scsi_set_sense_data(sense,
12289 				    /*sense_format*/ SSD_TYPE_NONE,
12290 				    /*current_error*/ 1,
12291 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
12292 				    /*asc*/ 0x44,
12293 				    /*ascq*/ 0x00,
12294 				    /*type*/ SSD_ELEM_SKS,
12295 				    /*size*/ sizeof(sks),
12296 				    /*data*/ sks,
12297 				    SSD_ELEM_NONE);
12298 
12299 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12300 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12301 			ctl_failover_io(io, /*have_lock*/ 1);
12302 			mtx_unlock(&softc->ctl_lock);
12303 			return;
12304 		}
12305 
12306 		mtx_unlock(&softc->ctl_lock);
12307 
12308 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
12309 		    CTL_HA_STATUS_SUCCESS) {
12310 			/* XXX KDM what to do if this fails? */
12311 		}
12312 		return;
12313 	}
12314 
12315 }
12316 
12317 static int
12318 ctl_process_done(union ctl_io *io, int have_lock)
12319 {
12320 	struct ctl_lun *lun;
12321 	struct ctl_softc *ctl_softc;
12322 	void (*fe_done)(union ctl_io *io);
12323 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
12324 
12325 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12326 
12327 	fe_done =
12328 	    control_softc->ctl_ports[targ_port]->fe_done;
12329 
12330 #ifdef CTL_TIME_IO
12331 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12332 		char str[256];
12333 		char path_str[64];
12334 		struct sbuf sb;
12335 
12336 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12337 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12338 
12339 		sbuf_cat(&sb, path_str);
12340 		switch (io->io_hdr.io_type) {
12341 		case CTL_IO_SCSI:
12342 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12343 			sbuf_printf(&sb, "\n");
12344 			sbuf_cat(&sb, path_str);
12345 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12346 				    io->scsiio.tag_num, io->scsiio.tag_type);
12347 			break;
12348 		case CTL_IO_TASK:
12349 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12350 				    "Tag Type: %d\n", io->taskio.task_action,
12351 				    io->taskio.tag_num, io->taskio.tag_type);
12352 			break;
12353 		default:
12354 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12355 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12356 			break;
12357 		}
12358 		sbuf_cat(&sb, path_str);
12359 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12360 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12361 		sbuf_finish(&sb);
12362 		printf("%s", sbuf_data(&sb));
12363 	}
12364 #endif /* CTL_TIME_IO */
12365 
12366 	switch (io->io_hdr.io_type) {
12367 	case CTL_IO_SCSI:
12368 		break;
12369 	case CTL_IO_TASK:
12370 		ctl_io_error_print(io, NULL);
12371 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12372 			ctl_free_io_internal(io, /*have_lock*/ 0);
12373 		else
12374 			fe_done(io);
12375 		return (CTL_RETVAL_COMPLETE);
12376 		break;
12377 	default:
12378 		printf("ctl_process_done: invalid io type %d\n",
12379 		       io->io_hdr.io_type);
12380 		panic("ctl_process_done: invalid io type %d\n",
12381 		      io->io_hdr.io_type);
12382 		break; /* NOTREACHED */
12383 	}
12384 
12385 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12386 	if (lun == NULL) {
12387 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12388 				 io->io_hdr.nexus.targ_lun));
12389 		fe_done(io);
12390 		goto bailout;
12391 	}
12392 	ctl_softc = lun->ctl_softc;
12393 
12394 	/*
12395 	 * Remove this from the OOA queue.
12396 	 */
12397 	if (have_lock == 0)
12398 		mtx_lock(&ctl_softc->ctl_lock);
12399 
12400 	/*
12401 	 * Check to see if we have any errors to inject here.  We only
12402 	 * inject errors for commands that don't already have errors set.
12403 	 */
12404 	if ((STAILQ_FIRST(&lun->error_list) != NULL)
12405 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
12406 		ctl_inject_error(lun, io);
12407 
12408 	/*
12409 	 * XXX KDM how do we treat commands that aren't completed
12410 	 * successfully?
12411 	 *
12412 	 * XXX KDM should we also track I/O latency?
12413 	 */
12414 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) {
12415 		uint32_t blocksize;
12416 #ifdef CTL_TIME_IO
12417 		struct bintime cur_bt;
12418 #endif
12419 
12420 		if ((lun->be_lun != NULL)
12421 		 && (lun->be_lun->blocksize != 0))
12422 			blocksize = lun->be_lun->blocksize;
12423 		else
12424 			blocksize = 512;
12425 
12426 		switch (io->io_hdr.io_type) {
12427 		case CTL_IO_SCSI: {
12428 			int isread;
12429 			struct ctl_lba_len lbalen;
12430 
12431 			isread = 0;
12432 			switch (io->scsiio.cdb[0]) {
12433 			case READ_6:
12434 			case READ_10:
12435 			case READ_12:
12436 			case READ_16:
12437 				isread = 1;
12438 				/* FALLTHROUGH */
12439 			case WRITE_6:
12440 			case WRITE_10:
12441 			case WRITE_12:
12442 			case WRITE_16:
12443 			case WRITE_VERIFY_10:
12444 			case WRITE_VERIFY_12:
12445 			case WRITE_VERIFY_16:
12446 				memcpy(&lbalen, io->io_hdr.ctl_private[
12447 				       CTL_PRIV_LBA_LEN].bytes, sizeof(lbalen));
12448 
12449 				if (isread) {
12450 					lun->stats.ports[targ_port].bytes[CTL_STATS_READ] +=
12451 						lbalen.len * blocksize;
12452 					lun->stats.ports[targ_port].operations[CTL_STATS_READ]++;
12453 
12454 #ifdef CTL_TIME_IO
12455 					bintime_add(
12456 					   &lun->stats.ports[targ_port].dma_time[CTL_STATS_READ],
12457 					   &io->io_hdr.dma_bt);
12458 					lun->stats.ports[targ_port].num_dmas[CTL_STATS_READ] +=
12459 						io->io_hdr.num_dmas;
12460 					getbintime(&cur_bt);
12461 					bintime_sub(&cur_bt,
12462 						    &io->io_hdr.start_bt);
12463 
12464 					bintime_add(
12465 					    &lun->stats.ports[targ_port].time[CTL_STATS_READ],
12466 					    &cur_bt);
12467 
12468 #if 0
12469 					cs_prof_gettime(&cur_ticks);
12470 					lun->stats.time[CTL_STATS_READ] +=
12471 						cur_ticks -
12472 						io->io_hdr.start_ticks;
12473 #endif
12474 #if 0
12475 					lun->stats.time[CTL_STATS_READ] +=
12476 						jiffies - io->io_hdr.start_time;
12477 #endif
12478 #endif /* CTL_TIME_IO */
12479 				} else {
12480 					lun->stats.ports[targ_port].bytes[CTL_STATS_WRITE] +=
12481 						lbalen.len * blocksize;
12482 					lun->stats.ports[targ_port].operations[
12483 						CTL_STATS_WRITE]++;
12484 
12485 #ifdef CTL_TIME_IO
12486 					bintime_add(
12487 					  &lun->stats.ports[targ_port].dma_time[CTL_STATS_WRITE],
12488 					  &io->io_hdr.dma_bt);
12489 					lun->stats.ports[targ_port].num_dmas[CTL_STATS_WRITE] +=
12490 						io->io_hdr.num_dmas;
12491 					getbintime(&cur_bt);
12492 					bintime_sub(&cur_bt,
12493 						    &io->io_hdr.start_bt);
12494 
12495 					bintime_add(
12496 					    &lun->stats.ports[targ_port].time[CTL_STATS_WRITE],
12497 					    &cur_bt);
12498 #if 0
12499 					cs_prof_gettime(&cur_ticks);
12500 					lun->stats.ports[targ_port].time[CTL_STATS_WRITE] +=
12501 						cur_ticks -
12502 						io->io_hdr.start_ticks;
12503 					lun->stats.ports[targ_port].time[CTL_STATS_WRITE] +=
12504 						jiffies - io->io_hdr.start_time;
12505 #endif
12506 #endif /* CTL_TIME_IO */
12507 				}
12508 				break;
12509 			default:
12510 				lun->stats.ports[targ_port].operations[CTL_STATS_NO_IO]++;
12511 
12512 #ifdef CTL_TIME_IO
12513 				bintime_add(
12514 				  &lun->stats.ports[targ_port].dma_time[CTL_STATS_NO_IO],
12515 				  &io->io_hdr.dma_bt);
12516 				lun->stats.ports[targ_port].num_dmas[CTL_STATS_NO_IO] +=
12517 					io->io_hdr.num_dmas;
12518 				getbintime(&cur_bt);
12519 				bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12520 
12521 				bintime_add(&lun->stats.ports[targ_port].time[CTL_STATS_NO_IO],
12522 					    &cur_bt);
12523 
12524 #if 0
12525 				cs_prof_gettime(&cur_ticks);
12526 				lun->stats.ports[targ_port].time[CTL_STATS_NO_IO] +=
12527 					cur_ticks -
12528 					io->io_hdr.start_ticks;
12529 				lun->stats.ports[targ_port].time[CTL_STATS_NO_IO] +=
12530 					jiffies - io->io_hdr.start_time;
12531 #endif
12532 #endif /* CTL_TIME_IO */
12533 				break;
12534 			}
12535 			break;
12536 		}
12537 		default:
12538 			break;
12539 		}
12540 	}
12541 
12542 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12543 
12544 	/*
12545 	 * Run through the blocked queue on this LUN and see if anything
12546 	 * has become unblocked, now that this transaction is done.
12547 	 */
12548 	ctl_check_blocked(lun);
12549 
12550 	/*
12551 	 * If the LUN has been invalidated, free it if there is nothing
12552 	 * left on its OOA queue.
12553 	 */
12554 	if ((lun->flags & CTL_LUN_INVALID)
12555 	 && (TAILQ_FIRST(&lun->ooa_queue) == NULL))
12556 		ctl_free_lun(lun);
12557 
12558 	/*
12559 	 * If this command has been aborted, make sure we set the status
12560 	 * properly.  The FETD is responsible for freeing the I/O and doing
12561 	 * whatever it needs to do to clean up its state.
12562 	 */
12563 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12564 		io->io_hdr.status = CTL_CMD_ABORTED;
12565 
12566 	/*
12567 	 * We print out status for every task management command.  For SCSI
12568 	 * commands, we filter out any unit attention errors; they happen
12569 	 * on every boot, and would clutter up the log.  Note:  task
12570 	 * management commands aren't printed here, they are printed above,
12571 	 * since they should never even make it down here.
12572 	 */
12573 	switch (io->io_hdr.io_type) {
12574 	case CTL_IO_SCSI: {
12575 		int error_code, sense_key, asc, ascq;
12576 
12577 		sense_key = 0;
12578 
12579 		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
12580 		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
12581 			/*
12582 			 * Since this is just for printing, no need to
12583 			 * show errors here.
12584 			 */
12585 			scsi_extract_sense_len(&io->scsiio.sense_data,
12586 					       io->scsiio.sense_len,
12587 					       &error_code,
12588 					       &sense_key,
12589 					       &asc,
12590 					       &ascq,
12591 					       /*show_errors*/ 0);
12592 		}
12593 
12594 		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
12595 		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
12596 		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
12597 		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
12598 
12599 			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
12600 				ctl_softc->skipped_prints++;
12601 				if (have_lock == 0)
12602 					mtx_unlock(&ctl_softc->ctl_lock);
12603 			} else {
12604 				uint32_t skipped_prints;
12605 
12606 				skipped_prints = ctl_softc->skipped_prints;
12607 
12608 				ctl_softc->skipped_prints = 0;
12609 				ctl_softc->last_print_jiffies = time_uptime;
12610 
12611 				if (have_lock == 0)
12612 					mtx_unlock(&ctl_softc->ctl_lock);
12613 				if (skipped_prints > 0) {
12614 #ifdef NEEDTOPORT
12615 					csevent_log(CSC_CTL | CSC_SHELF_SW |
12616 					    CTL_ERROR_REPORT,
12617 					    csevent_LogType_Trace,
12618 					    csevent_Severity_Information,
12619 					    csevent_AlertLevel_Green,
12620 					    csevent_FRU_Firmware,
12621 					    csevent_FRU_Unknown,
12622 					    "High CTL error volume, %d prints "
12623 					    "skipped", skipped_prints);
12624 #endif
12625 				}
12626 				ctl_io_error_print(io, NULL);
12627 			}
12628 		} else {
12629 			if (have_lock == 0)
12630 				mtx_unlock(&ctl_softc->ctl_lock);
12631 		}
12632 		break;
12633 	}
12634 	case CTL_IO_TASK:
12635 		if (have_lock == 0)
12636 			mtx_unlock(&ctl_softc->ctl_lock);
12637 		ctl_io_error_print(io, NULL);
12638 		break;
12639 	default:
12640 		if (have_lock == 0)
12641 			mtx_unlock(&ctl_softc->ctl_lock);
12642 		break;
12643 	}
12644 
12645 	/*
12646 	 * Tell the FETD or the other shelf controller we're done with this
12647 	 * command.  Note that only SCSI commands get to this point.  Task
12648 	 * management commands are completed above.
12649 	 *
12650 	 * We only send status to the other controller if we're in XFER
12651 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
12652 	 * received the I/O (from CTL's perspective), and so the status is
12653 	 * generated there.
12654 	 *
12655 	 * XXX KDM if we hold the lock here, we could cause a deadlock
12656 	 * if the frontend comes back in in this context to queue
12657 	 * something.
12658 	 */
12659 	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
12660 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12661 		union ctl_ha_msg msg;
12662 
12663 		memset(&msg, 0, sizeof(msg));
12664 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12665 		msg.hdr.original_sc = io->io_hdr.original_sc;
12666 		msg.hdr.nexus = io->io_hdr.nexus;
12667 		msg.hdr.status = io->io_hdr.status;
12668 		msg.scsi.scsi_status = io->scsiio.scsi_status;
12669 		msg.scsi.tag_num = io->scsiio.tag_num;
12670 		msg.scsi.tag_type = io->scsiio.tag_type;
12671 		msg.scsi.sense_len = io->scsiio.sense_len;
12672 		msg.scsi.sense_residual = io->scsiio.sense_residual;
12673 		msg.scsi.residual = io->scsiio.residual;
12674 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12675 		       sizeof(io->scsiio.sense_data));
12676 		/*
12677 		 * We copy this whether or not this is an I/O-related
12678 		 * command.  Otherwise, we'd have to go and check to see
12679 		 * whether it's a read/write command, and it really isn't
12680 		 * worth it.
12681 		 */
12682 		memcpy(&msg.scsi.lbalen,
12683 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
12684 		       sizeof(msg.scsi.lbalen));;
12685 
12686 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12687 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12688 			/* XXX do something here */
12689 		}
12690 
12691 		ctl_free_io_internal(io, /*have_lock*/ 0);
12692 	} else
12693 		fe_done(io);
12694 
12695 bailout:
12696 
12697 	return (CTL_RETVAL_COMPLETE);
12698 }
12699 
12700 /*
12701  * Front end should call this if it doesn't do autosense.  When the request
12702  * sense comes back in from the initiator, we'll dequeue this and send it.
12703  */
12704 int
12705 ctl_queue_sense(union ctl_io *io)
12706 {
12707 	struct ctl_lun *lun;
12708 	struct ctl_softc *ctl_softc;
12709 	uint32_t initidx;
12710 
12711 	ctl_softc = control_softc;
12712 
12713 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
12714 
12715 	/*
12716 	 * LUN lookup will likely move to the ctl_work_thread() once we
12717 	 * have our new queueing infrastructure (that doesn't put things on
12718 	 * a per-LUN queue initially).  That is so that we can handle
12719 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
12720 	 * can't deal with that right now.
12721 	 */
12722 	mtx_lock(&ctl_softc->ctl_lock);
12723 
12724 	/*
12725 	 * If we don't have a LUN for this, just toss the sense
12726 	 * information.
12727 	 */
12728 	if ((io->io_hdr.nexus.targ_lun < CTL_MAX_LUNS)
12729 	 && (ctl_softc->ctl_luns[io->io_hdr.nexus.targ_lun] != NULL))
12730 		lun = ctl_softc->ctl_luns[io->io_hdr.nexus.targ_lun];
12731 	else
12732 		goto bailout;
12733 
12734 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12735 
12736 	/*
12737 	 * Already have CA set for this LUN...toss the sense information.
12738 	 */
12739 	if (ctl_is_set(lun->have_ca, initidx))
12740 		goto bailout;
12741 
12742 	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
12743 	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
12744 	       sizeof(io->scsiio.sense_data)));
12745 	ctl_set_mask(lun->have_ca, initidx);
12746 
12747 bailout:
12748 	mtx_unlock(&ctl_softc->ctl_lock);
12749 
12750 	ctl_free_io(io);
12751 
12752 	return (CTL_RETVAL_COMPLETE);
12753 }
12754 
12755 /*
12756  * Primary command inlet from frontend ports.  All SCSI and task I/O
12757  * requests must go through this function.
12758  */
12759 int
12760 ctl_queue(union ctl_io *io)
12761 {
12762 	struct ctl_softc *ctl_softc;
12763 
12764 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
12765 
12766 	ctl_softc = control_softc;
12767 
12768 #ifdef CTL_TIME_IO
12769 	io->io_hdr.start_time = time_uptime;
12770 	getbintime(&io->io_hdr.start_bt);
12771 #endif /* CTL_TIME_IO */
12772 
12773 	mtx_lock(&ctl_softc->ctl_lock);
12774 
12775 	switch (io->io_hdr.io_type) {
12776 	case CTL_IO_SCSI:
12777 		STAILQ_INSERT_TAIL(&ctl_softc->incoming_queue, &io->io_hdr,
12778 				   links);
12779 		break;
12780 	case CTL_IO_TASK:
12781 		STAILQ_INSERT_TAIL(&ctl_softc->task_queue, &io->io_hdr, links);
12782 		/*
12783 		 * Set the task pending flag.  This is necessary to close a
12784 		 * race condition with the FETD:
12785 		 *
12786 		 * - FETD submits a task management command, like an abort.
12787 		 * - Back end calls fe_datamove() to move the data for the
12788 		 *   aborted command.  The FETD can't really accept it, but
12789 		 *   if it did, it would end up transmitting data for a
12790 		 *   command that the initiator told us to abort.
12791 		 *
12792 		 * We close the race condition by setting the flag here,
12793 		 * and checking it in ctl_datamove(), before calling the
12794 		 * FETD's fe_datamove routine.  If we've got a task
12795 		 * pending, we run the task queue and then check to see
12796 		 * whether our particular I/O has been aborted.
12797 		 */
12798 		ctl_softc->flags |= CTL_FLAG_TASK_PENDING;
12799 		break;
12800 	default:
12801 		mtx_unlock(&ctl_softc->ctl_lock);
12802 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
12803 		return (-EINVAL);
12804 		break; /* NOTREACHED */
12805 	}
12806 	mtx_unlock(&ctl_softc->ctl_lock);
12807 
12808 	ctl_wakeup_thread();
12809 
12810 	return (CTL_RETVAL_COMPLETE);
12811 }
12812 
12813 #ifdef CTL_IO_DELAY
12814 static void
12815 ctl_done_timer_wakeup(void *arg)
12816 {
12817 	union ctl_io *io;
12818 
12819 	io = (union ctl_io *)arg;
12820 	ctl_done_lock(io, /*have_lock*/ 0);
12821 }
12822 #endif /* CTL_IO_DELAY */
12823 
12824 void
12825 ctl_done_lock(union ctl_io *io, int have_lock)
12826 {
12827 	struct ctl_softc *ctl_softc;
12828 #ifndef CTL_DONE_THREAD
12829 	union ctl_io *xio;
12830 #endif /* !CTL_DONE_THREAD */
12831 
12832 	ctl_softc = control_softc;
12833 
12834 	if (have_lock == 0)
12835 		mtx_lock(&ctl_softc->ctl_lock);
12836 
12837 	/*
12838 	 * Enable this to catch duplicate completion issues.
12839 	 */
12840 #if 0
12841 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
12842 		printf("%s: type %d msg %d cdb %x iptl: "
12843 		       "%d:%d:%d:%d tag 0x%04x "
12844 		       "flag %#x status %x\n",
12845 			__func__,
12846 			io->io_hdr.io_type,
12847 			io->io_hdr.msg_type,
12848 			io->scsiio.cdb[0],
12849 			io->io_hdr.nexus.initid.id,
12850 			io->io_hdr.nexus.targ_port,
12851 			io->io_hdr.nexus.targ_target.id,
12852 			io->io_hdr.nexus.targ_lun,
12853 			(io->io_hdr.io_type ==
12854 			CTL_IO_TASK) ?
12855 			io->taskio.tag_num :
12856 			io->scsiio.tag_num,
12857 		        io->io_hdr.flags,
12858 			io->io_hdr.status);
12859 	} else
12860 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
12861 #endif
12862 
12863 	/*
12864 	 * This is an internal copy of an I/O, and should not go through
12865 	 * the normal done processing logic.
12866 	 */
12867 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY) {
12868 		if (have_lock == 0)
12869 			mtx_unlock(&ctl_softc->ctl_lock);
12870 		return;
12871 	}
12872 
12873 	/*
12874 	 * We need to send a msg to the serializing shelf to finish the IO
12875 	 * as well.  We don't send a finish message to the other shelf if
12876 	 * this is a task management command.  Task management commands
12877 	 * aren't serialized in the OOA queue, but rather just executed on
12878 	 * both shelf controllers for commands that originated on that
12879 	 * controller.
12880 	 */
12881 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
12882 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
12883 		union ctl_ha_msg msg_io;
12884 
12885 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
12886 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
12887 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
12888 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
12889 		}
12890 		/* continue on to finish IO */
12891 	}
12892 #ifdef CTL_IO_DELAY
12893 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12894 		struct ctl_lun *lun;
12895 
12896 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12897 
12898 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12899 	} else {
12900 		struct ctl_lun *lun;
12901 
12902 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12903 
12904 		if ((lun != NULL)
12905 		 && (lun->delay_info.done_delay > 0)) {
12906 			struct callout *callout;
12907 
12908 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12909 			callout_init(callout, /*mpsafe*/ 1);
12910 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12911 			callout_reset(callout,
12912 				      lun->delay_info.done_delay * hz,
12913 				      ctl_done_timer_wakeup, io);
12914 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
12915 				lun->delay_info.done_delay = 0;
12916 			if (have_lock == 0)
12917 				mtx_unlock(&ctl_softc->ctl_lock);
12918 			return;
12919 		}
12920 	}
12921 #endif /* CTL_IO_DELAY */
12922 
12923 	STAILQ_INSERT_TAIL(&ctl_softc->done_queue, &io->io_hdr, links);
12924 
12925 #ifdef CTL_DONE_THREAD
12926 	if (have_lock == 0)
12927 		mtx_unlock(&ctl_softc->ctl_lock);
12928 
12929 	ctl_wakeup_thread();
12930 #else /* CTL_DONE_THREAD */
12931 	for (xio = (union ctl_io *)STAILQ_FIRST(&ctl_softc->done_queue);
12932 	     xio != NULL;
12933 	     xio =(union ctl_io *)STAILQ_FIRST(&ctl_softc->done_queue)) {
12934 
12935 		STAILQ_REMOVE_HEAD(&ctl_softc->done_queue, links);
12936 
12937 		ctl_process_done(xio, /*have_lock*/ 1);
12938 	}
12939 	if (have_lock == 0)
12940 		mtx_unlock(&ctl_softc->ctl_lock);
12941 #endif /* CTL_DONE_THREAD */
12942 }
12943 
12944 void
12945 ctl_done(union ctl_io *io)
12946 {
12947 	ctl_done_lock(io, /*have_lock*/ 0);
12948 }
12949 
12950 int
12951 ctl_isc(struct ctl_scsiio *ctsio)
12952 {
12953 	struct ctl_lun *lun;
12954 	int retval;
12955 
12956 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12957 
12958 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
12959 
12960 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
12961 
12962 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
12963 
12964 	return (retval);
12965 }
12966 
12967 
12968 static void
12969 ctl_work_thread(void *arg)
12970 {
12971 	struct ctl_softc *softc;
12972 	union ctl_io *io;
12973 	struct ctl_be_lun *be_lun;
12974 	int retval;
12975 
12976 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
12977 
12978 	softc = (struct ctl_softc *)arg;
12979 	if (softc == NULL)
12980 		return;
12981 
12982 	mtx_lock(&softc->ctl_lock);
12983 	for (;;) {
12984 		retval = 0;
12985 
12986 		/*
12987 		 * We handle the queues in this order:
12988 		 * - task management
12989 		 * - ISC
12990 		 * - done queue (to free up resources, unblock other commands)
12991 		 * - RtR queue
12992 		 * - incoming queue
12993 		 *
12994 		 * If those queues are empty, we break out of the loop and
12995 		 * go to sleep.
12996 		 */
12997 		io = (union ctl_io *)STAILQ_FIRST(&softc->task_queue);
12998 		if (io != NULL) {
12999 			ctl_run_task_queue(softc);
13000 			continue;
13001 		}
13002 		io = (union ctl_io *)STAILQ_FIRST(&softc->isc_queue);
13003 		if (io != NULL) {
13004 			STAILQ_REMOVE_HEAD(&softc->isc_queue, links);
13005 			ctl_handle_isc(io);
13006 			continue;
13007 		}
13008 		io = (union ctl_io *)STAILQ_FIRST(&softc->done_queue);
13009 		if (io != NULL) {
13010 			STAILQ_REMOVE_HEAD(&softc->done_queue, links);
13011 			/* clear any blocked commands, call fe_done */
13012 			mtx_unlock(&softc->ctl_lock);
13013 			/*
13014 			 * XXX KDM
13015 			 * Call this without a lock for now.  This will
13016 			 * depend on whether there is any way the FETD can
13017 			 * sleep or deadlock if called with the CTL lock
13018 			 * held.
13019 			 */
13020 			retval = ctl_process_done(io, /*have_lock*/ 0);
13021 			mtx_lock(&softc->ctl_lock);
13022 			continue;
13023 		}
13024 		if (!ctl_pause_rtr) {
13025 			io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
13026 			if (io != NULL) {
13027 				STAILQ_REMOVE_HEAD(&softc->rtr_queue, links);
13028 				mtx_unlock(&softc->ctl_lock);
13029 				goto execute;
13030 			}
13031 		}
13032 		io = (union ctl_io *)STAILQ_FIRST(&softc->incoming_queue);
13033 		if (io != NULL) {
13034 			STAILQ_REMOVE_HEAD(&softc->incoming_queue, links);
13035 			mtx_unlock(&softc->ctl_lock);
13036 			ctl_scsiio_precheck(softc, &io->scsiio);
13037 			mtx_lock(&softc->ctl_lock);
13038 			continue;
13039 		}
13040 		/*
13041 		 * We might want to move this to a separate thread, so that
13042 		 * configuration requests (in this case LUN creations)
13043 		 * won't impact the I/O path.
13044 		 */
13045 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13046 		if (be_lun != NULL) {
13047 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13048 			mtx_unlock(&softc->ctl_lock);
13049 			ctl_create_lun(be_lun);
13050 			mtx_lock(&softc->ctl_lock);
13051 			continue;
13052 		}
13053 
13054 		/* XXX KDM use the PDROP flag?? */
13055 		/* Sleep until we have something to do. */
13056 		mtx_sleep(softc, &softc->ctl_lock, PRIBIO, "ctl_work", 0);
13057 
13058 		/* Back to the top of the loop to see what woke us up. */
13059 		continue;
13060 
13061 execute:
13062 		retval = ctl_scsiio(&io->scsiio);
13063 		switch (retval) {
13064 		case CTL_RETVAL_COMPLETE:
13065 			break;
13066 		default:
13067 			/*
13068 			 * Probably need to make sure this doesn't happen.
13069 			 */
13070 			break;
13071 		}
13072 		mtx_lock(&softc->ctl_lock);
13073 	}
13074 }
13075 
13076 void
13077 ctl_wakeup_thread()
13078 {
13079 	struct ctl_softc *softc;
13080 
13081 	softc = control_softc;
13082 
13083 	wakeup(softc);
13084 }
13085 
13086 /* Initialization and failover */
13087 
13088 void
13089 ctl_init_isc_msg(void)
13090 {
13091 	printf("CTL: Still calling this thing\n");
13092 }
13093 
13094 /*
13095  * Init component
13096  * 	Initializes component into configuration defined by bootMode
13097  *	(see hasc-sv.c)
13098  *  	returns hasc_Status:
13099  * 		OK
13100  *		ERROR - fatal error
13101  */
13102 static ctl_ha_comp_status
13103 ctl_isc_init(struct ctl_ha_component *c)
13104 {
13105 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13106 
13107 	c->status = ret;
13108 	return ret;
13109 }
13110 
13111 /* Start component
13112  * 	Starts component in state requested. If component starts successfully,
13113  *	it must set its own state to the requestrd state
13114  *	When requested state is HASC_STATE_HA, the component may refine it
13115  * 	by adding _SLAVE or _MASTER flags.
13116  *	Currently allowed state transitions are:
13117  *	UNKNOWN->HA		- initial startup
13118  *	UNKNOWN->SINGLE - initial startup when no parter detected
13119  *	HA->SINGLE		- failover
13120  * returns ctl_ha_comp_status:
13121  * 		OK	- component successfully started in requested state
13122  *		FAILED  - could not start the requested state, failover may
13123  * 			  be possible
13124  *		ERROR	- fatal error detected, no future startup possible
13125  */
13126 static ctl_ha_comp_status
13127 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13128 {
13129 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13130 
13131 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13132 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13133 		ctl_is_single = 0;
13134 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13135 		    != CTL_HA_STATUS_SUCCESS) {
13136 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13137 			ret = CTL_HA_COMP_STATUS_ERROR;
13138 		}
13139 	} else if (CTL_HA_STATE_IS_HA(c->state)
13140 		&& CTL_HA_STATE_IS_SINGLE(state)){
13141 		// HA->SINGLE transition
13142 	        ctl_failover();
13143 		ctl_is_single = 1;
13144 	} else {
13145 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13146 		       c->state, state);
13147 		ret = CTL_HA_COMP_STATUS_ERROR;
13148 	}
13149 	if (CTL_HA_STATE_IS_SINGLE(state))
13150 		ctl_is_single = 1;
13151 
13152 	c->state = state;
13153 	c->status = ret;
13154 	return ret;
13155 }
13156 
13157 /*
13158  * Quiesce component
13159  * The component must clear any error conditions (set status to OK) and
13160  * prepare itself to another Start call
13161  * returns ctl_ha_comp_status:
13162  * 	OK
13163  *	ERROR
13164  */
13165 static ctl_ha_comp_status
13166 ctl_isc_quiesce(struct ctl_ha_component *c)
13167 {
13168 	int ret = CTL_HA_COMP_STATUS_OK;
13169 
13170 	ctl_pause_rtr = 1;
13171 	c->status = ret;
13172 	return ret;
13173 }
13174 
13175 struct ctl_ha_component ctl_ha_component_ctlisc =
13176 {
13177 	.name = "CTL ISC",
13178 	.state = CTL_HA_STATE_UNKNOWN,
13179 	.init = ctl_isc_init,
13180 	.start = ctl_isc_start,
13181 	.quiesce = ctl_isc_quiesce
13182 };
13183 
13184 /*
13185  *  vim: ts=8
13186  */
13187