ctl.c revision 267641
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: head/sys/cam/ctl/ctl.c 267641 2014-06-19 12:43:41Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/types.h>
51#include <sys/kthread.h>
52#include <sys/bio.h>
53#include <sys/fcntl.h>
54#include <sys/lock.h>
55#include <sys/module.h>
56#include <sys/mutex.h>
57#include <sys/condvar.h>
58#include <sys/malloc.h>
59#include <sys/conf.h>
60#include <sys/ioccom.h>
61#include <sys/queue.h>
62#include <sys/sbuf.h>
63#include <sys/smp.h>
64#include <sys/endian.h>
65#include <sys/sysctl.h>
66
67#include <cam/cam.h>
68#include <cam/scsi/scsi_all.h>
69#include <cam/scsi/scsi_da.h>
70#include <cam/ctl/ctl_io.h>
71#include <cam/ctl/ctl.h>
72#include <cam/ctl/ctl_frontend.h>
73#include <cam/ctl/ctl_frontend_internal.h>
74#include <cam/ctl/ctl_util.h>
75#include <cam/ctl/ctl_backend.h>
76#include <cam/ctl/ctl_ioctl.h>
77#include <cam/ctl/ctl_ha.h>
78#include <cam/ctl/ctl_private.h>
79#include <cam/ctl/ctl_debug.h>
80#include <cam/ctl/ctl_scsi_all.h>
81#include <cam/ctl/ctl_error.h>
82
83struct ctl_softc *control_softc = NULL;
84
85/*
86 * The default is to run with CTL_DONE_THREAD turned on.  Completed
87 * transactions are queued for processing by the CTL work thread.  When
88 * CTL_DONE_THREAD is not defined, completed transactions are processed in
89 * the caller's context.
90 */
91#define CTL_DONE_THREAD
92
93/*
94 * Size and alignment macros needed for Copan-specific HA hardware.  These
95 * can go away when the HA code is re-written, and uses busdma for any
96 * hardware.
97 */
98#define	CTL_ALIGN_8B(target, source, type)				\
99	if (((uint32_t)source & 0x7) != 0)				\
100		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
101	else								\
102		target = (type)source;
103
104#define	CTL_SIZE_8B(target, size)					\
105	if ((size & 0x7) != 0)						\
106		target = size + (0x8 - (size & 0x7));			\
107	else								\
108		target = size;
109
110#define CTL_ALIGN_8B_MARGIN	16
111
112/*
113 * Template mode pages.
114 */
115
116/*
117 * Note that these are default values only.  The actual values will be
118 * filled in when the user does a mode sense.
119 */
120static struct copan_power_subpage power_page_default = {
121	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
122	/*subpage*/ PWR_SUBPAGE_CODE,
123	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
124			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
125	/*page_version*/ PWR_VERSION,
126	/* total_luns */ 26,
127	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
128	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
129		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
130		      0, 0, 0, 0, 0, 0}
131};
132
133static struct copan_power_subpage power_page_changeable = {
134	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
135	/*subpage*/ PWR_SUBPAGE_CODE,
136	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
137			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
138	/*page_version*/ 0,
139	/* total_luns */ 0,
140	/* max_active_luns*/ 0,
141	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
142		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
143		      0, 0, 0, 0, 0, 0}
144};
145
146static struct copan_aps_subpage aps_page_default = {
147	APS_PAGE_CODE | SMPH_SPF, //page_code
148	APS_SUBPAGE_CODE, //subpage
149	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
150	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
151	APS_VERSION, //page_version
152	0, //lock_active
153	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
154	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
155	0, 0, 0, 0, 0} //reserved
156};
157
158static struct copan_aps_subpage aps_page_changeable = {
159	APS_PAGE_CODE | SMPH_SPF, //page_code
160	APS_SUBPAGE_CODE, //subpage
161	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
162	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
163	0, //page_version
164	0, //lock_active
165	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
166	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
167	0, 0, 0, 0, 0} //reserved
168};
169
170static struct copan_debugconf_subpage debugconf_page_default = {
171	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
172	DBGCNF_SUBPAGE_CODE,		/* subpage */
173	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
174	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
175	DBGCNF_VERSION,			/* page_version */
176	{CTL_TIME_IO_DEFAULT_SECS>>8,
177	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
178};
179
180static struct copan_debugconf_subpage debugconf_page_changeable = {
181	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
182	DBGCNF_SUBPAGE_CODE,		/* subpage */
183	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
184	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
185	0,				/* page_version */
186	{0xff,0xff},			/* ctl_time_io_secs */
187};
188
189static struct scsi_format_page format_page_default = {
190	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
191	/*page_length*/sizeof(struct scsi_format_page) - 2,
192	/*tracks_per_zone*/ {0, 0},
193	/*alt_sectors_per_zone*/ {0, 0},
194	/*alt_tracks_per_zone*/ {0, 0},
195	/*alt_tracks_per_lun*/ {0, 0},
196	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
197			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
198	/*bytes_per_sector*/ {0, 0},
199	/*interleave*/ {0, 0},
200	/*track_skew*/ {0, 0},
201	/*cylinder_skew*/ {0, 0},
202	/*flags*/ SFP_HSEC,
203	/*reserved*/ {0, 0, 0}
204};
205
206static struct scsi_format_page format_page_changeable = {
207	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
208	/*page_length*/sizeof(struct scsi_format_page) - 2,
209	/*tracks_per_zone*/ {0, 0},
210	/*alt_sectors_per_zone*/ {0, 0},
211	/*alt_tracks_per_zone*/ {0, 0},
212	/*alt_tracks_per_lun*/ {0, 0},
213	/*sectors_per_track*/ {0, 0},
214	/*bytes_per_sector*/ {0, 0},
215	/*interleave*/ {0, 0},
216	/*track_skew*/ {0, 0},
217	/*cylinder_skew*/ {0, 0},
218	/*flags*/ 0,
219	/*reserved*/ {0, 0, 0}
220};
221
222static struct scsi_rigid_disk_page rigid_disk_page_default = {
223	/*page_code*/SMS_RIGID_DISK_PAGE,
224	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
225	/*cylinders*/ {0, 0, 0},
226	/*heads*/ CTL_DEFAULT_HEADS,
227	/*start_write_precomp*/ {0, 0, 0},
228	/*start_reduced_current*/ {0, 0, 0},
229	/*step_rate*/ {0, 0},
230	/*landing_zone_cylinder*/ {0, 0, 0},
231	/*rpl*/ SRDP_RPL_DISABLED,
232	/*rotational_offset*/ 0,
233	/*reserved1*/ 0,
234	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
235			   CTL_DEFAULT_ROTATION_RATE & 0xff},
236	/*reserved2*/ {0, 0}
237};
238
239static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
240	/*page_code*/SMS_RIGID_DISK_PAGE,
241	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
242	/*cylinders*/ {0, 0, 0},
243	/*heads*/ 0,
244	/*start_write_precomp*/ {0, 0, 0},
245	/*start_reduced_current*/ {0, 0, 0},
246	/*step_rate*/ {0, 0},
247	/*landing_zone_cylinder*/ {0, 0, 0},
248	/*rpl*/ 0,
249	/*rotational_offset*/ 0,
250	/*reserved1*/ 0,
251	/*rotation_rate*/ {0, 0},
252	/*reserved2*/ {0, 0}
253};
254
255static struct scsi_caching_page caching_page_default = {
256	/*page_code*/SMS_CACHING_PAGE,
257	/*page_length*/sizeof(struct scsi_caching_page) - 2,
258	/*flags1*/ SCP_DISC | SCP_WCE,
259	/*ret_priority*/ 0,
260	/*disable_pf_transfer_len*/ {0xff, 0xff},
261	/*min_prefetch*/ {0, 0},
262	/*max_prefetch*/ {0xff, 0xff},
263	/*max_pf_ceiling*/ {0xff, 0xff},
264	/*flags2*/ 0,
265	/*cache_segments*/ 0,
266	/*cache_seg_size*/ {0, 0},
267	/*reserved*/ 0,
268	/*non_cache_seg_size*/ {0, 0, 0}
269};
270
271static struct scsi_caching_page caching_page_changeable = {
272	/*page_code*/SMS_CACHING_PAGE,
273	/*page_length*/sizeof(struct scsi_caching_page) - 2,
274	/*flags1*/ 0,
275	/*ret_priority*/ 0,
276	/*disable_pf_transfer_len*/ {0, 0},
277	/*min_prefetch*/ {0, 0},
278	/*max_prefetch*/ {0, 0},
279	/*max_pf_ceiling*/ {0, 0},
280	/*flags2*/ 0,
281	/*cache_segments*/ 0,
282	/*cache_seg_size*/ {0, 0},
283	/*reserved*/ 0,
284	/*non_cache_seg_size*/ {0, 0, 0}
285};
286
287static struct scsi_control_page control_page_default = {
288	/*page_code*/SMS_CONTROL_MODE_PAGE,
289	/*page_length*/sizeof(struct scsi_control_page) - 2,
290	/*rlec*/0,
291	/*queue_flags*/0,
292	/*eca_and_aen*/0,
293	/*reserved*/0,
294	/*aen_holdoff_period*/{0, 0}
295};
296
297static struct scsi_control_page control_page_changeable = {
298	/*page_code*/SMS_CONTROL_MODE_PAGE,
299	/*page_length*/sizeof(struct scsi_control_page) - 2,
300	/*rlec*/SCP_DSENSE,
301	/*queue_flags*/0,
302	/*eca_and_aen*/0,
303	/*reserved*/0,
304	/*aen_holdoff_period*/{0, 0}
305};
306
307
308/*
309 * XXX KDM move these into the softc.
310 */
311static int rcv_sync_msg;
312static int persis_offset;
313static uint8_t ctl_pause_rtr;
314static int     ctl_is_single = 1;
315static int     index_to_aps_page;
316
317SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
318static int worker_threads = 1;
319TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
320SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
321    &worker_threads, 1, "Number of worker threads");
322static int verbose = 0;
323TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
324SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
325    &verbose, 0, "Show SCSI errors returned to initiator");
326
327/*
328 * Serial number (0x80), device id (0x83), supported pages (0x00),
329 * Block limits (0xB0) and Logical Block Provisioning (0xB2)
330 */
331#define SCSI_EVPD_NUM_SUPPORTED_PAGES	5
332
333static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
334				  int param);
335static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
336static int ctl_init(void);
337void ctl_shutdown(void);
338static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
339static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
340static void ctl_ioctl_online(void *arg);
341static void ctl_ioctl_offline(void *arg);
342static int ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id);
343static int ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id);
344static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
345static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
346static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
347static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio, int have_lock);
348static int ctl_ioctl_submit_wait(union ctl_io *io);
349static void ctl_ioctl_datamove(union ctl_io *io);
350static void ctl_ioctl_done(union ctl_io *io);
351static void ctl_ioctl_hard_startstop_callback(void *arg,
352					      struct cfi_metatask *metatask);
353static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
354static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
355			      struct ctl_ooa *ooa_hdr,
356			      struct ctl_ooa_entry *kern_entries);
357static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
358		     struct thread *td);
359uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
360uint32_t ctl_port_idx(int port_num);
361#ifdef unused
362static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
363				   uint32_t targ_target, uint32_t targ_lun,
364				   int can_wait);
365static void ctl_kfree_io(union ctl_io *io);
366#endif /* unused */
367static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
368			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
369static int ctl_free_lun(struct ctl_lun *lun);
370static void ctl_create_lun(struct ctl_be_lun *be_lun);
371/**
372static void ctl_failover_change_pages(struct ctl_softc *softc,
373				      struct ctl_scsiio *ctsio, int master);
374**/
375
376static int ctl_do_mode_select(union ctl_io *io);
377static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
378			   uint64_t res_key, uint64_t sa_res_key,
379			   uint8_t type, uint32_t residx,
380			   struct ctl_scsiio *ctsio,
381			   struct scsi_per_res_out *cdb,
382			   struct scsi_per_res_out_parms* param);
383static void ctl_pro_preempt_other(struct ctl_lun *lun,
384				  union ctl_ha_msg *msg);
385static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
386static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
387static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
388static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
389static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
390					 int alloc_len);
391static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
392static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
393static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
394static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
395static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
396static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
397					 union ctl_io *ooa_io);
398static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
399				union ctl_io *starting_io);
400static int ctl_check_blocked(struct ctl_lun *lun);
401static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
402				struct ctl_lun *lun,
403				struct ctl_cmd_entry *entry,
404				struct ctl_scsiio *ctsio);
405//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
406static void ctl_failover(void);
407static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
408			       struct ctl_scsiio *ctsio);
409static int ctl_scsiio(struct ctl_scsiio *ctsio);
410
411static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
412static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
413			    ctl_ua_type ua_type);
414static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
415			 ctl_ua_type ua_type);
416static int ctl_abort_task(union ctl_io *io);
417static void ctl_run_task_queue(struct ctl_softc *ctl_softc);
418#ifdef CTL_IO_DELAY
419static void ctl_datamove_timer_wakeup(void *arg);
420static void ctl_done_timer_wakeup(void *arg);
421#endif /* CTL_IO_DELAY */
422
423static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
424static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
425static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
426static void ctl_datamove_remote_write(union ctl_io *io);
427static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
428static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
429static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
430static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
431				    ctl_ha_dt_cb callback);
432static void ctl_datamove_remote_read(union ctl_io *io);
433static void ctl_datamove_remote(union ctl_io *io);
434static int ctl_process_done(union ctl_io *io, int have_lock);
435static void ctl_work_thread(void *arg);
436
437/*
438 * Load the serialization table.  This isn't very pretty, but is probably
439 * the easiest way to do it.
440 */
441#include "ctl_ser_table.c"
442
443/*
444 * We only need to define open, close and ioctl routines for this driver.
445 */
446static struct cdevsw ctl_cdevsw = {
447	.d_version =	D_VERSION,
448	.d_flags =	0,
449	.d_open =	ctl_open,
450	.d_close =	ctl_close,
451	.d_ioctl =	ctl_ioctl,
452	.d_name =	"ctl",
453};
454
455
456MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
457
458static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
459
460static moduledata_t ctl_moduledata = {
461	"ctl",
462	ctl_module_event_handler,
463	NULL
464};
465
466DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
467MODULE_VERSION(ctl, 1);
468
469static void
470ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
471			    union ctl_ha_msg *msg_info)
472{
473	struct ctl_scsiio *ctsio;
474
475	if (msg_info->hdr.original_sc == NULL) {
476		printf("%s: original_sc == NULL!\n", __func__);
477		/* XXX KDM now what? */
478		return;
479	}
480
481	ctsio = &msg_info->hdr.original_sc->scsiio;
482	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
483	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
484	ctsio->io_hdr.status = msg_info->hdr.status;
485	ctsio->scsi_status = msg_info->scsi.scsi_status;
486	ctsio->sense_len = msg_info->scsi.sense_len;
487	ctsio->sense_residual = msg_info->scsi.sense_residual;
488	ctsio->residual = msg_info->scsi.residual;
489	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
490	       sizeof(ctsio->sense_data));
491	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
492	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
493	STAILQ_INSERT_TAIL(&ctl_softc->isc_queue, &ctsio->io_hdr, links);
494	ctl_wakeup_thread();
495}
496
497static void
498ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
499				union ctl_ha_msg *msg_info)
500{
501	struct ctl_scsiio *ctsio;
502
503	if (msg_info->hdr.serializing_sc == NULL) {
504		printf("%s: serializing_sc == NULL!\n", __func__);
505		/* XXX KDM now what? */
506		return;
507	}
508
509	ctsio = &msg_info->hdr.serializing_sc->scsiio;
510#if 0
511	/*
512	 * Attempt to catch the situation where an I/O has
513	 * been freed, and we're using it again.
514	 */
515	if (ctsio->io_hdr.io_type == 0xff) {
516		union ctl_io *tmp_io;
517		tmp_io = (union ctl_io *)ctsio;
518		printf("%s: %p use after free!\n", __func__,
519		       ctsio);
520		printf("%s: type %d msg %d cdb %x iptl: "
521		       "%d:%d:%d:%d tag 0x%04x "
522		       "flag %#x status %x\n",
523			__func__,
524			tmp_io->io_hdr.io_type,
525			tmp_io->io_hdr.msg_type,
526			tmp_io->scsiio.cdb[0],
527			tmp_io->io_hdr.nexus.initid.id,
528			tmp_io->io_hdr.nexus.targ_port,
529			tmp_io->io_hdr.nexus.targ_target.id,
530			tmp_io->io_hdr.nexus.targ_lun,
531			(tmp_io->io_hdr.io_type ==
532			CTL_IO_TASK) ?
533			tmp_io->taskio.tag_num :
534			tmp_io->scsiio.tag_num,
535		        tmp_io->io_hdr.flags,
536			tmp_io->io_hdr.status);
537	}
538#endif
539	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
540	STAILQ_INSERT_TAIL(&ctl_softc->isc_queue, &ctsio->io_hdr, links);
541	ctl_wakeup_thread();
542}
543
544/*
545 * ISC (Inter Shelf Communication) event handler.  Events from the HA
546 * subsystem come in here.
547 */
548static void
549ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
550{
551	struct ctl_softc *ctl_softc;
552	union ctl_io *io;
553	struct ctl_prio *presio;
554	ctl_ha_status isc_status;
555
556	ctl_softc = control_softc;
557	io = NULL;
558
559
560#if 0
561	printf("CTL: Isc Msg event %d\n", event);
562#endif
563	if (event == CTL_HA_EVT_MSG_RECV) {
564		union ctl_ha_msg msg_info;
565
566		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
567					     sizeof(msg_info), /*wait*/ 0);
568#if 0
569		printf("CTL: msg_type %d\n", msg_info.msg_type);
570#endif
571		if (isc_status != 0) {
572			printf("Error receiving message, status = %d\n",
573			       isc_status);
574			return;
575		}
576		mtx_lock(&ctl_softc->ctl_lock);
577
578		switch (msg_info.hdr.msg_type) {
579		case CTL_MSG_SERIALIZE:
580#if 0
581			printf("Serialize\n");
582#endif
583			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
584			if (io == NULL) {
585				printf("ctl_isc_event_handler: can't allocate "
586				       "ctl_io!\n");
587				/* Bad Juju */
588				/* Need to set busy and send msg back */
589				mtx_unlock(&ctl_softc->ctl_lock);
590				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
591				msg_info.hdr.status = CTL_SCSI_ERROR;
592				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
593				msg_info.scsi.sense_len = 0;
594			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
595				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
596				}
597				goto bailout;
598			}
599			ctl_zero_io(io);
600			// populate ctsio from msg_info
601			io->io_hdr.io_type = CTL_IO_SCSI;
602			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
603			io->io_hdr.original_sc = msg_info.hdr.original_sc;
604#if 0
605			printf("pOrig %x\n", (int)msg_info.original_sc);
606#endif
607			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
608					    CTL_FLAG_IO_ACTIVE;
609			/*
610			 * If we're in serialization-only mode, we don't
611			 * want to go through full done processing.  Thus
612			 * the COPY flag.
613			 *
614			 * XXX KDM add another flag that is more specific.
615			 */
616			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
617				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
618			io->io_hdr.nexus = msg_info.hdr.nexus;
619#if 0
620			printf("targ %d, port %d, iid %d, lun %d\n",
621			       io->io_hdr.nexus.targ_target.id,
622			       io->io_hdr.nexus.targ_port,
623			       io->io_hdr.nexus.initid.id,
624			       io->io_hdr.nexus.targ_lun);
625#endif
626			io->scsiio.tag_num = msg_info.scsi.tag_num;
627			io->scsiio.tag_type = msg_info.scsi.tag_type;
628			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
629			       CTL_MAX_CDBLEN);
630			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
631				struct ctl_cmd_entry *entry;
632				uint8_t opcode;
633
634				opcode = io->scsiio.cdb[0];
635				entry = &ctl_cmd_table[opcode];
636				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
637				io->io_hdr.flags |=
638					entry->flags & CTL_FLAG_DATA_MASK;
639			}
640			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
641					   &io->io_hdr, links);
642			ctl_wakeup_thread();
643			break;
644
645		/* Performed on the Originating SC, XFER mode only */
646		case CTL_MSG_DATAMOVE: {
647			struct ctl_sg_entry *sgl;
648			int i, j;
649
650			io = msg_info.hdr.original_sc;
651			if (io == NULL) {
652				printf("%s: original_sc == NULL!\n", __func__);
653				/* XXX KDM do something here */
654				break;
655			}
656			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
657			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
658			/*
659			 * Keep track of this, we need to send it back over
660			 * when the datamove is complete.
661			 */
662			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
663
664			if (msg_info.dt.sg_sequence == 0) {
665				/*
666				 * XXX KDM we use the preallocated S/G list
667				 * here, but we'll need to change this to
668				 * dynamic allocation if we need larger S/G
669				 * lists.
670				 */
671				if (msg_info.dt.kern_sg_entries >
672				    sizeof(io->io_hdr.remote_sglist) /
673				    sizeof(io->io_hdr.remote_sglist[0])) {
674					printf("%s: number of S/G entries "
675					    "needed %u > allocated num %zd\n",
676					    __func__,
677					    msg_info.dt.kern_sg_entries,
678					    sizeof(io->io_hdr.remote_sglist)/
679					    sizeof(io->io_hdr.remote_sglist[0]));
680
681					/*
682					 * XXX KDM send a message back to
683					 * the other side to shut down the
684					 * DMA.  The error will come back
685					 * through via the normal channel.
686					 */
687					break;
688				}
689				sgl = io->io_hdr.remote_sglist;
690				memset(sgl, 0,
691				       sizeof(io->io_hdr.remote_sglist));
692
693				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
694
695				io->scsiio.kern_sg_entries =
696					msg_info.dt.kern_sg_entries;
697				io->scsiio.rem_sg_entries =
698					msg_info.dt.kern_sg_entries;
699				io->scsiio.kern_data_len =
700					msg_info.dt.kern_data_len;
701				io->scsiio.kern_total_len =
702					msg_info.dt.kern_total_len;
703				io->scsiio.kern_data_resid =
704					msg_info.dt.kern_data_resid;
705				io->scsiio.kern_rel_offset =
706					msg_info.dt.kern_rel_offset;
707				/*
708				 * Clear out per-DMA flags.
709				 */
710				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
711				/*
712				 * Add per-DMA flags that are set for this
713				 * particular DMA request.
714				 */
715				io->io_hdr.flags |= msg_info.dt.flags &
716						    CTL_FLAG_RDMA_MASK;
717			} else
718				sgl = (struct ctl_sg_entry *)
719					io->scsiio.kern_data_ptr;
720
721			for (i = msg_info.dt.sent_sg_entries, j = 0;
722			     i < (msg_info.dt.sent_sg_entries +
723			     msg_info.dt.cur_sg_entries); i++, j++) {
724				sgl[i].addr = msg_info.dt.sg_list[j].addr;
725				sgl[i].len = msg_info.dt.sg_list[j].len;
726
727#if 0
728				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
729				       __func__,
730				       msg_info.dt.sg_list[j].addr,
731				       msg_info.dt.sg_list[j].len,
732				       sgl[i].addr, sgl[i].len, j, i);
733#endif
734			}
735#if 0
736			memcpy(&sgl[msg_info.dt.sent_sg_entries],
737			       msg_info.dt.sg_list,
738			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
739#endif
740
741			/*
742			 * If this is the last piece of the I/O, we've got
743			 * the full S/G list.  Queue processing in the thread.
744			 * Otherwise wait for the next piece.
745			 */
746			if (msg_info.dt.sg_last != 0) {
747				STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
748						   &io->io_hdr, links);
749				ctl_wakeup_thread();
750			}
751			break;
752		}
753		/* Performed on the Serializing (primary) SC, XFER mode only */
754		case CTL_MSG_DATAMOVE_DONE: {
755			if (msg_info.hdr.serializing_sc == NULL) {
756				printf("%s: serializing_sc == NULL!\n",
757				       __func__);
758				/* XXX KDM now what? */
759				break;
760			}
761			/*
762			 * We grab the sense information here in case
763			 * there was a failure, so we can return status
764			 * back to the initiator.
765			 */
766			io = msg_info.hdr.serializing_sc;
767			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
768			io->io_hdr.status = msg_info.hdr.status;
769			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
770			io->scsiio.sense_len = msg_info.scsi.sense_len;
771			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
772			io->io_hdr.port_status = msg_info.scsi.fetd_status;
773			io->scsiio.residual = msg_info.scsi.residual;
774			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
775			       sizeof(io->scsiio.sense_data));
776
777			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
778					   &io->io_hdr, links);
779			ctl_wakeup_thread();
780			break;
781		}
782
783		/* Preformed on Originating SC, SER_ONLY mode */
784		case CTL_MSG_R2R:
785			io = msg_info.hdr.original_sc;
786			if (io == NULL) {
787				printf("%s: Major Bummer\n", __func__);
788				mtx_unlock(&ctl_softc->ctl_lock);
789				return;
790			} else {
791#if 0
792				printf("pOrig %x\n",(int) ctsio);
793#endif
794			}
795			io->io_hdr.msg_type = CTL_MSG_R2R;
796			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
797			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
798					   &io->io_hdr, links);
799			ctl_wakeup_thread();
800			break;
801
802		/*
803		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
804		 * mode.
805		 * Performed on the Originating (i.e. secondary) SC in XFER
806		 * mode
807		 */
808		case CTL_MSG_FINISH_IO:
809			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
810				ctl_isc_handler_finish_xfer(ctl_softc,
811							    &msg_info);
812			else
813				ctl_isc_handler_finish_ser_only(ctl_softc,
814								&msg_info);
815			break;
816
817		/* Preformed on Originating SC */
818		case CTL_MSG_BAD_JUJU:
819			io = msg_info.hdr.original_sc;
820			if (io == NULL) {
821				printf("%s: Bad JUJU!, original_sc is NULL!\n",
822				       __func__);
823				break;
824			}
825			ctl_copy_sense_data(&msg_info, io);
826			/*
827			 * IO should have already been cleaned up on other
828			 * SC so clear this flag so we won't send a message
829			 * back to finish the IO there.
830			 */
831			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
832			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
833
834			/* io = msg_info.hdr.serializing_sc; */
835			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
836		        STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
837					   &io->io_hdr, links);
838			ctl_wakeup_thread();
839			break;
840
841		/* Handle resets sent from the other side */
842		case CTL_MSG_MANAGE_TASKS: {
843			struct ctl_taskio *taskio;
844			taskio = (struct ctl_taskio *)ctl_alloc_io(
845				(void *)ctl_softc->othersc_pool);
846			if (taskio == NULL) {
847				printf("ctl_isc_event_handler: can't allocate "
848				       "ctl_io!\n");
849				/* Bad Juju */
850				/* should I just call the proper reset func
851				   here??? */
852				mtx_unlock(&ctl_softc->ctl_lock);
853				goto bailout;
854			}
855			ctl_zero_io((union ctl_io *)taskio);
856			taskio->io_hdr.io_type = CTL_IO_TASK;
857			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
858			taskio->io_hdr.nexus = msg_info.hdr.nexus;
859			taskio->task_action = msg_info.task.task_action;
860			taskio->tag_num = msg_info.task.tag_num;
861			taskio->tag_type = msg_info.task.tag_type;
862#ifdef CTL_TIME_IO
863			taskio->io_hdr.start_time = time_uptime;
864			getbintime(&taskio->io_hdr.start_bt);
865#if 0
866			cs_prof_gettime(&taskio->io_hdr.start_ticks);
867#endif
868#endif /* CTL_TIME_IO */
869		        STAILQ_INSERT_TAIL(&ctl_softc->task_queue,
870					   &taskio->io_hdr, links);
871			ctl_softc->flags |= CTL_FLAG_TASK_PENDING;
872			ctl_wakeup_thread();
873			break;
874		}
875		/* Persistent Reserve action which needs attention */
876		case CTL_MSG_PERS_ACTION:
877			presio = (struct ctl_prio *)ctl_alloc_io(
878				(void *)ctl_softc->othersc_pool);
879			if (presio == NULL) {
880				printf("ctl_isc_event_handler: can't allocate "
881				       "ctl_io!\n");
882				/* Bad Juju */
883				/* Need to set busy and send msg back */
884				mtx_unlock(&ctl_softc->ctl_lock);
885				goto bailout;
886			}
887			ctl_zero_io((union ctl_io *)presio);
888			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
889			presio->pr_msg = msg_info.pr;
890		        STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
891					   &presio->io_hdr, links);
892			ctl_wakeup_thread();
893			break;
894		case CTL_MSG_SYNC_FE:
895			rcv_sync_msg = 1;
896			break;
897		case CTL_MSG_APS_LOCK: {
898			// It's quicker to execute this then to
899			// queue it.
900			struct ctl_lun *lun;
901			struct ctl_page_index *page_index;
902			struct copan_aps_subpage *current_sp;
903			uint32_t targ_lun;
904
905			targ_lun = msg_info.hdr.nexus.targ_lun;
906			if (msg_info.hdr.nexus.lun_map_fn != NULL)
907				targ_lun = msg_info.hdr.nexus.lun_map_fn(msg_info.hdr.nexus.lun_map_arg, targ_lun);
908
909			lun = ctl_softc->ctl_luns[targ_lun];
910			page_index = &lun->mode_pages.index[index_to_aps_page];
911			current_sp = (struct copan_aps_subpage *)
912				     (page_index->page_data +
913				     (page_index->page_len * CTL_PAGE_CURRENT));
914
915			current_sp->lock_active = msg_info.aps.lock_flag;
916		        break;
917		}
918		default:
919		        printf("How did I get here?\n");
920		}
921		mtx_unlock(&ctl_softc->ctl_lock);
922	} else if (event == CTL_HA_EVT_MSG_SENT) {
923		if (param != CTL_HA_STATUS_SUCCESS) {
924			printf("Bad status from ctl_ha_msg_send status %d\n",
925			       param);
926		}
927		return;
928	} else if (event == CTL_HA_EVT_DISCONNECT) {
929		printf("CTL: Got a disconnect from Isc\n");
930		return;
931	} else {
932		printf("ctl_isc_event_handler: Unknown event %d\n", event);
933		return;
934	}
935
936bailout:
937	return;
938}
939
940static void
941ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
942{
943	struct scsi_sense_data *sense;
944
945	sense = &dest->scsiio.sense_data;
946	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
947	dest->scsiio.scsi_status = src->scsi.scsi_status;
948	dest->scsiio.sense_len = src->scsi.sense_len;
949	dest->io_hdr.status = src->hdr.status;
950}
951
952static int
953ctl_init(void)
954{
955	struct ctl_softc *softc;
956	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
957	struct ctl_frontend *fe;
958        uint8_t sc_id =0;
959	int i, error, retval;
960	//int isc_retval;
961
962	retval = 0;
963	ctl_pause_rtr = 0;
964        rcv_sync_msg = 0;
965
966	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
967			       M_WAITOK | M_ZERO);
968	softc = control_softc;
969
970	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
971			      "cam/ctl");
972
973	softc->dev->si_drv1 = softc;
974
975	/*
976	 * By default, return a "bad LUN" peripheral qualifier for unknown
977	 * LUNs.  The user can override this default using the tunable or
978	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
979	 */
980	softc->inquiry_pq_no_lun = 1;
981	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
982			  &softc->inquiry_pq_no_lun);
983	sysctl_ctx_init(&softc->sysctl_ctx);
984	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
985		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
986		CTLFLAG_RD, 0, "CAM Target Layer");
987
988	if (softc->sysctl_tree == NULL) {
989		printf("%s: unable to allocate sysctl tree\n", __func__);
990		destroy_dev(softc->dev);
991		free(control_softc, M_DEVBUF);
992		control_softc = NULL;
993		return (ENOMEM);
994	}
995
996	SYSCTL_ADD_INT(&softc->sysctl_ctx,
997		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
998		       "inquiry_pq_no_lun", CTLFLAG_RW,
999		       &softc->inquiry_pq_no_lun, 0,
1000		       "Report no lun possible for invalid LUNs");
1001
1002	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1003	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
1004	softc->open_count = 0;
1005
1006	/*
1007	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1008	 * the drive.
1009	 */
1010	softc->flags = CTL_FLAG_REAL_SYNC;
1011
1012	/*
1013	 * In Copan's HA scheme, the "master" and "slave" roles are
1014	 * figured out through the slot the controller is in.  Although it
1015	 * is an active/active system, someone has to be in charge.
1016 	 */
1017#ifdef NEEDTOPORT
1018        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1019#endif
1020
1021        if (sc_id == 0) {
1022		softc->flags |= CTL_FLAG_MASTER_SHELF;
1023		persis_offset = 0;
1024	} else
1025		persis_offset = CTL_MAX_INITIATORS;
1026
1027	/*
1028	 * XXX KDM need to figure out where we want to get our target ID
1029	 * and WWID.  Is it different on each port?
1030	 */
1031	softc->target.id = 0;
1032	softc->target.wwid[0] = 0x12345678;
1033	softc->target.wwid[1] = 0x87654321;
1034	STAILQ_INIT(&softc->lun_list);
1035	STAILQ_INIT(&softc->pending_lun_queue);
1036	STAILQ_INIT(&softc->task_queue);
1037	STAILQ_INIT(&softc->incoming_queue);
1038	STAILQ_INIT(&softc->rtr_queue);
1039	STAILQ_INIT(&softc->done_queue);
1040	STAILQ_INIT(&softc->isc_queue);
1041	STAILQ_INIT(&softc->fe_list);
1042	STAILQ_INIT(&softc->be_list);
1043	STAILQ_INIT(&softc->io_pools);
1044
1045	/*
1046	 * We don't bother calling these with ctl_lock held here, because,
1047	 * in theory, no one else can try to do anything while we're in our
1048	 * module init routine.
1049	 */
1050	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1051			    &internal_pool)!= 0){
1052		printf("ctl: can't allocate %d entry internal pool, "
1053		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1054		return (ENOMEM);
1055	}
1056
1057	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1058			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1059		printf("ctl: can't allocate %d entry emergency pool, "
1060		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1061		ctl_pool_free(internal_pool);
1062		return (ENOMEM);
1063	}
1064
1065	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1066	                    &other_pool) != 0)
1067	{
1068		printf("ctl: can't allocate %d entry other SC pool, "
1069		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1070		ctl_pool_free(internal_pool);
1071		ctl_pool_free(emergency_pool);
1072		return (ENOMEM);
1073	}
1074
1075	softc->internal_pool = internal_pool;
1076	softc->emergency_pool = emergency_pool;
1077	softc->othersc_pool = other_pool;
1078
1079	if (worker_threads > MAXCPU || worker_threads == 0) {
1080		printf("invalid kern.cam.ctl.worker_threads value; "
1081		    "setting to 1");
1082		worker_threads = 1;
1083	} else if (worker_threads < 0) {
1084		if (mp_ncpus > 2) {
1085			/*
1086			 * Using more than two worker threads actually hurts
1087			 * performance due to lock contention.
1088			 */
1089			worker_threads = 2;
1090		} else {
1091			worker_threads = 1;
1092		}
1093	}
1094
1095	for (i = 0; i < worker_threads; i++) {
1096		error = kproc_kthread_add(ctl_work_thread, softc,
1097		    &softc->work_thread, NULL, 0, 0, "ctl", "work%d", i);
1098		if (error != 0) {
1099			printf("error creating CTL work thread!\n");
1100			ctl_pool_free(internal_pool);
1101			ctl_pool_free(emergency_pool);
1102			ctl_pool_free(other_pool);
1103			return (error);
1104		}
1105	}
1106	if (bootverbose)
1107		printf("ctl: CAM Target Layer loaded\n");
1108
1109	/*
1110	 * Initialize the initiator and portname mappings
1111	 */
1112	memset(softc->wwpn_iid, 0, sizeof(softc->wwpn_iid));
1113
1114	/*
1115	 * Initialize the ioctl front end.
1116	 */
1117	fe = &softc->ioctl_info.fe;
1118	sprintf(softc->ioctl_info.port_name, "CTL ioctl");
1119	fe->port_type = CTL_PORT_IOCTL;
1120	fe->num_requested_ctl_io = 100;
1121	fe->port_name = softc->ioctl_info.port_name;
1122	fe->port_online = ctl_ioctl_online;
1123	fe->port_offline = ctl_ioctl_offline;
1124	fe->onoff_arg = &softc->ioctl_info;
1125	fe->targ_enable = ctl_ioctl_targ_enable;
1126	fe->targ_disable = ctl_ioctl_targ_disable;
1127	fe->lun_enable = ctl_ioctl_lun_enable;
1128	fe->lun_disable = ctl_ioctl_lun_disable;
1129	fe->targ_lun_arg = &softc->ioctl_info;
1130	fe->fe_datamove = ctl_ioctl_datamove;
1131	fe->fe_done = ctl_ioctl_done;
1132	fe->max_targets = 15;
1133	fe->max_target_id = 15;
1134
1135	if (ctl_frontend_register(&softc->ioctl_info.fe,
1136	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1137		printf("ctl: ioctl front end registration failed, will "
1138		       "continue anyway\n");
1139	}
1140
1141#ifdef CTL_IO_DELAY
1142	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1143		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1144		       sizeof(struct callout), CTL_TIMER_BYTES);
1145		return (EINVAL);
1146	}
1147#endif /* CTL_IO_DELAY */
1148
1149	return (0);
1150}
1151
1152void
1153ctl_shutdown(void)
1154{
1155	struct ctl_softc *softc;
1156	struct ctl_lun *lun, *next_lun;
1157	struct ctl_io_pool *pool;
1158
1159	softc = (struct ctl_softc *)control_softc;
1160
1161	if (ctl_frontend_deregister(&softc->ioctl_info.fe) != 0)
1162		printf("ctl: ioctl front end deregistration failed\n");
1163
1164	mtx_lock(&softc->ctl_lock);
1165
1166	/*
1167	 * Free up each LUN.
1168	 */
1169	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1170		next_lun = STAILQ_NEXT(lun, links);
1171		ctl_free_lun(lun);
1172	}
1173
1174	mtx_unlock(&softc->ctl_lock);
1175
1176	/*
1177	 * This will rip the rug out from under any FETDs or anyone else
1178	 * that has a pool allocated.  Since we increment our module
1179	 * refcount any time someone outside the main CTL module allocates
1180	 * a pool, we shouldn't have any problems here.  The user won't be
1181	 * able to unload the CTL module until client modules have
1182	 * successfully unloaded.
1183	 */
1184	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1185		ctl_pool_free(pool);
1186
1187#if 0
1188	ctl_shutdown_thread(softc->work_thread);
1189#endif
1190
1191	mtx_destroy(&softc->pool_lock);
1192	mtx_destroy(&softc->ctl_lock);
1193
1194	destroy_dev(softc->dev);
1195
1196	sysctl_ctx_free(&softc->sysctl_ctx);
1197
1198	free(control_softc, M_DEVBUF);
1199	control_softc = NULL;
1200
1201	if (bootverbose)
1202		printf("ctl: CAM Target Layer unloaded\n");
1203}
1204
1205static int
1206ctl_module_event_handler(module_t mod, int what, void *arg)
1207{
1208
1209	switch (what) {
1210	case MOD_LOAD:
1211		return (ctl_init());
1212	case MOD_UNLOAD:
1213		return (EBUSY);
1214	default:
1215		return (EOPNOTSUPP);
1216	}
1217}
1218
1219/*
1220 * XXX KDM should we do some access checks here?  Bump a reference count to
1221 * prevent a CTL module from being unloaded while someone has it open?
1222 */
1223static int
1224ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1225{
1226	return (0);
1227}
1228
1229static int
1230ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1231{
1232	return (0);
1233}
1234
1235int
1236ctl_port_enable(ctl_port_type port_type)
1237{
1238	struct ctl_softc *softc;
1239	struct ctl_frontend *fe;
1240
1241	if (ctl_is_single == 0) {
1242		union ctl_ha_msg msg_info;
1243		int isc_retval;
1244
1245#if 0
1246		printf("%s: HA mode, synchronizing frontend enable\n",
1247		        __func__);
1248#endif
1249		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1250	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1251		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1252			printf("Sync msg send error retval %d\n", isc_retval);
1253		}
1254		if (!rcv_sync_msg) {
1255			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1256			        sizeof(msg_info), 1);
1257		}
1258#if 0
1259        	printf("CTL:Frontend Enable\n");
1260	} else {
1261		printf("%s: single mode, skipping frontend synchronization\n",
1262		        __func__);
1263#endif
1264	}
1265
1266	softc = control_softc;
1267
1268	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1269		if (port_type & fe->port_type)
1270		{
1271#if 0
1272			printf("port %d\n", fe->targ_port);
1273#endif
1274			ctl_frontend_online(fe);
1275		}
1276	}
1277
1278	return (0);
1279}
1280
1281int
1282ctl_port_disable(ctl_port_type port_type)
1283{
1284	struct ctl_softc *softc;
1285	struct ctl_frontend *fe;
1286
1287	softc = control_softc;
1288
1289	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1290		if (port_type & fe->port_type)
1291			ctl_frontend_offline(fe);
1292	}
1293
1294	return (0);
1295}
1296
1297/*
1298 * Returns 0 for success, 1 for failure.
1299 * Currently the only failure mode is if there aren't enough entries
1300 * allocated.  So, in case of a failure, look at num_entries_dropped,
1301 * reallocate and try again.
1302 */
1303int
1304ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1305	      int *num_entries_filled, int *num_entries_dropped,
1306	      ctl_port_type port_type, int no_virtual)
1307{
1308	struct ctl_softc *softc;
1309	struct ctl_frontend *fe;
1310	int entries_dropped, entries_filled;
1311	int retval;
1312	int i;
1313
1314	softc = control_softc;
1315
1316	retval = 0;
1317	entries_filled = 0;
1318	entries_dropped = 0;
1319
1320	i = 0;
1321	mtx_lock(&softc->ctl_lock);
1322	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1323		struct ctl_port_entry *entry;
1324
1325		if ((fe->port_type & port_type) == 0)
1326			continue;
1327
1328		if ((no_virtual != 0)
1329		 && (fe->virtual_port != 0))
1330			continue;
1331
1332		if (entries_filled >= num_entries_alloced) {
1333			entries_dropped++;
1334			continue;
1335		}
1336		entry = &entries[i];
1337
1338		entry->port_type = fe->port_type;
1339		strlcpy(entry->port_name, fe->port_name,
1340			sizeof(entry->port_name));
1341		entry->physical_port = fe->physical_port;
1342		entry->virtual_port = fe->virtual_port;
1343		entry->wwnn = fe->wwnn;
1344		entry->wwpn = fe->wwpn;
1345
1346		i++;
1347		entries_filled++;
1348	}
1349
1350	mtx_unlock(&softc->ctl_lock);
1351
1352	if (entries_dropped > 0)
1353		retval = 1;
1354
1355	*num_entries_dropped = entries_dropped;
1356	*num_entries_filled = entries_filled;
1357
1358	return (retval);
1359}
1360
1361static void
1362ctl_ioctl_online(void *arg)
1363{
1364	struct ctl_ioctl_info *ioctl_info;
1365
1366	ioctl_info = (struct ctl_ioctl_info *)arg;
1367
1368	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1369}
1370
1371static void
1372ctl_ioctl_offline(void *arg)
1373{
1374	struct ctl_ioctl_info *ioctl_info;
1375
1376	ioctl_info = (struct ctl_ioctl_info *)arg;
1377
1378	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1379}
1380
1381/*
1382 * Remove an initiator by port number and initiator ID.
1383 * Returns 0 for success, 1 for failure.
1384 */
1385int
1386ctl_remove_initiator(int32_t targ_port, uint32_t iid)
1387{
1388	struct ctl_softc *softc;
1389
1390	softc = control_softc;
1391
1392	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1393
1394	if ((targ_port < 0)
1395	 || (targ_port > CTL_MAX_PORTS)) {
1396		printf("%s: invalid port number %d\n", __func__, targ_port);
1397		return (1);
1398	}
1399	if (iid > CTL_MAX_INIT_PER_PORT) {
1400		printf("%s: initiator ID %u > maximun %u!\n",
1401		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1402		return (1);
1403	}
1404
1405	mtx_lock(&softc->ctl_lock);
1406
1407	softc->wwpn_iid[targ_port][iid].in_use = 0;
1408
1409	mtx_unlock(&softc->ctl_lock);
1410
1411	return (0);
1412}
1413
1414/*
1415 * Add an initiator to the initiator map.
1416 * Returns 0 for success, 1 for failure.
1417 */
1418int
1419ctl_add_initiator(uint64_t wwpn, int32_t targ_port, uint32_t iid)
1420{
1421	struct ctl_softc *softc;
1422	int retval;
1423
1424	softc = control_softc;
1425
1426	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1427
1428	retval = 0;
1429
1430	if ((targ_port < 0)
1431	 || (targ_port > CTL_MAX_PORTS)) {
1432		printf("%s: invalid port number %d\n", __func__, targ_port);
1433		return (1);
1434	}
1435	if (iid > CTL_MAX_INIT_PER_PORT) {
1436		printf("%s: WWPN %#jx initiator ID %u > maximun %u!\n",
1437		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1438		return (1);
1439	}
1440
1441	mtx_lock(&softc->ctl_lock);
1442
1443	if (softc->wwpn_iid[targ_port][iid].in_use != 0) {
1444		/*
1445		 * We don't treat this as an error.
1446		 */
1447		if (softc->wwpn_iid[targ_port][iid].wwpn == wwpn) {
1448			printf("%s: port %d iid %u WWPN %#jx arrived again?\n",
1449			       __func__, targ_port, iid, (uintmax_t)wwpn);
1450			goto bailout;
1451		}
1452
1453		/*
1454		 * This is an error, but what do we do about it?  The
1455		 * driver is telling us we have a new WWPN for this
1456		 * initiator ID, so we pretty much need to use it.
1457		 */
1458		printf("%s: port %d iid %u WWPN %#jx arrived, WWPN %#jx is "
1459		       "still at that address\n", __func__, targ_port, iid,
1460		       (uintmax_t)wwpn,
1461		       (uintmax_t)softc->wwpn_iid[targ_port][iid].wwpn);
1462
1463		/*
1464		 * XXX KDM clear have_ca and ua_pending on each LUN for
1465		 * this initiator.
1466		 */
1467	}
1468	softc->wwpn_iid[targ_port][iid].in_use = 1;
1469	softc->wwpn_iid[targ_port][iid].iid = iid;
1470	softc->wwpn_iid[targ_port][iid].wwpn = wwpn;
1471	softc->wwpn_iid[targ_port][iid].port = targ_port;
1472
1473bailout:
1474
1475	mtx_unlock(&softc->ctl_lock);
1476
1477	return (retval);
1478}
1479
1480/*
1481 * XXX KDM should we pretend to do something in the target/lun
1482 * enable/disable functions?
1483 */
1484static int
1485ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id)
1486{
1487	return (0);
1488}
1489
1490static int
1491ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id)
1492{
1493	return (0);
1494}
1495
1496static int
1497ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1498{
1499	return (0);
1500}
1501
1502static int
1503ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1504{
1505	return (0);
1506}
1507
1508/*
1509 * Data movement routine for the CTL ioctl frontend port.
1510 */
1511static int
1512ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1513{
1514	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1515	struct ctl_sg_entry ext_entry, kern_entry;
1516	int ext_sglen, ext_sg_entries, kern_sg_entries;
1517	int ext_sg_start, ext_offset;
1518	int len_to_copy, len_copied;
1519	int kern_watermark, ext_watermark;
1520	int ext_sglist_malloced;
1521	int i, j;
1522
1523	ext_sglist_malloced = 0;
1524	ext_sg_start = 0;
1525	ext_offset = 0;
1526
1527	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1528
1529	/*
1530	 * If this flag is set, fake the data transfer.
1531	 */
1532	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1533		ctsio->ext_data_filled = ctsio->ext_data_len;
1534		goto bailout;
1535	}
1536
1537	/*
1538	 * To simplify things here, if we have a single buffer, stick it in
1539	 * a S/G entry and just make it a single entry S/G list.
1540	 */
1541	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1542		int len_seen;
1543
1544		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1545
1546		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1547							   M_WAITOK);
1548		ext_sglist_malloced = 1;
1549		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1550				   ext_sglen) != 0) {
1551			ctl_set_internal_failure(ctsio,
1552						 /*sks_valid*/ 0,
1553						 /*retry_count*/ 0);
1554			goto bailout;
1555		}
1556		ext_sg_entries = ctsio->ext_sg_entries;
1557		len_seen = 0;
1558		for (i = 0; i < ext_sg_entries; i++) {
1559			if ((len_seen + ext_sglist[i].len) >=
1560			     ctsio->ext_data_filled) {
1561				ext_sg_start = i;
1562				ext_offset = ctsio->ext_data_filled - len_seen;
1563				break;
1564			}
1565			len_seen += ext_sglist[i].len;
1566		}
1567	} else {
1568		ext_sglist = &ext_entry;
1569		ext_sglist->addr = ctsio->ext_data_ptr;
1570		ext_sglist->len = ctsio->ext_data_len;
1571		ext_sg_entries = 1;
1572		ext_sg_start = 0;
1573		ext_offset = ctsio->ext_data_filled;
1574	}
1575
1576	if (ctsio->kern_sg_entries > 0) {
1577		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1578		kern_sg_entries = ctsio->kern_sg_entries;
1579	} else {
1580		kern_sglist = &kern_entry;
1581		kern_sglist->addr = ctsio->kern_data_ptr;
1582		kern_sglist->len = ctsio->kern_data_len;
1583		kern_sg_entries = 1;
1584	}
1585
1586
1587	kern_watermark = 0;
1588	ext_watermark = ext_offset;
1589	len_copied = 0;
1590	for (i = ext_sg_start, j = 0;
1591	     i < ext_sg_entries && j < kern_sg_entries;) {
1592		uint8_t *ext_ptr, *kern_ptr;
1593
1594		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1595				      kern_sglist[j].len - kern_watermark);
1596
1597		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1598		ext_ptr = ext_ptr + ext_watermark;
1599		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1600			/*
1601			 * XXX KDM fix this!
1602			 */
1603			panic("need to implement bus address support");
1604#if 0
1605			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1606#endif
1607		} else
1608			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1609		kern_ptr = kern_ptr + kern_watermark;
1610
1611		kern_watermark += len_to_copy;
1612		ext_watermark += len_to_copy;
1613
1614		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1615		     CTL_FLAG_DATA_IN) {
1616			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1617					 "bytes to user\n", len_to_copy));
1618			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1619					 "to %p\n", kern_ptr, ext_ptr));
1620			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1621				ctl_set_internal_failure(ctsio,
1622							 /*sks_valid*/ 0,
1623							 /*retry_count*/ 0);
1624				goto bailout;
1625			}
1626		} else {
1627			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1628					 "bytes from user\n", len_to_copy));
1629			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1630					 "to %p\n", ext_ptr, kern_ptr));
1631			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1632				ctl_set_internal_failure(ctsio,
1633							 /*sks_valid*/ 0,
1634							 /*retry_count*/0);
1635				goto bailout;
1636			}
1637		}
1638
1639		len_copied += len_to_copy;
1640
1641		if (ext_sglist[i].len == ext_watermark) {
1642			i++;
1643			ext_watermark = 0;
1644		}
1645
1646		if (kern_sglist[j].len == kern_watermark) {
1647			j++;
1648			kern_watermark = 0;
1649		}
1650	}
1651
1652	ctsio->ext_data_filled += len_copied;
1653
1654	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1655			 "kern_sg_entries: %d\n", ext_sg_entries,
1656			 kern_sg_entries));
1657	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1658			 "kern_data_len = %d\n", ctsio->ext_data_len,
1659			 ctsio->kern_data_len));
1660
1661
1662	/* XXX KDM set residual?? */
1663bailout:
1664
1665	if (ext_sglist_malloced != 0)
1666		free(ext_sglist, M_CTL);
1667
1668	return (CTL_RETVAL_COMPLETE);
1669}
1670
1671/*
1672 * Serialize a command that went down the "wrong" side, and so was sent to
1673 * this controller for execution.  The logic is a little different than the
1674 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1675 * sent back to the other side, but in the success case, we execute the
1676 * command on this side (XFER mode) or tell the other side to execute it
1677 * (SER_ONLY mode).
1678 */
1679static int
1680ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio, int have_lock)
1681{
1682	struct ctl_softc *ctl_softc;
1683	union ctl_ha_msg msg_info;
1684	struct ctl_lun *lun;
1685	int retval = 0;
1686	uint32_t targ_lun;
1687
1688	ctl_softc = control_softc;
1689	if (have_lock == 0)
1690		mtx_lock(&ctl_softc->ctl_lock);
1691
1692	targ_lun = ctsio->io_hdr.nexus.targ_lun;
1693	if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
1694		targ_lun = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, targ_lun);
1695	lun = ctl_softc->ctl_luns[targ_lun];
1696	if (lun==NULL)
1697	{
1698		/*
1699		 * Why isn't LUN defined? The other side wouldn't
1700		 * send a cmd if the LUN is undefined.
1701		 */
1702		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1703
1704		/* "Logical unit not supported" */
1705		ctl_set_sense_data(&msg_info.scsi.sense_data,
1706				   lun,
1707				   /*sense_format*/SSD_TYPE_NONE,
1708				   /*current_error*/ 1,
1709				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1710				   /*asc*/ 0x25,
1711				   /*ascq*/ 0x00,
1712				   SSD_ELEM_NONE);
1713
1714		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1715		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1716		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1717		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1718		msg_info.hdr.serializing_sc = NULL;
1719		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1720	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1721				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1722		}
1723		if (have_lock == 0)
1724			mtx_unlock(&ctl_softc->ctl_lock);
1725		return(1);
1726
1727	}
1728
1729    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1730
1731	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1732		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1733		 ooa_links))) {
1734	case CTL_ACTION_BLOCK:
1735		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1736		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1737				  blocked_links);
1738		break;
1739	case CTL_ACTION_PASS:
1740	case CTL_ACTION_SKIP:
1741		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1742			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1743			STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
1744					   &ctsio->io_hdr, links);
1745		} else {
1746
1747			/* send msg back to other side */
1748			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1749			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1750			msg_info.hdr.msg_type = CTL_MSG_R2R;
1751#if 0
1752			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1753#endif
1754		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1755			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1756			}
1757		}
1758		break;
1759	case CTL_ACTION_OVERLAP:
1760		/* OVERLAPPED COMMANDS ATTEMPTED */
1761		ctl_set_sense_data(&msg_info.scsi.sense_data,
1762				   lun,
1763				   /*sense_format*/SSD_TYPE_NONE,
1764				   /*current_error*/ 1,
1765				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1766				   /*asc*/ 0x4E,
1767				   /*ascq*/ 0x00,
1768				   SSD_ELEM_NONE);
1769
1770		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1771		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1772		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1773		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1774		msg_info.hdr.serializing_sc = NULL;
1775		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1776#if 0
1777		printf("BAD JUJU:Major Bummer Overlap\n");
1778#endif
1779		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1780		retval = 1;
1781		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1782		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1783		}
1784		break;
1785	case CTL_ACTION_OVERLAP_TAG:
1786		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1787		ctl_set_sense_data(&msg_info.scsi.sense_data,
1788				   lun,
1789				   /*sense_format*/SSD_TYPE_NONE,
1790				   /*current_error*/ 1,
1791				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1792				   /*asc*/ 0x4D,
1793				   /*ascq*/ ctsio->tag_num & 0xff,
1794				   SSD_ELEM_NONE);
1795
1796		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1797		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1798		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1799		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1800		msg_info.hdr.serializing_sc = NULL;
1801		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1802#if 0
1803		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1804#endif
1805		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1806		retval = 1;
1807		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1808		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1809		}
1810		break;
1811	case CTL_ACTION_ERROR:
1812	default:
1813		/* "Internal target failure" */
1814		ctl_set_sense_data(&msg_info.scsi.sense_data,
1815				   lun,
1816				   /*sense_format*/SSD_TYPE_NONE,
1817				   /*current_error*/ 1,
1818				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1819				   /*asc*/ 0x44,
1820				   /*ascq*/ 0x00,
1821				   SSD_ELEM_NONE);
1822
1823		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1824		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1825		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1826		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1827		msg_info.hdr.serializing_sc = NULL;
1828		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1829#if 0
1830		printf("BAD JUJU:Major Bummer HW Error\n");
1831#endif
1832		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1833		retval = 1;
1834		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1835		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1836		}
1837		break;
1838	}
1839	if (have_lock == 0)
1840		mtx_unlock(&ctl_softc->ctl_lock);
1841	return (retval);
1842}
1843
1844static int
1845ctl_ioctl_submit_wait(union ctl_io *io)
1846{
1847	struct ctl_fe_ioctl_params params;
1848	ctl_fe_ioctl_state last_state;
1849	int done, retval;
1850
1851	retval = 0;
1852
1853	bzero(&params, sizeof(params));
1854
1855	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1856	cv_init(&params.sem, "ctlioccv");
1857	params.state = CTL_IOCTL_INPROG;
1858	last_state = params.state;
1859
1860	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1861
1862	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1863
1864	/* This shouldn't happen */
1865	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1866		return (retval);
1867
1868	done = 0;
1869
1870	do {
1871		mtx_lock(&params.ioctl_mtx);
1872		/*
1873		 * Check the state here, and don't sleep if the state has
1874		 * already changed (i.e. wakeup has already occured, but we
1875		 * weren't waiting yet).
1876		 */
1877		if (params.state == last_state) {
1878			/* XXX KDM cv_wait_sig instead? */
1879			cv_wait(&params.sem, &params.ioctl_mtx);
1880		}
1881		last_state = params.state;
1882
1883		switch (params.state) {
1884		case CTL_IOCTL_INPROG:
1885			/* Why did we wake up? */
1886			/* XXX KDM error here? */
1887			mtx_unlock(&params.ioctl_mtx);
1888			break;
1889		case CTL_IOCTL_DATAMOVE:
1890			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1891
1892			/*
1893			 * change last_state back to INPROG to avoid
1894			 * deadlock on subsequent data moves.
1895			 */
1896			params.state = last_state = CTL_IOCTL_INPROG;
1897
1898			mtx_unlock(&params.ioctl_mtx);
1899			ctl_ioctl_do_datamove(&io->scsiio);
1900			/*
1901			 * Note that in some cases, most notably writes,
1902			 * this will queue the I/O and call us back later.
1903			 * In other cases, generally reads, this routine
1904			 * will immediately call back and wake us up,
1905			 * probably using our own context.
1906			 */
1907			io->scsiio.be_move_done(io);
1908			break;
1909		case CTL_IOCTL_DONE:
1910			mtx_unlock(&params.ioctl_mtx);
1911			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1912			done = 1;
1913			break;
1914		default:
1915			mtx_unlock(&params.ioctl_mtx);
1916			/* XXX KDM error here? */
1917			break;
1918		}
1919	} while (done == 0);
1920
1921	mtx_destroy(&params.ioctl_mtx);
1922	cv_destroy(&params.sem);
1923
1924	return (CTL_RETVAL_COMPLETE);
1925}
1926
1927static void
1928ctl_ioctl_datamove(union ctl_io *io)
1929{
1930	struct ctl_fe_ioctl_params *params;
1931
1932	params = (struct ctl_fe_ioctl_params *)
1933		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1934
1935	mtx_lock(&params->ioctl_mtx);
1936	params->state = CTL_IOCTL_DATAMOVE;
1937	cv_broadcast(&params->sem);
1938	mtx_unlock(&params->ioctl_mtx);
1939}
1940
1941static void
1942ctl_ioctl_done(union ctl_io *io)
1943{
1944	struct ctl_fe_ioctl_params *params;
1945
1946	params = (struct ctl_fe_ioctl_params *)
1947		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1948
1949	mtx_lock(&params->ioctl_mtx);
1950	params->state = CTL_IOCTL_DONE;
1951	cv_broadcast(&params->sem);
1952	mtx_unlock(&params->ioctl_mtx);
1953}
1954
1955static void
1956ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
1957{
1958	struct ctl_fe_ioctl_startstop_info *sd_info;
1959
1960	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
1961
1962	sd_info->hs_info.status = metatask->status;
1963	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
1964	sd_info->hs_info.luns_complete =
1965		metatask->taskinfo.startstop.luns_complete;
1966	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
1967
1968	cv_broadcast(&sd_info->sem);
1969}
1970
1971static void
1972ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
1973{
1974	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
1975
1976	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
1977
1978	mtx_lock(fe_bbr_info->lock);
1979	fe_bbr_info->bbr_info->status = metatask->status;
1980	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
1981	fe_bbr_info->wakeup_done = 1;
1982	mtx_unlock(fe_bbr_info->lock);
1983
1984	cv_broadcast(&fe_bbr_info->sem);
1985}
1986
1987/*
1988 * Returns 0 for success, errno for failure.
1989 */
1990static int
1991ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1992		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1993{
1994	union ctl_io *io;
1995	int retval;
1996
1997	retval = 0;
1998
1999	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
2000
2001	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2002	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2003	     ooa_links)) {
2004		struct ctl_ooa_entry *entry;
2005
2006		/*
2007		 * If we've got more than we can fit, just count the
2008		 * remaining entries.
2009		 */
2010		if (*cur_fill_num >= ooa_hdr->alloc_num)
2011			continue;
2012
2013		entry = &kern_entries[*cur_fill_num];
2014
2015		entry->tag_num = io->scsiio.tag_num;
2016		entry->lun_num = lun->lun;
2017#ifdef CTL_TIME_IO
2018		entry->start_bt = io->io_hdr.start_bt;
2019#endif
2020		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2021		entry->cdb_len = io->scsiio.cdb_len;
2022		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2023			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2024
2025		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2026			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2027
2028		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2029			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2030
2031		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2032			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2033
2034		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2035			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2036	}
2037
2038	return (retval);
2039}
2040
2041static void *
2042ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2043		 size_t error_str_len)
2044{
2045	void *kptr;
2046
2047	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2048
2049	if (copyin(user_addr, kptr, len) != 0) {
2050		snprintf(error_str, error_str_len, "Error copying %d bytes "
2051			 "from user address %p to kernel address %p", len,
2052			 user_addr, kptr);
2053		free(kptr, M_CTL);
2054		return (NULL);
2055	}
2056
2057	return (kptr);
2058}
2059
2060static void
2061ctl_free_args(int num_be_args, struct ctl_be_arg *be_args)
2062{
2063	int i;
2064
2065	if (be_args == NULL)
2066		return;
2067
2068	for (i = 0; i < num_be_args; i++) {
2069		free(be_args[i].kname, M_CTL);
2070		free(be_args[i].kvalue, M_CTL);
2071	}
2072
2073	free(be_args, M_CTL);
2074}
2075
2076static struct ctl_be_arg *
2077ctl_copyin_args(int num_be_args, struct ctl_be_arg *be_args,
2078		char *error_str, size_t error_str_len)
2079{
2080	struct ctl_be_arg *args;
2081	int i;
2082
2083	args = ctl_copyin_alloc(be_args, num_be_args * sizeof(*be_args),
2084				error_str, error_str_len);
2085
2086	if (args == NULL)
2087		goto bailout;
2088
2089	for (i = 0; i < num_be_args; i++) {
2090		args[i].kname = NULL;
2091		args[i].kvalue = NULL;
2092	}
2093
2094	for (i = 0; i < num_be_args; i++) {
2095		uint8_t *tmpptr;
2096
2097		args[i].kname = ctl_copyin_alloc(args[i].name,
2098			args[i].namelen, error_str, error_str_len);
2099		if (args[i].kname == NULL)
2100			goto bailout;
2101
2102		if (args[i].kname[args[i].namelen - 1] != '\0') {
2103			snprintf(error_str, error_str_len, "Argument %d "
2104				 "name is not NUL-terminated", i);
2105			goto bailout;
2106		}
2107
2108		args[i].kvalue = NULL;
2109
2110		tmpptr = ctl_copyin_alloc(args[i].value,
2111			args[i].vallen, error_str, error_str_len);
2112		if (tmpptr == NULL)
2113			goto bailout;
2114
2115		args[i].kvalue = tmpptr;
2116
2117		if ((args[i].flags & CTL_BEARG_ASCII)
2118		 && (tmpptr[args[i].vallen - 1] != '\0')) {
2119			snprintf(error_str, error_str_len, "Argument %d "
2120				 "value is not NUL-terminated", i);
2121			goto bailout;
2122		}
2123	}
2124
2125	return (args);
2126bailout:
2127
2128	ctl_free_args(num_be_args, args);
2129
2130	return (NULL);
2131}
2132
2133/*
2134 * Escape characters that are illegal or not recommended in XML.
2135 */
2136int
2137ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2138{
2139	int retval;
2140
2141	retval = 0;
2142
2143	for (; *str; str++) {
2144		switch (*str) {
2145		case '&':
2146			retval = sbuf_printf(sb, "&amp;");
2147			break;
2148		case '>':
2149			retval = sbuf_printf(sb, "&gt;");
2150			break;
2151		case '<':
2152			retval = sbuf_printf(sb, "&lt;");
2153			break;
2154		default:
2155			retval = sbuf_putc(sb, *str);
2156			break;
2157		}
2158
2159		if (retval != 0)
2160			break;
2161
2162	}
2163
2164	return (retval);
2165}
2166
2167static int
2168ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2169	  struct thread *td)
2170{
2171	struct ctl_softc *softc;
2172	int retval;
2173
2174	softc = control_softc;
2175
2176	retval = 0;
2177
2178	switch (cmd) {
2179	case CTL_IO: {
2180		union ctl_io *io;
2181		void *pool_tmp;
2182
2183		/*
2184		 * If we haven't been "enabled", don't allow any SCSI I/O
2185		 * to this FETD.
2186		 */
2187		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2188			retval = -EPERM;
2189			break;
2190		}
2191
2192		io = ctl_alloc_io(softc->ioctl_info.fe.ctl_pool_ref);
2193		if (io == NULL) {
2194			printf("ctl_ioctl: can't allocate ctl_io!\n");
2195			retval = -ENOSPC;
2196			break;
2197		}
2198
2199		/*
2200		 * Need to save the pool reference so it doesn't get
2201		 * spammed by the user's ctl_io.
2202		 */
2203		pool_tmp = io->io_hdr.pool;
2204
2205		memcpy(io, (void *)addr, sizeof(*io));
2206
2207		io->io_hdr.pool = pool_tmp;
2208		/*
2209		 * No status yet, so make sure the status is set properly.
2210		 */
2211		io->io_hdr.status = CTL_STATUS_NONE;
2212
2213		/*
2214		 * The user sets the initiator ID, target and LUN IDs.
2215		 */
2216		io->io_hdr.nexus.targ_port = softc->ioctl_info.fe.targ_port;
2217		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2218		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2219		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2220			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2221
2222		retval = ctl_ioctl_submit_wait(io);
2223
2224		if (retval != 0) {
2225			ctl_free_io(io);
2226			break;
2227		}
2228
2229		memcpy((void *)addr, io, sizeof(*io));
2230
2231		/* return this to our pool */
2232		ctl_free_io(io);
2233
2234		break;
2235	}
2236	case CTL_ENABLE_PORT:
2237	case CTL_DISABLE_PORT:
2238	case CTL_SET_PORT_WWNS: {
2239		struct ctl_frontend *fe;
2240		struct ctl_port_entry *entry;
2241
2242		entry = (struct ctl_port_entry *)addr;
2243
2244		mtx_lock(&softc->ctl_lock);
2245		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2246			int action, done;
2247
2248			action = 0;
2249			done = 0;
2250
2251			if ((entry->port_type == CTL_PORT_NONE)
2252			 && (entry->targ_port == fe->targ_port)) {
2253				/*
2254				 * If the user only wants to enable or
2255				 * disable or set WWNs on a specific port,
2256				 * do the operation and we're done.
2257				 */
2258				action = 1;
2259				done = 1;
2260			} else if (entry->port_type & fe->port_type) {
2261				/*
2262				 * Compare the user's type mask with the
2263				 * particular frontend type to see if we
2264				 * have a match.
2265				 */
2266				action = 1;
2267				done = 0;
2268
2269				/*
2270				 * Make sure the user isn't trying to set
2271				 * WWNs on multiple ports at the same time.
2272				 */
2273				if (cmd == CTL_SET_PORT_WWNS) {
2274					printf("%s: Can't set WWNs on "
2275					       "multiple ports\n", __func__);
2276					retval = EINVAL;
2277					break;
2278				}
2279			}
2280			if (action != 0) {
2281				/*
2282				 * XXX KDM we have to drop the lock here,
2283				 * because the online/offline operations
2284				 * can potentially block.  We need to
2285				 * reference count the frontends so they
2286				 * can't go away,
2287				 */
2288				mtx_unlock(&softc->ctl_lock);
2289
2290				if (cmd == CTL_ENABLE_PORT) {
2291					struct ctl_lun *lun;
2292
2293					STAILQ_FOREACH(lun, &softc->lun_list,
2294						       links) {
2295						fe->lun_enable(fe->targ_lun_arg,
2296						    lun->target,
2297						    lun->lun);
2298					}
2299
2300					ctl_frontend_online(fe);
2301				} else if (cmd == CTL_DISABLE_PORT) {
2302					struct ctl_lun *lun;
2303
2304					ctl_frontend_offline(fe);
2305
2306					STAILQ_FOREACH(lun, &softc->lun_list,
2307						       links) {
2308						fe->lun_disable(
2309						    fe->targ_lun_arg,
2310						    lun->target,
2311						    lun->lun);
2312					}
2313				}
2314
2315				mtx_lock(&softc->ctl_lock);
2316
2317				if (cmd == CTL_SET_PORT_WWNS)
2318					ctl_frontend_set_wwns(fe,
2319					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2320					    1 : 0, entry->wwnn,
2321					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2322					    1 : 0, entry->wwpn);
2323			}
2324			if (done != 0)
2325				break;
2326		}
2327		mtx_unlock(&softc->ctl_lock);
2328		break;
2329	}
2330	case CTL_GET_PORT_LIST: {
2331		struct ctl_frontend *fe;
2332		struct ctl_port_list *list;
2333		int i;
2334
2335		list = (struct ctl_port_list *)addr;
2336
2337		if (list->alloc_len != (list->alloc_num *
2338		    sizeof(struct ctl_port_entry))) {
2339			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2340			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2341			       "%zu\n", __func__, list->alloc_len,
2342			       list->alloc_num, sizeof(struct ctl_port_entry));
2343			retval = EINVAL;
2344			break;
2345		}
2346		list->fill_len = 0;
2347		list->fill_num = 0;
2348		list->dropped_num = 0;
2349		i = 0;
2350		mtx_lock(&softc->ctl_lock);
2351		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2352			struct ctl_port_entry entry, *list_entry;
2353
2354			if (list->fill_num >= list->alloc_num) {
2355				list->dropped_num++;
2356				continue;
2357			}
2358
2359			entry.port_type = fe->port_type;
2360			strlcpy(entry.port_name, fe->port_name,
2361				sizeof(entry.port_name));
2362			entry.targ_port = fe->targ_port;
2363			entry.physical_port = fe->physical_port;
2364			entry.virtual_port = fe->virtual_port;
2365			entry.wwnn = fe->wwnn;
2366			entry.wwpn = fe->wwpn;
2367			if (fe->status & CTL_PORT_STATUS_ONLINE)
2368				entry.online = 1;
2369			else
2370				entry.online = 0;
2371
2372			list_entry = &list->entries[i];
2373
2374			retval = copyout(&entry, list_entry, sizeof(entry));
2375			if (retval != 0) {
2376				printf("%s: CTL_GET_PORT_LIST: copyout "
2377				       "returned %d\n", __func__, retval);
2378				break;
2379			}
2380			i++;
2381			list->fill_num++;
2382			list->fill_len += sizeof(entry);
2383		}
2384		mtx_unlock(&softc->ctl_lock);
2385
2386		/*
2387		 * If this is non-zero, we had a copyout fault, so there's
2388		 * probably no point in attempting to set the status inside
2389		 * the structure.
2390		 */
2391		if (retval != 0)
2392			break;
2393
2394		if (list->dropped_num > 0)
2395			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2396		else
2397			list->status = CTL_PORT_LIST_OK;
2398		break;
2399	}
2400	case CTL_DUMP_OOA: {
2401		struct ctl_lun *lun;
2402		union ctl_io *io;
2403		char printbuf[128];
2404		struct sbuf sb;
2405
2406		mtx_lock(&softc->ctl_lock);
2407		printf("Dumping OOA queues:\n");
2408		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2409			for (io = (union ctl_io *)TAILQ_FIRST(
2410			     &lun->ooa_queue); io != NULL;
2411			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2412			     ooa_links)) {
2413				sbuf_new(&sb, printbuf, sizeof(printbuf),
2414					 SBUF_FIXEDLEN);
2415				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2416					    (intmax_t)lun->lun,
2417					    io->scsiio.tag_num,
2418					    (io->io_hdr.flags &
2419					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2420					    (io->io_hdr.flags &
2421					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2422					    (io->io_hdr.flags &
2423					    CTL_FLAG_ABORT) ? " ABORT" : "",
2424			                    (io->io_hdr.flags &
2425		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2426				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2427				sbuf_finish(&sb);
2428				printf("%s\n", sbuf_data(&sb));
2429			}
2430		}
2431		printf("OOA queues dump done\n");
2432		mtx_unlock(&softc->ctl_lock);
2433		break;
2434	}
2435	case CTL_GET_OOA: {
2436		struct ctl_lun *lun;
2437		struct ctl_ooa *ooa_hdr;
2438		struct ctl_ooa_entry *entries;
2439		uint32_t cur_fill_num;
2440
2441		ooa_hdr = (struct ctl_ooa *)addr;
2442
2443		if ((ooa_hdr->alloc_len == 0)
2444		 || (ooa_hdr->alloc_num == 0)) {
2445			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2446			       "must be non-zero\n", __func__,
2447			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2448			retval = EINVAL;
2449			break;
2450		}
2451
2452		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2453		    sizeof(struct ctl_ooa_entry))) {
2454			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2455			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2456			       __func__, ooa_hdr->alloc_len,
2457			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2458			retval = EINVAL;
2459			break;
2460		}
2461
2462		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2463		if (entries == NULL) {
2464			printf("%s: could not allocate %d bytes for OOA "
2465			       "dump\n", __func__, ooa_hdr->alloc_len);
2466			retval = ENOMEM;
2467			break;
2468		}
2469
2470		mtx_lock(&softc->ctl_lock);
2471		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2472		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2473		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2474			mtx_unlock(&softc->ctl_lock);
2475			free(entries, M_CTL);
2476			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2477			       __func__, (uintmax_t)ooa_hdr->lun_num);
2478			retval = EINVAL;
2479			break;
2480		}
2481
2482		cur_fill_num = 0;
2483
2484		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2485			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2486				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2487					ooa_hdr, entries);
2488				if (retval != 0)
2489					break;
2490			}
2491			if (retval != 0) {
2492				mtx_unlock(&softc->ctl_lock);
2493				free(entries, M_CTL);
2494				break;
2495			}
2496		} else {
2497			lun = softc->ctl_luns[ooa_hdr->lun_num];
2498
2499			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2500						    entries);
2501		}
2502		mtx_unlock(&softc->ctl_lock);
2503
2504		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2505		ooa_hdr->fill_len = ooa_hdr->fill_num *
2506			sizeof(struct ctl_ooa_entry);
2507		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2508		if (retval != 0) {
2509			printf("%s: error copying out %d bytes for OOA dump\n",
2510			       __func__, ooa_hdr->fill_len);
2511		}
2512
2513		getbintime(&ooa_hdr->cur_bt);
2514
2515		if (cur_fill_num > ooa_hdr->alloc_num) {
2516			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2517			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2518		} else {
2519			ooa_hdr->dropped_num = 0;
2520			ooa_hdr->status = CTL_OOA_OK;
2521		}
2522
2523		free(entries, M_CTL);
2524		break;
2525	}
2526	case CTL_CHECK_OOA: {
2527		union ctl_io *io;
2528		struct ctl_lun *lun;
2529		struct ctl_ooa_info *ooa_info;
2530
2531
2532		ooa_info = (struct ctl_ooa_info *)addr;
2533
2534		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2535			ooa_info->status = CTL_OOA_INVALID_LUN;
2536			break;
2537		}
2538		mtx_lock(&softc->ctl_lock);
2539		lun = softc->ctl_luns[ooa_info->lun_id];
2540		if (lun == NULL) {
2541			mtx_unlock(&softc->ctl_lock);
2542			ooa_info->status = CTL_OOA_INVALID_LUN;
2543			break;
2544		}
2545
2546		ooa_info->num_entries = 0;
2547		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2548		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2549		     &io->io_hdr, ooa_links)) {
2550			ooa_info->num_entries++;
2551		}
2552
2553		mtx_unlock(&softc->ctl_lock);
2554		ooa_info->status = CTL_OOA_SUCCESS;
2555
2556		break;
2557	}
2558	case CTL_HARD_START:
2559	case CTL_HARD_STOP: {
2560		struct ctl_fe_ioctl_startstop_info ss_info;
2561		struct cfi_metatask *metatask;
2562		struct mtx hs_mtx;
2563
2564		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2565
2566		cv_init(&ss_info.sem, "hard start/stop cv" );
2567
2568		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2569		if (metatask == NULL) {
2570			retval = ENOMEM;
2571			mtx_destroy(&hs_mtx);
2572			break;
2573		}
2574
2575		if (cmd == CTL_HARD_START)
2576			metatask->tasktype = CFI_TASK_STARTUP;
2577		else
2578			metatask->tasktype = CFI_TASK_SHUTDOWN;
2579
2580		metatask->callback = ctl_ioctl_hard_startstop_callback;
2581		metatask->callback_arg = &ss_info;
2582
2583		cfi_action(metatask);
2584
2585		/* Wait for the callback */
2586		mtx_lock(&hs_mtx);
2587		cv_wait_sig(&ss_info.sem, &hs_mtx);
2588		mtx_unlock(&hs_mtx);
2589
2590		/*
2591		 * All information has been copied from the metatask by the
2592		 * time cv_broadcast() is called, so we free the metatask here.
2593		 */
2594		cfi_free_metatask(metatask);
2595
2596		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2597
2598		mtx_destroy(&hs_mtx);
2599		break;
2600	}
2601	case CTL_BBRREAD: {
2602		struct ctl_bbrread_info *bbr_info;
2603		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2604		struct mtx bbr_mtx;
2605		struct cfi_metatask *metatask;
2606
2607		bbr_info = (struct ctl_bbrread_info *)addr;
2608
2609		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2610
2611		bzero(&bbr_mtx, sizeof(bbr_mtx));
2612		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2613
2614		fe_bbr_info.bbr_info = bbr_info;
2615		fe_bbr_info.lock = &bbr_mtx;
2616
2617		cv_init(&fe_bbr_info.sem, "BBR read cv");
2618		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2619
2620		if (metatask == NULL) {
2621			mtx_destroy(&bbr_mtx);
2622			cv_destroy(&fe_bbr_info.sem);
2623			retval = ENOMEM;
2624			break;
2625		}
2626		metatask->tasktype = CFI_TASK_BBRREAD;
2627		metatask->callback = ctl_ioctl_bbrread_callback;
2628		metatask->callback_arg = &fe_bbr_info;
2629		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2630		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2631		metatask->taskinfo.bbrread.len = bbr_info->len;
2632
2633		cfi_action(metatask);
2634
2635		mtx_lock(&bbr_mtx);
2636		while (fe_bbr_info.wakeup_done == 0)
2637			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2638		mtx_unlock(&bbr_mtx);
2639
2640		bbr_info->status = metatask->status;
2641		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2642		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2643		memcpy(&bbr_info->sense_data,
2644		       &metatask->taskinfo.bbrread.sense_data,
2645		       ctl_min(sizeof(bbr_info->sense_data),
2646			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2647
2648		cfi_free_metatask(metatask);
2649
2650		mtx_destroy(&bbr_mtx);
2651		cv_destroy(&fe_bbr_info.sem);
2652
2653		break;
2654	}
2655	case CTL_DELAY_IO: {
2656		struct ctl_io_delay_info *delay_info;
2657#ifdef CTL_IO_DELAY
2658		struct ctl_lun *lun;
2659#endif /* CTL_IO_DELAY */
2660
2661		delay_info = (struct ctl_io_delay_info *)addr;
2662
2663#ifdef CTL_IO_DELAY
2664		mtx_lock(&softc->ctl_lock);
2665
2666		if ((delay_info->lun_id > CTL_MAX_LUNS)
2667		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2668			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2669		} else {
2670			lun = softc->ctl_luns[delay_info->lun_id];
2671
2672			delay_info->status = CTL_DELAY_STATUS_OK;
2673
2674			switch (delay_info->delay_type) {
2675			case CTL_DELAY_TYPE_CONT:
2676				break;
2677			case CTL_DELAY_TYPE_ONESHOT:
2678				break;
2679			default:
2680				delay_info->status =
2681					CTL_DELAY_STATUS_INVALID_TYPE;
2682				break;
2683			}
2684
2685			switch (delay_info->delay_loc) {
2686			case CTL_DELAY_LOC_DATAMOVE:
2687				lun->delay_info.datamove_type =
2688					delay_info->delay_type;
2689				lun->delay_info.datamove_delay =
2690					delay_info->delay_secs;
2691				break;
2692			case CTL_DELAY_LOC_DONE:
2693				lun->delay_info.done_type =
2694					delay_info->delay_type;
2695				lun->delay_info.done_delay =
2696					delay_info->delay_secs;
2697				break;
2698			default:
2699				delay_info->status =
2700					CTL_DELAY_STATUS_INVALID_LOC;
2701				break;
2702			}
2703		}
2704
2705		mtx_unlock(&softc->ctl_lock);
2706#else
2707		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2708#endif /* CTL_IO_DELAY */
2709		break;
2710	}
2711	case CTL_REALSYNC_SET: {
2712		int *syncstate;
2713
2714		syncstate = (int *)addr;
2715
2716		mtx_lock(&softc->ctl_lock);
2717		switch (*syncstate) {
2718		case 0:
2719			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2720			break;
2721		case 1:
2722			softc->flags |= CTL_FLAG_REAL_SYNC;
2723			break;
2724		default:
2725			retval = -EINVAL;
2726			break;
2727		}
2728		mtx_unlock(&softc->ctl_lock);
2729		break;
2730	}
2731	case CTL_REALSYNC_GET: {
2732		int *syncstate;
2733
2734		syncstate = (int*)addr;
2735
2736		mtx_lock(&softc->ctl_lock);
2737		if (softc->flags & CTL_FLAG_REAL_SYNC)
2738			*syncstate = 1;
2739		else
2740			*syncstate = 0;
2741		mtx_unlock(&softc->ctl_lock);
2742
2743		break;
2744	}
2745	case CTL_SETSYNC:
2746	case CTL_GETSYNC: {
2747		struct ctl_sync_info *sync_info;
2748		struct ctl_lun *lun;
2749
2750		sync_info = (struct ctl_sync_info *)addr;
2751
2752		mtx_lock(&softc->ctl_lock);
2753		lun = softc->ctl_luns[sync_info->lun_id];
2754		if (lun == NULL) {
2755			mtx_unlock(&softc->ctl_lock);
2756			sync_info->status = CTL_GS_SYNC_NO_LUN;
2757		}
2758		/*
2759		 * Get or set the sync interval.  We're not bounds checking
2760		 * in the set case, hopefully the user won't do something
2761		 * silly.
2762		 */
2763		if (cmd == CTL_GETSYNC)
2764			sync_info->sync_interval = lun->sync_interval;
2765		else
2766			lun->sync_interval = sync_info->sync_interval;
2767
2768		mtx_unlock(&softc->ctl_lock);
2769
2770		sync_info->status = CTL_GS_SYNC_OK;
2771
2772		break;
2773	}
2774	case CTL_GETSTATS: {
2775		struct ctl_stats *stats;
2776		struct ctl_lun *lun;
2777		int i;
2778
2779		stats = (struct ctl_stats *)addr;
2780
2781		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2782		     stats->alloc_len) {
2783			stats->status = CTL_SS_NEED_MORE_SPACE;
2784			stats->num_luns = softc->num_luns;
2785			break;
2786		}
2787		/*
2788		 * XXX KDM no locking here.  If the LUN list changes,
2789		 * things can blow up.
2790		 */
2791		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2792		     i++, lun = STAILQ_NEXT(lun, links)) {
2793			retval = copyout(&lun->stats, &stats->lun_stats[i],
2794					 sizeof(lun->stats));
2795			if (retval != 0)
2796				break;
2797		}
2798		stats->num_luns = softc->num_luns;
2799		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2800				 softc->num_luns;
2801		stats->status = CTL_SS_OK;
2802#ifdef CTL_TIME_IO
2803		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2804#else
2805		stats->flags = CTL_STATS_FLAG_NONE;
2806#endif
2807		getnanouptime(&stats->timestamp);
2808		break;
2809	}
2810	case CTL_ERROR_INJECT: {
2811		struct ctl_error_desc *err_desc, *new_err_desc;
2812		struct ctl_lun *lun;
2813
2814		err_desc = (struct ctl_error_desc *)addr;
2815
2816		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2817				      M_WAITOK | M_ZERO);
2818		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2819
2820		mtx_lock(&softc->ctl_lock);
2821		lun = softc->ctl_luns[err_desc->lun_id];
2822		if (lun == NULL) {
2823			mtx_unlock(&softc->ctl_lock);
2824			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2825			       __func__, (uintmax_t)err_desc->lun_id);
2826			retval = EINVAL;
2827			break;
2828		}
2829
2830		/*
2831		 * We could do some checking here to verify the validity
2832		 * of the request, but given the complexity of error
2833		 * injection requests, the checking logic would be fairly
2834		 * complex.
2835		 *
2836		 * For now, if the request is invalid, it just won't get
2837		 * executed and might get deleted.
2838		 */
2839		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2840
2841		/*
2842		 * XXX KDM check to make sure the serial number is unique,
2843		 * in case we somehow manage to wrap.  That shouldn't
2844		 * happen for a very long time, but it's the right thing to
2845		 * do.
2846		 */
2847		new_err_desc->serial = lun->error_serial;
2848		err_desc->serial = lun->error_serial;
2849		lun->error_serial++;
2850
2851		mtx_unlock(&softc->ctl_lock);
2852		break;
2853	}
2854	case CTL_ERROR_INJECT_DELETE: {
2855		struct ctl_error_desc *delete_desc, *desc, *desc2;
2856		struct ctl_lun *lun;
2857		int delete_done;
2858
2859		delete_desc = (struct ctl_error_desc *)addr;
2860		delete_done = 0;
2861
2862		mtx_lock(&softc->ctl_lock);
2863		lun = softc->ctl_luns[delete_desc->lun_id];
2864		if (lun == NULL) {
2865			mtx_unlock(&softc->ctl_lock);
2866			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2867			       __func__, (uintmax_t)delete_desc->lun_id);
2868			retval = EINVAL;
2869			break;
2870		}
2871		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2872			if (desc->serial != delete_desc->serial)
2873				continue;
2874
2875			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2876				      links);
2877			free(desc, M_CTL);
2878			delete_done = 1;
2879		}
2880		mtx_unlock(&softc->ctl_lock);
2881		if (delete_done == 0) {
2882			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2883			       "error serial %ju on LUN %u\n", __func__,
2884			       delete_desc->serial, delete_desc->lun_id);
2885			retval = EINVAL;
2886			break;
2887		}
2888		break;
2889	}
2890	case CTL_DUMP_STRUCTS: {
2891		int i, j, k;
2892		struct ctl_frontend *fe;
2893
2894		printf("CTL IID to WWPN map start:\n");
2895		for (i = 0; i < CTL_MAX_PORTS; i++) {
2896			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2897				if (softc->wwpn_iid[i][j].in_use == 0)
2898					continue;
2899
2900				printf("port %d iid %u WWPN %#jx\n",
2901				       softc->wwpn_iid[i][j].port,
2902				       softc->wwpn_iid[i][j].iid,
2903				       (uintmax_t)softc->wwpn_iid[i][j].wwpn);
2904			}
2905		}
2906		printf("CTL IID to WWPN map end\n");
2907		printf("CTL Persistent Reservation information start:\n");
2908		for (i = 0; i < CTL_MAX_LUNS; i++) {
2909			struct ctl_lun *lun;
2910
2911			lun = softc->ctl_luns[i];
2912
2913			if ((lun == NULL)
2914			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2915				continue;
2916
2917			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2918				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2919					if (lun->per_res[j+k].registered == 0)
2920						continue;
2921					printf("LUN %d port %d iid %d key "
2922					       "%#jx\n", i, j, k,
2923					       (uintmax_t)scsi_8btou64(
2924					       lun->per_res[j+k].res_key.key));
2925				}
2926			}
2927		}
2928		printf("CTL Persistent Reservation information end\n");
2929		printf("CTL Frontends:\n");
2930		/*
2931		 * XXX KDM calling this without a lock.  We'd likely want
2932		 * to drop the lock before calling the frontend's dump
2933		 * routine anyway.
2934		 */
2935		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2936			printf("Frontend %s Type %u pport %d vport %d WWNN "
2937			       "%#jx WWPN %#jx\n", fe->port_name, fe->port_type,
2938			       fe->physical_port, fe->virtual_port,
2939			       (uintmax_t)fe->wwnn, (uintmax_t)fe->wwpn);
2940
2941			/*
2942			 * Frontends are not required to support the dump
2943			 * routine.
2944			 */
2945			if (fe->fe_dump == NULL)
2946				continue;
2947
2948			fe->fe_dump();
2949		}
2950		printf("CTL Frontend information end\n");
2951		break;
2952	}
2953	case CTL_LUN_REQ: {
2954		struct ctl_lun_req *lun_req;
2955		struct ctl_backend_driver *backend;
2956
2957		lun_req = (struct ctl_lun_req *)addr;
2958
2959		backend = ctl_backend_find(lun_req->backend);
2960		if (backend == NULL) {
2961			lun_req->status = CTL_LUN_ERROR;
2962			snprintf(lun_req->error_str,
2963				 sizeof(lun_req->error_str),
2964				 "Backend \"%s\" not found.",
2965				 lun_req->backend);
2966			break;
2967		}
2968		if (lun_req->num_be_args > 0) {
2969			lun_req->kern_be_args = ctl_copyin_args(
2970				lun_req->num_be_args,
2971				lun_req->be_args,
2972				lun_req->error_str,
2973				sizeof(lun_req->error_str));
2974			if (lun_req->kern_be_args == NULL) {
2975				lun_req->status = CTL_LUN_ERROR;
2976				break;
2977			}
2978		}
2979
2980		retval = backend->ioctl(dev, cmd, addr, flag, td);
2981
2982		if (lun_req->num_be_args > 0) {
2983			ctl_free_args(lun_req->num_be_args,
2984				      lun_req->kern_be_args);
2985		}
2986		break;
2987	}
2988	case CTL_LUN_LIST: {
2989		struct sbuf *sb;
2990		struct ctl_lun *lun;
2991		struct ctl_lun_list *list;
2992		struct ctl_be_lun_option *opt;
2993
2994		list = (struct ctl_lun_list *)addr;
2995
2996		/*
2997		 * Allocate a fixed length sbuf here, based on the length
2998		 * of the user's buffer.  We could allocate an auto-extending
2999		 * buffer, and then tell the user how much larger our
3000		 * amount of data is than his buffer, but that presents
3001		 * some problems:
3002		 *
3003		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3004		 *     we can't hold a lock while calling them with an
3005		 *     auto-extending buffer.
3006 		 *
3007		 * 2.  There is not currently a LUN reference counting
3008		 *     mechanism, outside of outstanding transactions on
3009		 *     the LUN's OOA queue.  So a LUN could go away on us
3010		 *     while we're getting the LUN number, backend-specific
3011		 *     information, etc.  Thus, given the way things
3012		 *     currently work, we need to hold the CTL lock while
3013		 *     grabbing LUN information.
3014		 *
3015		 * So, from the user's standpoint, the best thing to do is
3016		 * allocate what he thinks is a reasonable buffer length,
3017		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3018		 * double the buffer length and try again.  (And repeat
3019		 * that until he succeeds.)
3020		 */
3021		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3022		if (sb == NULL) {
3023			list->status = CTL_LUN_LIST_ERROR;
3024			snprintf(list->error_str, sizeof(list->error_str),
3025				 "Unable to allocate %d bytes for LUN list",
3026				 list->alloc_len);
3027			break;
3028		}
3029
3030		sbuf_printf(sb, "<ctllunlist>\n");
3031
3032		mtx_lock(&softc->ctl_lock);
3033
3034		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3035			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3036					     (uintmax_t)lun->lun);
3037
3038			/*
3039			 * Bail out as soon as we see that we've overfilled
3040			 * the buffer.
3041			 */
3042			if (retval != 0)
3043				break;
3044
3045			retval = sbuf_printf(sb, "<backend_type>%s"
3046					     "</backend_type>\n",
3047					     (lun->backend == NULL) ?  "none" :
3048					     lun->backend->name);
3049
3050			if (retval != 0)
3051				break;
3052
3053			retval = sbuf_printf(sb, "<lun_type>%d</lun_type>\n",
3054					     lun->be_lun->lun_type);
3055
3056			if (retval != 0)
3057				break;
3058
3059			if (lun->backend == NULL) {
3060				retval = sbuf_printf(sb, "</lun>\n");
3061				if (retval != 0)
3062					break;
3063				continue;
3064			}
3065
3066			retval = sbuf_printf(sb, "<size>%ju</size>\n",
3067					     (lun->be_lun->maxlba > 0) ?
3068					     lun->be_lun->maxlba + 1 : 0);
3069
3070			if (retval != 0)
3071				break;
3072
3073			retval = sbuf_printf(sb, "<blocksize>%u</blocksize>\n",
3074					     lun->be_lun->blocksize);
3075
3076			if (retval != 0)
3077				break;
3078
3079			retval = sbuf_printf(sb, "<serial_number>");
3080
3081			if (retval != 0)
3082				break;
3083
3084			retval = ctl_sbuf_printf_esc(sb,
3085						     lun->be_lun->serial_num);
3086
3087			if (retval != 0)
3088				break;
3089
3090			retval = sbuf_printf(sb, "</serial_number>\n");
3091
3092			if (retval != 0)
3093				break;
3094
3095			retval = sbuf_printf(sb, "<device_id>");
3096
3097			if (retval != 0)
3098				break;
3099
3100			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3101
3102			if (retval != 0)
3103				break;
3104
3105			retval = sbuf_printf(sb, "</device_id>\n");
3106
3107			if (retval != 0)
3108				break;
3109
3110			if (lun->backend->lun_info != NULL) {
3111				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3112				if (retval != 0)
3113					break;
3114			}
3115			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3116				retval = sbuf_printf(sb, "<%s>%s</%s>", opt->name, opt->value, opt->name);
3117				if (retval != 0)
3118					break;
3119			}
3120
3121			retval = sbuf_printf(sb, "</lun>\n");
3122
3123			if (retval != 0)
3124				break;
3125		}
3126		mtx_unlock(&softc->ctl_lock);
3127
3128		if ((retval != 0)
3129		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3130			retval = 0;
3131			sbuf_delete(sb);
3132			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3133			snprintf(list->error_str, sizeof(list->error_str),
3134				 "Out of space, %d bytes is too small",
3135				 list->alloc_len);
3136			break;
3137		}
3138
3139		sbuf_finish(sb);
3140
3141		retval = copyout(sbuf_data(sb), list->lun_xml,
3142				 sbuf_len(sb) + 1);
3143
3144		list->fill_len = sbuf_len(sb) + 1;
3145		list->status = CTL_LUN_LIST_OK;
3146		sbuf_delete(sb);
3147		break;
3148	}
3149	case CTL_ISCSI: {
3150		struct ctl_iscsi *ci;
3151		struct ctl_frontend *fe;
3152
3153		ci = (struct ctl_iscsi *)addr;
3154
3155		mtx_lock(&softc->ctl_lock);
3156		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3157			if (strcmp(fe->port_name, "iscsi") == 0)
3158				break;
3159		}
3160		mtx_unlock(&softc->ctl_lock);
3161
3162		if (fe == NULL) {
3163			ci->status = CTL_ISCSI_ERROR;
3164			snprintf(ci->error_str, sizeof(ci->error_str), "Backend \"iscsi\" not found.");
3165			break;
3166		}
3167
3168		retval = fe->ioctl(dev, cmd, addr, flag, td);
3169		break;
3170	}
3171	default: {
3172		/* XXX KDM should we fix this? */
3173#if 0
3174		struct ctl_backend_driver *backend;
3175		unsigned int type;
3176		int found;
3177
3178		found = 0;
3179
3180		/*
3181		 * We encode the backend type as the ioctl type for backend
3182		 * ioctls.  So parse it out here, and then search for a
3183		 * backend of this type.
3184		 */
3185		type = _IOC_TYPE(cmd);
3186
3187		STAILQ_FOREACH(backend, &softc->be_list, links) {
3188			if (backend->type == type) {
3189				found = 1;
3190				break;
3191			}
3192		}
3193		if (found == 0) {
3194			printf("ctl: unknown ioctl command %#lx or backend "
3195			       "%d\n", cmd, type);
3196			retval = -EINVAL;
3197			break;
3198		}
3199		retval = backend->ioctl(dev, cmd, addr, flag, td);
3200#endif
3201		retval = ENOTTY;
3202		break;
3203	}
3204	}
3205	return (retval);
3206}
3207
3208uint32_t
3209ctl_get_initindex(struct ctl_nexus *nexus)
3210{
3211	if (nexus->targ_port < CTL_MAX_PORTS)
3212		return (nexus->initid.id +
3213			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3214	else
3215		return (nexus->initid.id +
3216		       ((nexus->targ_port - CTL_MAX_PORTS) *
3217			CTL_MAX_INIT_PER_PORT));
3218}
3219
3220uint32_t
3221ctl_get_resindex(struct ctl_nexus *nexus)
3222{
3223	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3224}
3225
3226uint32_t
3227ctl_port_idx(int port_num)
3228{
3229	if (port_num < CTL_MAX_PORTS)
3230		return(port_num);
3231	else
3232		return(port_num - CTL_MAX_PORTS);
3233}
3234
3235/*
3236 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3237 * that are a power of 2.
3238 */
3239int
3240ctl_ffz(uint32_t *mask, uint32_t size)
3241{
3242	uint32_t num_chunks, num_pieces;
3243	int i, j;
3244
3245	num_chunks = (size >> 5);
3246	if (num_chunks == 0)
3247		num_chunks++;
3248	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3249
3250	for (i = 0; i < num_chunks; i++) {
3251		for (j = 0; j < num_pieces; j++) {
3252			if ((mask[i] & (1 << j)) == 0)
3253				return ((i << 5) + j);
3254		}
3255	}
3256
3257	return (-1);
3258}
3259
3260int
3261ctl_set_mask(uint32_t *mask, uint32_t bit)
3262{
3263	uint32_t chunk, piece;
3264
3265	chunk = bit >> 5;
3266	piece = bit % (sizeof(uint32_t) * 8);
3267
3268	if ((mask[chunk] & (1 << piece)) != 0)
3269		return (-1);
3270	else
3271		mask[chunk] |= (1 << piece);
3272
3273	return (0);
3274}
3275
3276int
3277ctl_clear_mask(uint32_t *mask, uint32_t bit)
3278{
3279	uint32_t chunk, piece;
3280
3281	chunk = bit >> 5;
3282	piece = bit % (sizeof(uint32_t) * 8);
3283
3284	if ((mask[chunk] & (1 << piece)) == 0)
3285		return (-1);
3286	else
3287		mask[chunk] &= ~(1 << piece);
3288
3289	return (0);
3290}
3291
3292int
3293ctl_is_set(uint32_t *mask, uint32_t bit)
3294{
3295	uint32_t chunk, piece;
3296
3297	chunk = bit >> 5;
3298	piece = bit % (sizeof(uint32_t) * 8);
3299
3300	if ((mask[chunk] & (1 << piece)) == 0)
3301		return (0);
3302	else
3303		return (1);
3304}
3305
3306#ifdef unused
3307/*
3308 * The bus, target and lun are optional, they can be filled in later.
3309 * can_wait is used to determine whether we can wait on the malloc or not.
3310 */
3311union ctl_io*
3312ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3313	      uint32_t targ_lun, int can_wait)
3314{
3315	union ctl_io *io;
3316
3317	if (can_wait)
3318		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3319	else
3320		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3321
3322	if (io != NULL) {
3323		io->io_hdr.io_type = io_type;
3324		io->io_hdr.targ_port = targ_port;
3325		/*
3326		 * XXX KDM this needs to change/go away.  We need to move
3327		 * to a preallocated pool of ctl_scsiio structures.
3328		 */
3329		io->io_hdr.nexus.targ_target.id = targ_target;
3330		io->io_hdr.nexus.targ_lun = targ_lun;
3331	}
3332
3333	return (io);
3334}
3335
3336void
3337ctl_kfree_io(union ctl_io *io)
3338{
3339	free(io, M_CTL);
3340}
3341#endif /* unused */
3342
3343/*
3344 * ctl_softc, pool_type, total_ctl_io are passed in.
3345 * npool is passed out.
3346 */
3347int
3348ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3349		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3350{
3351	uint32_t i;
3352	union ctl_io *cur_io, *next_io;
3353	struct ctl_io_pool *pool;
3354	int retval;
3355
3356	retval = 0;
3357
3358	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3359					    M_NOWAIT | M_ZERO);
3360	if (pool == NULL) {
3361		retval = -ENOMEM;
3362		goto bailout;
3363	}
3364
3365	pool->type = pool_type;
3366	pool->ctl_softc = ctl_softc;
3367
3368	mtx_lock(&ctl_softc->pool_lock);
3369	pool->id = ctl_softc->cur_pool_id++;
3370	mtx_unlock(&ctl_softc->pool_lock);
3371
3372	pool->flags = CTL_POOL_FLAG_NONE;
3373	pool->refcount = 1;		/* Reference for validity. */
3374	STAILQ_INIT(&pool->free_queue);
3375
3376	/*
3377	 * XXX KDM other options here:
3378	 * - allocate a page at a time
3379	 * - allocate one big chunk of memory.
3380	 * Page allocation might work well, but would take a little more
3381	 * tracking.
3382	 */
3383	for (i = 0; i < total_ctl_io; i++) {
3384		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTL,
3385						M_NOWAIT);
3386		if (cur_io == NULL) {
3387			retval = ENOMEM;
3388			break;
3389		}
3390		cur_io->io_hdr.pool = pool;
3391		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3392		pool->total_ctl_io++;
3393		pool->free_ctl_io++;
3394	}
3395
3396	if (retval != 0) {
3397		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3398		     cur_io != NULL; cur_io = next_io) {
3399			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3400							      links);
3401			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3402				      ctl_io_hdr, links);
3403			free(cur_io, M_CTL);
3404		}
3405
3406		free(pool, M_CTL);
3407		goto bailout;
3408	}
3409	mtx_lock(&ctl_softc->pool_lock);
3410	ctl_softc->num_pools++;
3411	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3412	/*
3413	 * Increment our usage count if this is an external consumer, so we
3414	 * can't get unloaded until the external consumer (most likely a
3415	 * FETD) unloads and frees his pool.
3416	 *
3417	 * XXX KDM will this increment the caller's module use count, or
3418	 * mine?
3419	 */
3420#if 0
3421	if ((pool_type != CTL_POOL_EMERGENCY)
3422	 && (pool_type != CTL_POOL_INTERNAL)
3423	 && (pool_type != CTL_POOL_IOCTL)
3424	 && (pool_type != CTL_POOL_4OTHERSC))
3425		MOD_INC_USE_COUNT;
3426#endif
3427
3428	mtx_unlock(&ctl_softc->pool_lock);
3429
3430	*npool = pool;
3431
3432bailout:
3433
3434	return (retval);
3435}
3436
3437static int
3438ctl_pool_acquire(struct ctl_io_pool *pool)
3439{
3440
3441	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3442
3443	if (pool->flags & CTL_POOL_FLAG_INVALID)
3444		return (-EINVAL);
3445
3446	pool->refcount++;
3447
3448	return (0);
3449}
3450
3451static void
3452ctl_pool_release(struct ctl_io_pool *pool)
3453{
3454	struct ctl_softc *ctl_softc = pool->ctl_softc;
3455	union ctl_io *io;
3456
3457	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3458
3459	if (--pool->refcount != 0)
3460		return;
3461
3462	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3463		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3464			      links);
3465		free(io, M_CTL);
3466	}
3467
3468	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3469	ctl_softc->num_pools--;
3470
3471	/*
3472	 * XXX KDM will this decrement the caller's usage count or mine?
3473	 */
3474#if 0
3475	if ((pool->type != CTL_POOL_EMERGENCY)
3476	 && (pool->type != CTL_POOL_INTERNAL)
3477	 && (pool->type != CTL_POOL_IOCTL))
3478		MOD_DEC_USE_COUNT;
3479#endif
3480
3481	free(pool, M_CTL);
3482}
3483
3484void
3485ctl_pool_free(struct ctl_io_pool *pool)
3486{
3487	struct ctl_softc *ctl_softc;
3488
3489	if (pool == NULL)
3490		return;
3491
3492	ctl_softc = pool->ctl_softc;
3493	mtx_lock(&ctl_softc->pool_lock);
3494	pool->flags |= CTL_POOL_FLAG_INVALID;
3495	ctl_pool_release(pool);
3496	mtx_unlock(&ctl_softc->pool_lock);
3497}
3498
3499/*
3500 * This routine does not block (except for spinlocks of course).
3501 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3502 * possible.
3503 */
3504union ctl_io *
3505ctl_alloc_io(void *pool_ref)
3506{
3507	union ctl_io *io;
3508	struct ctl_softc *ctl_softc;
3509	struct ctl_io_pool *pool, *npool;
3510	struct ctl_io_pool *emergency_pool;
3511
3512	pool = (struct ctl_io_pool *)pool_ref;
3513
3514	if (pool == NULL) {
3515		printf("%s: pool is NULL\n", __func__);
3516		return (NULL);
3517	}
3518
3519	emergency_pool = NULL;
3520
3521	ctl_softc = pool->ctl_softc;
3522
3523	mtx_lock(&ctl_softc->pool_lock);
3524	/*
3525	 * First, try to get the io structure from the user's pool.
3526	 */
3527	if (ctl_pool_acquire(pool) == 0) {
3528		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3529		if (io != NULL) {
3530			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3531			pool->total_allocated++;
3532			pool->free_ctl_io--;
3533			mtx_unlock(&ctl_softc->pool_lock);
3534			return (io);
3535		} else
3536			ctl_pool_release(pool);
3537	}
3538	/*
3539	 * If he doesn't have any io structures left, search for an
3540	 * emergency pool and grab one from there.
3541	 */
3542	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3543		if (npool->type != CTL_POOL_EMERGENCY)
3544			continue;
3545
3546		if (ctl_pool_acquire(npool) != 0)
3547			continue;
3548
3549		emergency_pool = npool;
3550
3551		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3552		if (io != NULL) {
3553			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3554			npool->total_allocated++;
3555			npool->free_ctl_io--;
3556			mtx_unlock(&ctl_softc->pool_lock);
3557			return (io);
3558		} else
3559			ctl_pool_release(npool);
3560	}
3561
3562	/* Drop the spinlock before we malloc */
3563	mtx_unlock(&ctl_softc->pool_lock);
3564
3565	/*
3566	 * The emergency pool (if it exists) didn't have one, so try an
3567	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3568	 */
3569	io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3570	if (io != NULL) {
3571		/*
3572		 * If the emergency pool exists but is empty, add this
3573		 * ctl_io to its list when it gets freed.
3574		 */
3575		if (emergency_pool != NULL) {
3576			mtx_lock(&ctl_softc->pool_lock);
3577			if (ctl_pool_acquire(emergency_pool) == 0) {
3578				io->io_hdr.pool = emergency_pool;
3579				emergency_pool->total_ctl_io++;
3580				/*
3581				 * Need to bump this, otherwise
3582				 * total_allocated and total_freed won't
3583				 * match when we no longer have anything
3584				 * outstanding.
3585				 */
3586				emergency_pool->total_allocated++;
3587			}
3588			mtx_unlock(&ctl_softc->pool_lock);
3589		} else
3590			io->io_hdr.pool = NULL;
3591	}
3592
3593	return (io);
3594}
3595
3596void
3597ctl_free_io(union ctl_io *io)
3598{
3599	if (io == NULL)
3600		return;
3601
3602	/*
3603	 * If this ctl_io has a pool, return it to that pool.
3604	 */
3605	if (io->io_hdr.pool != NULL) {
3606		struct ctl_io_pool *pool;
3607#if 0
3608		struct ctl_softc *ctl_softc;
3609		union ctl_io *tmp_io;
3610		unsigned long xflags;
3611		int i;
3612
3613		ctl_softc = control_softc;
3614#endif
3615
3616		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3617
3618		mtx_lock(&pool->ctl_softc->pool_lock);
3619#if 0
3620		save_flags(xflags);
3621
3622		for (i = 0, tmp_io = (union ctl_io *)STAILQ_FIRST(
3623		     &ctl_softc->task_queue); tmp_io != NULL; i++,
3624		     tmp_io = (union ctl_io *)STAILQ_NEXT(&tmp_io->io_hdr,
3625		     links)) {
3626			if (tmp_io == io) {
3627				printf("%s: %p is still on the task queue!\n",
3628				       __func__, tmp_io);
3629				printf("%s: (%d): type %d "
3630				       "msg %d cdb %x iptl: "
3631				       "%d:%d:%d:%d tag 0x%04x "
3632				       "flg %#lx\n",
3633					__func__, i,
3634					tmp_io->io_hdr.io_type,
3635					tmp_io->io_hdr.msg_type,
3636					tmp_io->scsiio.cdb[0],
3637					tmp_io->io_hdr.nexus.initid.id,
3638					tmp_io->io_hdr.nexus.targ_port,
3639					tmp_io->io_hdr.nexus.targ_target.id,
3640					tmp_io->io_hdr.nexus.targ_lun,
3641					(tmp_io->io_hdr.io_type ==
3642					CTL_IO_TASK) ?
3643					tmp_io->taskio.tag_num :
3644					tmp_io->scsiio.tag_num,
3645					xflags);
3646				panic("I/O still on the task queue!");
3647			}
3648		}
3649#endif
3650		io->io_hdr.io_type = 0xff;
3651		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3652		pool->total_freed++;
3653		pool->free_ctl_io++;
3654		ctl_pool_release(pool);
3655		mtx_unlock(&pool->ctl_softc->pool_lock);
3656	} else {
3657		/*
3658		 * Otherwise, just free it.  We probably malloced it and
3659		 * the emergency pool wasn't available.
3660		 */
3661		free(io, M_CTL);
3662	}
3663
3664}
3665
3666void
3667ctl_zero_io(union ctl_io *io)
3668{
3669	void *pool_ref;
3670
3671	if (io == NULL)
3672		return;
3673
3674	/*
3675	 * May need to preserve linked list pointers at some point too.
3676	 */
3677	pool_ref = io->io_hdr.pool;
3678
3679	memset(io, 0, sizeof(*io));
3680
3681	io->io_hdr.pool = pool_ref;
3682}
3683
3684/*
3685 * This routine is currently used for internal copies of ctl_ios that need
3686 * to persist for some reason after we've already returned status to the
3687 * FETD.  (Thus the flag set.)
3688 *
3689 * XXX XXX
3690 * Note that this makes a blind copy of all fields in the ctl_io, except
3691 * for the pool reference.  This includes any memory that has been
3692 * allocated!  That memory will no longer be valid after done has been
3693 * called, so this would be VERY DANGEROUS for command that actually does
3694 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3695 * start and stop commands, which don't transfer any data, so this is not a
3696 * problem.  If it is used for anything else, the caller would also need to
3697 * allocate data buffer space and this routine would need to be modified to
3698 * copy the data buffer(s) as well.
3699 */
3700void
3701ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3702{
3703	void *pool_ref;
3704
3705	if ((src == NULL)
3706	 || (dest == NULL))
3707		return;
3708
3709	/*
3710	 * May need to preserve linked list pointers at some point too.
3711	 */
3712	pool_ref = dest->io_hdr.pool;
3713
3714	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3715
3716	dest->io_hdr.pool = pool_ref;
3717	/*
3718	 * We need to know that this is an internal copy, and doesn't need
3719	 * to get passed back to the FETD that allocated it.
3720	 */
3721	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3722}
3723
3724#ifdef NEEDTOPORT
3725static void
3726ctl_update_power_subpage(struct copan_power_subpage *page)
3727{
3728	int num_luns, num_partitions, config_type;
3729	struct ctl_softc *softc;
3730	cs_BOOL_t aor_present, shelf_50pct_power;
3731	cs_raidset_personality_t rs_type;
3732	int max_active_luns;
3733
3734	softc = control_softc;
3735
3736	/* subtract out the processor LUN */
3737	num_luns = softc->num_luns - 1;
3738	/*
3739	 * Default to 7 LUNs active, which was the only number we allowed
3740	 * in the past.
3741	 */
3742	max_active_luns = 7;
3743
3744	num_partitions = config_GetRsPartitionInfo();
3745	config_type = config_GetConfigType();
3746	shelf_50pct_power = config_GetShelfPowerMode();
3747	aor_present = config_IsAorRsPresent();
3748
3749	rs_type = ddb_GetRsRaidType(1);
3750	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3751	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3752		EPRINT(0, "Unsupported RS type %d!", rs_type);
3753	}
3754
3755
3756	page->total_luns = num_luns;
3757
3758	switch (config_type) {
3759	case 40:
3760		/*
3761		 * In a 40 drive configuration, it doesn't matter what DC
3762		 * cards we have, whether we have AOR enabled or not,
3763		 * partitioning or not, or what type of RAIDset we have.
3764		 * In that scenario, we can power up every LUN we present
3765		 * to the user.
3766		 */
3767		max_active_luns = num_luns;
3768
3769		break;
3770	case 64:
3771		if (shelf_50pct_power == CS_FALSE) {
3772			/* 25% power */
3773			if (aor_present == CS_TRUE) {
3774				if (rs_type ==
3775				     CS_RAIDSET_PERSONALITY_RAID5) {
3776					max_active_luns = 7;
3777				} else if (rs_type ==
3778					 CS_RAIDSET_PERSONALITY_RAID1){
3779					max_active_luns = 14;
3780				} else {
3781					/* XXX KDM now what?? */
3782				}
3783			} else {
3784				if (rs_type ==
3785				     CS_RAIDSET_PERSONALITY_RAID5) {
3786					max_active_luns = 8;
3787				} else if (rs_type ==
3788					 CS_RAIDSET_PERSONALITY_RAID1){
3789					max_active_luns = 16;
3790				} else {
3791					/* XXX KDM now what?? */
3792				}
3793			}
3794		} else {
3795			/* 50% power */
3796			/*
3797			 * With 50% power in a 64 drive configuration, we
3798			 * can power all LUNs we present.
3799			 */
3800			max_active_luns = num_luns;
3801		}
3802		break;
3803	case 112:
3804		if (shelf_50pct_power == CS_FALSE) {
3805			/* 25% power */
3806			if (aor_present == CS_TRUE) {
3807				if (rs_type ==
3808				     CS_RAIDSET_PERSONALITY_RAID5) {
3809					max_active_luns = 7;
3810				} else if (rs_type ==
3811					 CS_RAIDSET_PERSONALITY_RAID1){
3812					max_active_luns = 14;
3813				} else {
3814					/* XXX KDM now what?? */
3815				}
3816			} else {
3817				if (rs_type ==
3818				     CS_RAIDSET_PERSONALITY_RAID5) {
3819					max_active_luns = 8;
3820				} else if (rs_type ==
3821					 CS_RAIDSET_PERSONALITY_RAID1){
3822					max_active_luns = 16;
3823				} else {
3824					/* XXX KDM now what?? */
3825				}
3826			}
3827		} else {
3828			/* 50% power */
3829			if (aor_present == CS_TRUE) {
3830				if (rs_type ==
3831				     CS_RAIDSET_PERSONALITY_RAID5) {
3832					max_active_luns = 14;
3833				} else if (rs_type ==
3834					 CS_RAIDSET_PERSONALITY_RAID1){
3835					/*
3836					 * We're assuming here that disk
3837					 * caching is enabled, and so we're
3838					 * able to power up half of each
3839					 * LUN, and cache all writes.
3840					 */
3841					max_active_luns = num_luns;
3842				} else {
3843					/* XXX KDM now what?? */
3844				}
3845			} else {
3846				if (rs_type ==
3847				     CS_RAIDSET_PERSONALITY_RAID5) {
3848					max_active_luns = 15;
3849				} else if (rs_type ==
3850					 CS_RAIDSET_PERSONALITY_RAID1){
3851					max_active_luns = 30;
3852				} else {
3853					/* XXX KDM now what?? */
3854				}
3855			}
3856		}
3857		break;
3858	default:
3859		/*
3860		 * In this case, we have an unknown configuration, so we
3861		 * just use the default from above.
3862		 */
3863		break;
3864	}
3865
3866	page->max_active_luns = max_active_luns;
3867#if 0
3868	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
3869	       page->total_luns, page->max_active_luns);
3870#endif
3871}
3872#endif /* NEEDTOPORT */
3873
3874/*
3875 * This routine could be used in the future to load default and/or saved
3876 * mode page parameters for a particuar lun.
3877 */
3878static int
3879ctl_init_page_index(struct ctl_lun *lun)
3880{
3881	int i;
3882	struct ctl_page_index *page_index;
3883	struct ctl_softc *softc;
3884
3885	memcpy(&lun->mode_pages.index, page_index_template,
3886	       sizeof(page_index_template));
3887
3888	softc = lun->ctl_softc;
3889
3890	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3891
3892		page_index = &lun->mode_pages.index[i];
3893		/*
3894		 * If this is a disk-only mode page, there's no point in
3895		 * setting it up.  For some pages, we have to have some
3896		 * basic information about the disk in order to calculate the
3897		 * mode page data.
3898		 */
3899		if ((lun->be_lun->lun_type != T_DIRECT)
3900		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3901			continue;
3902
3903		switch (page_index->page_code & SMPH_PC_MASK) {
3904		case SMS_FORMAT_DEVICE_PAGE: {
3905			struct scsi_format_page *format_page;
3906
3907			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3908				panic("subpage is incorrect!");
3909
3910			/*
3911			 * Sectors per track are set above.  Bytes per
3912			 * sector need to be set here on a per-LUN basis.
3913			 */
3914			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3915			       &format_page_default,
3916			       sizeof(format_page_default));
3917			memcpy(&lun->mode_pages.format_page[
3918			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3919			       sizeof(format_page_changeable));
3920			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3921			       &format_page_default,
3922			       sizeof(format_page_default));
3923			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3924			       &format_page_default,
3925			       sizeof(format_page_default));
3926
3927			format_page = &lun->mode_pages.format_page[
3928				CTL_PAGE_CURRENT];
3929			scsi_ulto2b(lun->be_lun->blocksize,
3930				    format_page->bytes_per_sector);
3931
3932			format_page = &lun->mode_pages.format_page[
3933				CTL_PAGE_DEFAULT];
3934			scsi_ulto2b(lun->be_lun->blocksize,
3935				    format_page->bytes_per_sector);
3936
3937			format_page = &lun->mode_pages.format_page[
3938				CTL_PAGE_SAVED];
3939			scsi_ulto2b(lun->be_lun->blocksize,
3940				    format_page->bytes_per_sector);
3941
3942			page_index->page_data =
3943				(uint8_t *)lun->mode_pages.format_page;
3944			break;
3945		}
3946		case SMS_RIGID_DISK_PAGE: {
3947			struct scsi_rigid_disk_page *rigid_disk_page;
3948			uint32_t sectors_per_cylinder;
3949			uint64_t cylinders;
3950#ifndef	__XSCALE__
3951			int shift;
3952#endif /* !__XSCALE__ */
3953
3954			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3955				panic("invalid subpage value %d",
3956				      page_index->subpage);
3957
3958			/*
3959			 * Rotation rate and sectors per track are set
3960			 * above.  We calculate the cylinders here based on
3961			 * capacity.  Due to the number of heads and
3962			 * sectors per track we're using, smaller arrays
3963			 * may turn out to have 0 cylinders.  Linux and
3964			 * FreeBSD don't pay attention to these mode pages
3965			 * to figure out capacity, but Solaris does.  It
3966			 * seems to deal with 0 cylinders just fine, and
3967			 * works out a fake geometry based on the capacity.
3968			 */
3969			memcpy(&lun->mode_pages.rigid_disk_page[
3970			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
3971			       sizeof(rigid_disk_page_default));
3972			memcpy(&lun->mode_pages.rigid_disk_page[
3973			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3974			       sizeof(rigid_disk_page_changeable));
3975			memcpy(&lun->mode_pages.rigid_disk_page[
3976			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3977			       sizeof(rigid_disk_page_default));
3978			memcpy(&lun->mode_pages.rigid_disk_page[
3979			       CTL_PAGE_SAVED], &rigid_disk_page_default,
3980			       sizeof(rigid_disk_page_default));
3981
3982			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3983				CTL_DEFAULT_HEADS;
3984
3985			/*
3986			 * The divide method here will be more accurate,
3987			 * probably, but results in floating point being
3988			 * used in the kernel on i386 (__udivdi3()).  On the
3989			 * XScale, though, __udivdi3() is implemented in
3990			 * software.
3991			 *
3992			 * The shift method for cylinder calculation is
3993			 * accurate if sectors_per_cylinder is a power of
3994			 * 2.  Otherwise it might be slightly off -- you
3995			 * might have a bit of a truncation problem.
3996			 */
3997#ifdef	__XSCALE__
3998			cylinders = (lun->be_lun->maxlba + 1) /
3999				sectors_per_cylinder;
4000#else
4001			for (shift = 31; shift > 0; shift--) {
4002				if (sectors_per_cylinder & (1 << shift))
4003					break;
4004			}
4005			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4006#endif
4007
4008			/*
4009			 * We've basically got 3 bytes, or 24 bits for the
4010			 * cylinder size in the mode page.  If we're over,
4011			 * just round down to 2^24.
4012			 */
4013			if (cylinders > 0xffffff)
4014				cylinders = 0xffffff;
4015
4016			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4017				CTL_PAGE_CURRENT];
4018			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4019
4020			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4021				CTL_PAGE_DEFAULT];
4022			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4023
4024			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4025				CTL_PAGE_SAVED];
4026			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4027
4028			page_index->page_data =
4029				(uint8_t *)lun->mode_pages.rigid_disk_page;
4030			break;
4031		}
4032		case SMS_CACHING_PAGE: {
4033
4034			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4035				panic("invalid subpage value %d",
4036				      page_index->subpage);
4037			/*
4038			 * Defaults should be okay here, no calculations
4039			 * needed.
4040			 */
4041			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4042			       &caching_page_default,
4043			       sizeof(caching_page_default));
4044			memcpy(&lun->mode_pages.caching_page[
4045			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4046			       sizeof(caching_page_changeable));
4047			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4048			       &caching_page_default,
4049			       sizeof(caching_page_default));
4050			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4051			       &caching_page_default,
4052			       sizeof(caching_page_default));
4053			page_index->page_data =
4054				(uint8_t *)lun->mode_pages.caching_page;
4055			break;
4056		}
4057		case SMS_CONTROL_MODE_PAGE: {
4058
4059			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4060				panic("invalid subpage value %d",
4061				      page_index->subpage);
4062
4063			/*
4064			 * Defaults should be okay here, no calculations
4065			 * needed.
4066			 */
4067			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4068			       &control_page_default,
4069			       sizeof(control_page_default));
4070			memcpy(&lun->mode_pages.control_page[
4071			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4072			       sizeof(control_page_changeable));
4073			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4074			       &control_page_default,
4075			       sizeof(control_page_default));
4076			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4077			       &control_page_default,
4078			       sizeof(control_page_default));
4079			page_index->page_data =
4080				(uint8_t *)lun->mode_pages.control_page;
4081			break;
4082
4083		}
4084		case SMS_VENDOR_SPECIFIC_PAGE:{
4085			switch (page_index->subpage) {
4086			case PWR_SUBPAGE_CODE: {
4087				struct copan_power_subpage *current_page,
4088							   *saved_page;
4089
4090				memcpy(&lun->mode_pages.power_subpage[
4091				       CTL_PAGE_CURRENT],
4092				       &power_page_default,
4093				       sizeof(power_page_default));
4094				memcpy(&lun->mode_pages.power_subpage[
4095				       CTL_PAGE_CHANGEABLE],
4096				       &power_page_changeable,
4097				       sizeof(power_page_changeable));
4098				memcpy(&lun->mode_pages.power_subpage[
4099				       CTL_PAGE_DEFAULT],
4100				       &power_page_default,
4101				       sizeof(power_page_default));
4102				memcpy(&lun->mode_pages.power_subpage[
4103				       CTL_PAGE_SAVED],
4104				       &power_page_default,
4105				       sizeof(power_page_default));
4106				page_index->page_data =
4107				    (uint8_t *)lun->mode_pages.power_subpage;
4108
4109				current_page = (struct copan_power_subpage *)
4110					(page_index->page_data +
4111					 (page_index->page_len *
4112					  CTL_PAGE_CURRENT));
4113			        saved_page = (struct copan_power_subpage *)
4114				        (page_index->page_data +
4115					 (page_index->page_len *
4116					  CTL_PAGE_SAVED));
4117				break;
4118			}
4119			case APS_SUBPAGE_CODE: {
4120				struct copan_aps_subpage *current_page,
4121							 *saved_page;
4122
4123				// This gets set multiple times but
4124				// it should always be the same. It's
4125				// only done during init so who cares.
4126				index_to_aps_page = i;
4127
4128				memcpy(&lun->mode_pages.aps_subpage[
4129				       CTL_PAGE_CURRENT],
4130				       &aps_page_default,
4131				       sizeof(aps_page_default));
4132				memcpy(&lun->mode_pages.aps_subpage[
4133				       CTL_PAGE_CHANGEABLE],
4134				       &aps_page_changeable,
4135				       sizeof(aps_page_changeable));
4136				memcpy(&lun->mode_pages.aps_subpage[
4137				       CTL_PAGE_DEFAULT],
4138				       &aps_page_default,
4139				       sizeof(aps_page_default));
4140				memcpy(&lun->mode_pages.aps_subpage[
4141				       CTL_PAGE_SAVED],
4142				       &aps_page_default,
4143				       sizeof(aps_page_default));
4144				page_index->page_data =
4145					(uint8_t *)lun->mode_pages.aps_subpage;
4146
4147				current_page = (struct copan_aps_subpage *)
4148					(page_index->page_data +
4149					 (page_index->page_len *
4150					  CTL_PAGE_CURRENT));
4151				saved_page = (struct copan_aps_subpage *)
4152					(page_index->page_data +
4153					 (page_index->page_len *
4154					  CTL_PAGE_SAVED));
4155				break;
4156			}
4157			case DBGCNF_SUBPAGE_CODE: {
4158				struct copan_debugconf_subpage *current_page,
4159							       *saved_page;
4160
4161				memcpy(&lun->mode_pages.debugconf_subpage[
4162				       CTL_PAGE_CURRENT],
4163				       &debugconf_page_default,
4164				       sizeof(debugconf_page_default));
4165				memcpy(&lun->mode_pages.debugconf_subpage[
4166				       CTL_PAGE_CHANGEABLE],
4167				       &debugconf_page_changeable,
4168				       sizeof(debugconf_page_changeable));
4169				memcpy(&lun->mode_pages.debugconf_subpage[
4170				       CTL_PAGE_DEFAULT],
4171				       &debugconf_page_default,
4172				       sizeof(debugconf_page_default));
4173				memcpy(&lun->mode_pages.debugconf_subpage[
4174				       CTL_PAGE_SAVED],
4175				       &debugconf_page_default,
4176				       sizeof(debugconf_page_default));
4177				page_index->page_data =
4178					(uint8_t *)lun->mode_pages.debugconf_subpage;
4179
4180				current_page = (struct copan_debugconf_subpage *)
4181					(page_index->page_data +
4182					 (page_index->page_len *
4183					  CTL_PAGE_CURRENT));
4184				saved_page = (struct copan_debugconf_subpage *)
4185					(page_index->page_data +
4186					 (page_index->page_len *
4187					  CTL_PAGE_SAVED));
4188				break;
4189			}
4190			default:
4191				panic("invalid subpage value %d",
4192				      page_index->subpage);
4193				break;
4194			}
4195   			break;
4196		}
4197		default:
4198			panic("invalid page value %d",
4199			      page_index->page_code & SMPH_PC_MASK);
4200			break;
4201    	}
4202	}
4203
4204	return (CTL_RETVAL_COMPLETE);
4205}
4206
4207/*
4208 * LUN allocation.
4209 *
4210 * Requirements:
4211 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4212 *   wants us to allocate the LUN and he can block.
4213 * - ctl_softc is always set
4214 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4215 *
4216 * Returns 0 for success, non-zero (errno) for failure.
4217 */
4218static int
4219ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4220	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4221{
4222	struct ctl_lun *nlun, *lun;
4223	struct ctl_frontend *fe;
4224	int lun_number, i, lun_malloced;
4225
4226	if (be_lun == NULL)
4227		return (EINVAL);
4228
4229	/*
4230	 * We currently only support Direct Access or Processor LUN types.
4231	 */
4232	switch (be_lun->lun_type) {
4233	case T_DIRECT:
4234		break;
4235	case T_PROCESSOR:
4236		break;
4237	case T_SEQUENTIAL:
4238	case T_CHANGER:
4239	default:
4240		be_lun->lun_config_status(be_lun->be_lun,
4241					  CTL_LUN_CONFIG_FAILURE);
4242		break;
4243	}
4244	if (ctl_lun == NULL) {
4245		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4246		lun_malloced = 1;
4247	} else {
4248		lun_malloced = 0;
4249		lun = ctl_lun;
4250	}
4251
4252	memset(lun, 0, sizeof(*lun));
4253	if (lun_malloced)
4254		lun->flags = CTL_LUN_MALLOCED;
4255
4256	mtx_lock(&ctl_softc->ctl_lock);
4257	/*
4258	 * See if the caller requested a particular LUN number.  If so, see
4259	 * if it is available.  Otherwise, allocate the first available LUN.
4260	 */
4261	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4262		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4263		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4264			mtx_unlock(&ctl_softc->ctl_lock);
4265			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4266				printf("ctl: requested LUN ID %d is higher "
4267				       "than CTL_MAX_LUNS - 1 (%d)\n",
4268				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4269			} else {
4270				/*
4271				 * XXX KDM return an error, or just assign
4272				 * another LUN ID in this case??
4273				 */
4274				printf("ctl: requested LUN ID %d is already "
4275				       "in use\n", be_lun->req_lun_id);
4276			}
4277			if (lun->flags & CTL_LUN_MALLOCED)
4278				free(lun, M_CTL);
4279			be_lun->lun_config_status(be_lun->be_lun,
4280						  CTL_LUN_CONFIG_FAILURE);
4281			return (ENOSPC);
4282		}
4283		lun_number = be_lun->req_lun_id;
4284	} else {
4285		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4286		if (lun_number == -1) {
4287			mtx_unlock(&ctl_softc->ctl_lock);
4288			printf("ctl: can't allocate LUN on target %ju, out of "
4289			       "LUNs\n", (uintmax_t)target_id.id);
4290			if (lun->flags & CTL_LUN_MALLOCED)
4291				free(lun, M_CTL);
4292			be_lun->lun_config_status(be_lun->be_lun,
4293						  CTL_LUN_CONFIG_FAILURE);
4294			return (ENOSPC);
4295		}
4296	}
4297	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4298
4299	lun->target = target_id;
4300	lun->lun = lun_number;
4301	lun->be_lun = be_lun;
4302	/*
4303	 * The processor LUN is always enabled.  Disk LUNs come on line
4304	 * disabled, and must be enabled by the backend.
4305	 */
4306	lun->flags |= CTL_LUN_DISABLED;
4307	lun->backend = be_lun->be;
4308	be_lun->ctl_lun = lun;
4309	be_lun->lun_id = lun_number;
4310	atomic_add_int(&be_lun->be->num_luns, 1);
4311	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4312		lun->flags |= CTL_LUN_STOPPED;
4313
4314	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4315		lun->flags |= CTL_LUN_INOPERABLE;
4316
4317	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4318		lun->flags |= CTL_LUN_PRIMARY_SC;
4319
4320	lun->ctl_softc = ctl_softc;
4321	TAILQ_INIT(&lun->ooa_queue);
4322	TAILQ_INIT(&lun->blocked_queue);
4323	STAILQ_INIT(&lun->error_list);
4324
4325	/*
4326	 * Initialize the mode page index.
4327	 */
4328	ctl_init_page_index(lun);
4329
4330	/*
4331	 * Set the poweron UA for all initiators on this LUN only.
4332	 */
4333	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4334		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4335
4336	/*
4337	 * Now, before we insert this lun on the lun list, set the lun
4338	 * inventory changed UA for all other luns.
4339	 */
4340	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4341		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4342			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4343		}
4344	}
4345
4346	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4347
4348	ctl_softc->ctl_luns[lun_number] = lun;
4349
4350	ctl_softc->num_luns++;
4351
4352	/* Setup statistics gathering */
4353	lun->stats.device_type = be_lun->lun_type;
4354	lun->stats.lun_number = lun_number;
4355	if (lun->stats.device_type == T_DIRECT)
4356		lun->stats.blocksize = be_lun->blocksize;
4357	else
4358		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4359	for (i = 0;i < CTL_MAX_PORTS;i++)
4360		lun->stats.ports[i].targ_port = i;
4361
4362	mtx_unlock(&ctl_softc->ctl_lock);
4363
4364	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4365
4366	/*
4367	 * Run through each registered FETD and bring it online if it isn't
4368	 * already.  Enable the target ID if it hasn't been enabled, and
4369	 * enable this particular LUN.
4370	 */
4371	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4372		int retval;
4373
4374		/*
4375		 * XXX KDM this only works for ONE TARGET ID.  We'll need
4376		 * to do things differently if we go to a multiple target
4377		 * ID scheme.
4378		 */
4379		if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) == 0) {
4380
4381			retval = fe->targ_enable(fe->targ_lun_arg, target_id);
4382			if (retval != 0) {
4383				printf("ctl_alloc_lun: FETD %s port %d "
4384				       "returned error %d for targ_enable on "
4385				       "target %ju\n", fe->port_name,
4386				       fe->targ_port, retval,
4387				       (uintmax_t)target_id.id);
4388			} else
4389				fe->status |= CTL_PORT_STATUS_TARG_ONLINE;
4390		}
4391
4392		retval = fe->lun_enable(fe->targ_lun_arg, target_id,lun_number);
4393		if (retval != 0) {
4394			printf("ctl_alloc_lun: FETD %s port %d returned error "
4395			       "%d for lun_enable on target %ju lun %d\n",
4396			       fe->port_name, fe->targ_port, retval,
4397			       (uintmax_t)target_id.id, lun_number);
4398		} else
4399			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4400	}
4401	return (0);
4402}
4403
4404/*
4405 * Delete a LUN.
4406 * Assumptions:
4407 * - LUN has already been marked invalid and any pending I/O has been taken
4408 *   care of.
4409 */
4410static int
4411ctl_free_lun(struct ctl_lun *lun)
4412{
4413	struct ctl_softc *softc;
4414#if 0
4415	struct ctl_frontend *fe;
4416#endif
4417	struct ctl_lun *nlun;
4418	union ctl_io *io, *next_io;
4419	int i;
4420
4421	softc = lun->ctl_softc;
4422
4423	mtx_assert(&softc->ctl_lock, MA_OWNED);
4424
4425	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4426
4427	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4428
4429	softc->ctl_luns[lun->lun] = NULL;
4430
4431	if (TAILQ_FIRST(&lun->ooa_queue) != NULL) {
4432		printf("ctl_free_lun: aieee!! freeing a LUN with "
4433		       "outstanding I/O!!\n");
4434	}
4435
4436	/*
4437	 * If we have anything pending on the RtR queue, remove it.
4438	 */
4439	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue); io != NULL;
4440	     io = next_io) {
4441		uint32_t targ_lun;
4442
4443		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
4444		targ_lun = io->io_hdr.nexus.targ_lun;
4445		if (io->io_hdr.nexus.lun_map_fn != NULL)
4446			targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
4447		if ((io->io_hdr.nexus.targ_target.id == lun->target.id)
4448		 && (targ_lun == lun->lun))
4449			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
4450				      ctl_io_hdr, links);
4451	}
4452
4453	/*
4454	 * Then remove everything from the blocked queue.
4455	 */
4456	for (io = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue); io != NULL;
4457	     io = next_io) {
4458		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,blocked_links);
4459		TAILQ_REMOVE(&lun->blocked_queue, &io->io_hdr, blocked_links);
4460		io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
4461	}
4462
4463	/*
4464	 * Now clear out the OOA queue, and free all the I/O.
4465	 * XXX KDM should we notify the FETD here?  We probably need to
4466	 * quiesce the LUN before deleting it.
4467	 */
4468	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); io != NULL;
4469	     io = next_io) {
4470		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, ooa_links);
4471		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
4472		ctl_free_io(io);
4473	}
4474
4475	softc->num_luns--;
4476
4477	/*
4478	 * XXX KDM this scheme only works for a single target/multiple LUN
4479	 * setup.  It needs to be revamped for a multiple target scheme.
4480	 *
4481	 * XXX KDM this results in fe->lun_disable() getting called twice,
4482	 * once when ctl_disable_lun() is called, and a second time here.
4483	 * We really need to re-think the LUN disable semantics.  There
4484	 * should probably be several steps/levels to LUN removal:
4485	 *  - disable
4486	 *  - invalidate
4487	 *  - free
4488 	 *
4489	 * Right now we only have a disable method when communicating to
4490	 * the front end ports, at least for individual LUNs.
4491	 */
4492#if 0
4493	STAILQ_FOREACH(fe, &softc->fe_list, links) {
4494		int retval;
4495
4496		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4497					 lun->lun);
4498		if (retval != 0) {
4499			printf("ctl_free_lun: FETD %s port %d returned error "
4500			       "%d for lun_disable on target %ju lun %jd\n",
4501			       fe->port_name, fe->targ_port, retval,
4502			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4503		}
4504
4505		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4506			fe->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4507
4508			retval = fe->targ_disable(fe->targ_lun_arg,lun->target);
4509			if (retval != 0) {
4510				printf("ctl_free_lun: FETD %s port %d "
4511				       "returned error %d for targ_disable on "
4512				       "target %ju\n", fe->port_name,
4513				       fe->targ_port, retval,
4514				       (uintmax_t)lun->target.id);
4515			} else
4516				fe->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4517
4518			if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4519				continue;
4520
4521#if 0
4522			fe->port_offline(fe->onoff_arg);
4523			fe->status &= ~CTL_PORT_STATUS_ONLINE;
4524#endif
4525		}
4526	}
4527#endif
4528
4529	/*
4530	 * Tell the backend to free resources, if this LUN has a backend.
4531	 */
4532	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4533	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4534
4535	if (lun->flags & CTL_LUN_MALLOCED)
4536		free(lun, M_CTL);
4537
4538	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4539		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4540			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4541		}
4542	}
4543
4544	return (0);
4545}
4546
4547static void
4548ctl_create_lun(struct ctl_be_lun *be_lun)
4549{
4550	struct ctl_softc *ctl_softc;
4551
4552	ctl_softc = control_softc;
4553
4554	/*
4555	 * ctl_alloc_lun() should handle all potential failure cases.
4556	 */
4557	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4558}
4559
4560int
4561ctl_add_lun(struct ctl_be_lun *be_lun)
4562{
4563	struct ctl_softc *ctl_softc;
4564
4565	ctl_softc = control_softc;
4566
4567	mtx_lock(&ctl_softc->ctl_lock);
4568	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4569	mtx_unlock(&ctl_softc->ctl_lock);
4570
4571	ctl_wakeup_thread();
4572
4573	return (0);
4574}
4575
4576int
4577ctl_enable_lun(struct ctl_be_lun *be_lun)
4578{
4579	struct ctl_softc *ctl_softc;
4580	struct ctl_frontend *fe, *nfe;
4581	struct ctl_lun *lun;
4582	int retval;
4583
4584	ctl_softc = control_softc;
4585
4586	lun = (struct ctl_lun *)be_lun->ctl_lun;
4587
4588	mtx_lock(&ctl_softc->ctl_lock);
4589	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4590		/*
4591		 * eh?  Why did we get called if the LUN is already
4592		 * enabled?
4593		 */
4594		mtx_unlock(&ctl_softc->ctl_lock);
4595		return (0);
4596	}
4597	lun->flags &= ~CTL_LUN_DISABLED;
4598
4599	for (fe = STAILQ_FIRST(&ctl_softc->fe_list); fe != NULL; fe = nfe) {
4600		nfe = STAILQ_NEXT(fe, links);
4601
4602		/*
4603		 * Drop the lock while we call the FETD's enable routine.
4604		 * This can lead to a callback into CTL (at least in the
4605		 * case of the internal initiator frontend.
4606		 */
4607		mtx_unlock(&ctl_softc->ctl_lock);
4608		retval = fe->lun_enable(fe->targ_lun_arg, lun->target,lun->lun);
4609		mtx_lock(&ctl_softc->ctl_lock);
4610		if (retval != 0) {
4611			printf("%s: FETD %s port %d returned error "
4612			       "%d for lun_enable on target %ju lun %jd\n",
4613			       __func__, fe->port_name, fe->targ_port, retval,
4614			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4615		}
4616#if 0
4617		 else {
4618            /* NOTE:  TODO:  why does lun enable affect port status? */
4619			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4620		}
4621#endif
4622	}
4623
4624	mtx_unlock(&ctl_softc->ctl_lock);
4625
4626	return (0);
4627}
4628
4629int
4630ctl_disable_lun(struct ctl_be_lun *be_lun)
4631{
4632	struct ctl_softc *ctl_softc;
4633	struct ctl_frontend *fe;
4634	struct ctl_lun *lun;
4635	int retval;
4636
4637	ctl_softc = control_softc;
4638
4639	lun = (struct ctl_lun *)be_lun->ctl_lun;
4640
4641	mtx_lock(&ctl_softc->ctl_lock);
4642
4643	if (lun->flags & CTL_LUN_DISABLED) {
4644		mtx_unlock(&ctl_softc->ctl_lock);
4645		return (0);
4646	}
4647	lun->flags |= CTL_LUN_DISABLED;
4648
4649	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4650		mtx_unlock(&ctl_softc->ctl_lock);
4651		/*
4652		 * Drop the lock before we call the frontend's disable
4653		 * routine, to avoid lock order reversals.
4654		 *
4655		 * XXX KDM what happens if the frontend list changes while
4656		 * we're traversing it?  It's unlikely, but should be handled.
4657		 */
4658		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4659					 lun->lun);
4660		mtx_lock(&ctl_softc->ctl_lock);
4661		if (retval != 0) {
4662			printf("ctl_alloc_lun: FETD %s port %d returned error "
4663			       "%d for lun_disable on target %ju lun %jd\n",
4664			       fe->port_name, fe->targ_port, retval,
4665			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4666		}
4667	}
4668
4669	mtx_unlock(&ctl_softc->ctl_lock);
4670
4671	return (0);
4672}
4673
4674int
4675ctl_start_lun(struct ctl_be_lun *be_lun)
4676{
4677	struct ctl_softc *ctl_softc;
4678	struct ctl_lun *lun;
4679
4680	ctl_softc = control_softc;
4681
4682	lun = (struct ctl_lun *)be_lun->ctl_lun;
4683
4684	mtx_lock(&ctl_softc->ctl_lock);
4685	lun->flags &= ~CTL_LUN_STOPPED;
4686	mtx_unlock(&ctl_softc->ctl_lock);
4687
4688	return (0);
4689}
4690
4691int
4692ctl_stop_lun(struct ctl_be_lun *be_lun)
4693{
4694	struct ctl_softc *ctl_softc;
4695	struct ctl_lun *lun;
4696
4697	ctl_softc = control_softc;
4698
4699	lun = (struct ctl_lun *)be_lun->ctl_lun;
4700
4701	mtx_lock(&ctl_softc->ctl_lock);
4702	lun->flags |= CTL_LUN_STOPPED;
4703	mtx_unlock(&ctl_softc->ctl_lock);
4704
4705	return (0);
4706}
4707
4708int
4709ctl_lun_offline(struct ctl_be_lun *be_lun)
4710{
4711	struct ctl_softc *ctl_softc;
4712	struct ctl_lun *lun;
4713
4714	ctl_softc = control_softc;
4715
4716	lun = (struct ctl_lun *)be_lun->ctl_lun;
4717
4718	mtx_lock(&ctl_softc->ctl_lock);
4719	lun->flags |= CTL_LUN_OFFLINE;
4720	mtx_unlock(&ctl_softc->ctl_lock);
4721
4722	return (0);
4723}
4724
4725int
4726ctl_lun_online(struct ctl_be_lun *be_lun)
4727{
4728	struct ctl_softc *ctl_softc;
4729	struct ctl_lun *lun;
4730
4731	ctl_softc = control_softc;
4732
4733	lun = (struct ctl_lun *)be_lun->ctl_lun;
4734
4735	mtx_lock(&ctl_softc->ctl_lock);
4736	lun->flags &= ~CTL_LUN_OFFLINE;
4737	mtx_unlock(&ctl_softc->ctl_lock);
4738
4739	return (0);
4740}
4741
4742int
4743ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4744{
4745	struct ctl_softc *ctl_softc;
4746	struct ctl_lun *lun;
4747
4748	ctl_softc = control_softc;
4749
4750	lun = (struct ctl_lun *)be_lun->ctl_lun;
4751
4752	mtx_lock(&ctl_softc->ctl_lock);
4753
4754	/*
4755	 * The LUN needs to be disabled before it can be marked invalid.
4756	 */
4757	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4758		mtx_unlock(&ctl_softc->ctl_lock);
4759		return (-1);
4760	}
4761	/*
4762	 * Mark the LUN invalid.
4763	 */
4764	lun->flags |= CTL_LUN_INVALID;
4765
4766	/*
4767	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4768	 * If we have something in the OOA queue, we'll free it when the
4769	 * last I/O completes.
4770	 */
4771	if (TAILQ_FIRST(&lun->ooa_queue) == NULL)
4772		ctl_free_lun(lun);
4773	mtx_unlock(&ctl_softc->ctl_lock);
4774
4775	return (0);
4776}
4777
4778int
4779ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4780{
4781	struct ctl_softc *ctl_softc;
4782	struct ctl_lun *lun;
4783
4784	ctl_softc = control_softc;
4785	lun = (struct ctl_lun *)be_lun->ctl_lun;
4786
4787	mtx_lock(&ctl_softc->ctl_lock);
4788	lun->flags |= CTL_LUN_INOPERABLE;
4789	mtx_unlock(&ctl_softc->ctl_lock);
4790
4791	return (0);
4792}
4793
4794int
4795ctl_lun_operable(struct ctl_be_lun *be_lun)
4796{
4797	struct ctl_softc *ctl_softc;
4798	struct ctl_lun *lun;
4799
4800	ctl_softc = control_softc;
4801	lun = (struct ctl_lun *)be_lun->ctl_lun;
4802
4803	mtx_lock(&ctl_softc->ctl_lock);
4804	lun->flags &= ~CTL_LUN_INOPERABLE;
4805	mtx_unlock(&ctl_softc->ctl_lock);
4806
4807	return (0);
4808}
4809
4810int
4811ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
4812		   int lock)
4813{
4814	struct ctl_softc *softc;
4815	struct ctl_lun *lun;
4816	struct copan_aps_subpage *current_sp;
4817	struct ctl_page_index *page_index;
4818	int i;
4819
4820	softc = control_softc;
4821
4822	mtx_lock(&softc->ctl_lock);
4823
4824	lun = (struct ctl_lun *)be_lun->ctl_lun;
4825
4826	page_index = NULL;
4827	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4828		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
4829		     APS_PAGE_CODE)
4830			continue;
4831
4832		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
4833			continue;
4834		page_index = &lun->mode_pages.index[i];
4835	}
4836
4837	if (page_index == NULL) {
4838		mtx_unlock(&softc->ctl_lock);
4839		printf("%s: APS subpage not found for lun %ju!\n", __func__,
4840		       (uintmax_t)lun->lun);
4841		return (1);
4842	}
4843#if 0
4844	if ((softc->aps_locked_lun != 0)
4845	 && (softc->aps_locked_lun != lun->lun)) {
4846		printf("%s: attempt to lock LUN %llu when %llu is already "
4847		       "locked\n");
4848		mtx_unlock(&softc->ctl_lock);
4849		return (1);
4850	}
4851#endif
4852
4853	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
4854		(page_index->page_len * CTL_PAGE_CURRENT));
4855
4856	if (lock != 0) {
4857		current_sp->lock_active = APS_LOCK_ACTIVE;
4858		softc->aps_locked_lun = lun->lun;
4859	} else {
4860		current_sp->lock_active = 0;
4861		softc->aps_locked_lun = 0;
4862	}
4863
4864
4865	/*
4866	 * If we're in HA mode, try to send the lock message to the other
4867	 * side.
4868	 */
4869	if (ctl_is_single == 0) {
4870		int isc_retval;
4871		union ctl_ha_msg lock_msg;
4872
4873		lock_msg.hdr.nexus = *nexus;
4874		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
4875		if (lock != 0)
4876			lock_msg.aps.lock_flag = 1;
4877		else
4878			lock_msg.aps.lock_flag = 0;
4879		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
4880					 sizeof(lock_msg), 0);
4881		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
4882			printf("%s: APS (lock=%d) error returned from "
4883			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
4884			mtx_unlock(&softc->ctl_lock);
4885			return (1);
4886		}
4887	}
4888
4889	mtx_unlock(&softc->ctl_lock);
4890
4891	return (0);
4892}
4893
4894void
4895ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4896{
4897	struct ctl_lun *lun;
4898	struct ctl_softc *softc;
4899	int i;
4900
4901	softc = control_softc;
4902
4903	mtx_lock(&softc->ctl_lock);
4904
4905	lun = (struct ctl_lun *)be_lun->ctl_lun;
4906
4907	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4908		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
4909
4910	mtx_unlock(&softc->ctl_lock);
4911}
4912
4913/*
4914 * Backend "memory move is complete" callback for requests that never
4915 * make it down to say RAIDCore's configuration code.
4916 */
4917int
4918ctl_config_move_done(union ctl_io *io)
4919{
4920	int retval;
4921
4922	retval = CTL_RETVAL_COMPLETE;
4923
4924
4925	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4926	/*
4927	 * XXX KDM this shouldn't happen, but what if it does?
4928	 */
4929	if (io->io_hdr.io_type != CTL_IO_SCSI)
4930		panic("I/O type isn't CTL_IO_SCSI!");
4931
4932	if ((io->io_hdr.port_status == 0)
4933	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4934	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
4935		io->io_hdr.status = CTL_SUCCESS;
4936	else if ((io->io_hdr.port_status != 0)
4937	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4938	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
4939		/*
4940		 * For hardware error sense keys, the sense key
4941		 * specific value is defined to be a retry count,
4942		 * but we use it to pass back an internal FETD
4943		 * error code.  XXX KDM  Hopefully the FETD is only
4944		 * using 16 bits for an error code, since that's
4945		 * all the space we have in the sks field.
4946		 */
4947		ctl_set_internal_failure(&io->scsiio,
4948					 /*sks_valid*/ 1,
4949					 /*retry_count*/
4950					 io->io_hdr.port_status);
4951		free(io->scsiio.kern_data_ptr, M_CTL);
4952		ctl_done(io);
4953		goto bailout;
4954	}
4955
4956	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
4957	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
4958	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4959		/*
4960		 * XXX KDM just assuming a single pointer here, and not a
4961		 * S/G list.  If we start using S/G lists for config data,
4962		 * we'll need to know how to clean them up here as well.
4963		 */
4964		free(io->scsiio.kern_data_ptr, M_CTL);
4965		/* Hopefully the user has already set the status... */
4966		ctl_done(io);
4967	} else {
4968		/*
4969		 * XXX KDM now we need to continue data movement.  Some
4970		 * options:
4971		 * - call ctl_scsiio() again?  We don't do this for data
4972		 *   writes, because for those at least we know ahead of
4973		 *   time where the write will go and how long it is.  For
4974		 *   config writes, though, that information is largely
4975		 *   contained within the write itself, thus we need to
4976		 *   parse out the data again.
4977		 *
4978		 * - Call some other function once the data is in?
4979		 */
4980
4981		/*
4982		 * XXX KDM call ctl_scsiio() again for now, and check flag
4983		 * bits to see whether we're allocated or not.
4984		 */
4985		retval = ctl_scsiio(&io->scsiio);
4986	}
4987bailout:
4988	return (retval);
4989}
4990
4991/*
4992 * This gets called by a backend driver when it is done with a
4993 * data_submit method.
4994 */
4995void
4996ctl_data_submit_done(union ctl_io *io)
4997{
4998	/*
4999	 * If the IO_CONT flag is set, we need to call the supplied
5000	 * function to continue processing the I/O, instead of completing
5001	 * the I/O just yet.
5002	 *
5003	 * If there is an error, though, we don't want to keep processing.
5004	 * Instead, just send status back to the initiator.
5005	 */
5006	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5007	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5008	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5009	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5010		io->scsiio.io_cont(io);
5011		return;
5012	}
5013	ctl_done(io);
5014}
5015
5016/*
5017 * This gets called by a backend driver when it is done with a
5018 * configuration write.
5019 */
5020void
5021ctl_config_write_done(union ctl_io *io)
5022{
5023	/*
5024	 * If the IO_CONT flag is set, we need to call the supplied
5025	 * function to continue processing the I/O, instead of completing
5026	 * the I/O just yet.
5027	 *
5028	 * If there is an error, though, we don't want to keep processing.
5029	 * Instead, just send status back to the initiator.
5030	 */
5031	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5032	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5033	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5034		io->scsiio.io_cont(io);
5035		return;
5036	}
5037	/*
5038	 * Since a configuration write can be done for commands that actually
5039	 * have data allocated, like write buffer, and commands that have
5040	 * no data, like start/stop unit, we need to check here.
5041	 */
5042	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5043		free(io->scsiio.kern_data_ptr, M_CTL);
5044	ctl_done(io);
5045}
5046
5047/*
5048 * SCSI release command.
5049 */
5050int
5051ctl_scsi_release(struct ctl_scsiio *ctsio)
5052{
5053	int length, longid, thirdparty_id, resv_id;
5054	struct ctl_softc *ctl_softc;
5055	struct ctl_lun *lun;
5056
5057	length = 0;
5058	resv_id = 0;
5059
5060	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5061
5062	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5063	ctl_softc = control_softc;
5064
5065	switch (ctsio->cdb[0]) {
5066	case RELEASE: {
5067		struct scsi_release *cdb;
5068
5069		cdb = (struct scsi_release *)ctsio->cdb;
5070		if ((cdb->byte2 & 0x1f) != 0) {
5071			ctl_set_invalid_field(ctsio,
5072					      /*sks_valid*/ 1,
5073					      /*command*/ 1,
5074					      /*field*/ 1,
5075					      /*bit_valid*/ 0,
5076					      /*bit*/ 0);
5077			ctl_done((union ctl_io *)ctsio);
5078			return (CTL_RETVAL_COMPLETE);
5079		}
5080		break;
5081	}
5082	case RELEASE_10: {
5083		struct scsi_release_10 *cdb;
5084
5085		cdb = (struct scsi_release_10 *)ctsio->cdb;
5086
5087		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5088			ctl_set_invalid_field(ctsio,
5089					      /*sks_valid*/ 1,
5090					      /*command*/ 1,
5091					      /*field*/ 1,
5092					      /*bit_valid*/ 1,
5093					      /*bit*/ 0);
5094			ctl_done((union ctl_io *)ctsio);
5095			return (CTL_RETVAL_COMPLETE);
5096
5097		}
5098
5099		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5100			ctl_set_invalid_field(ctsio,
5101					      /*sks_valid*/ 1,
5102					      /*command*/ 1,
5103					      /*field*/ 1,
5104					      /*bit_valid*/ 1,
5105					      /*bit*/ 4);
5106			ctl_done((union ctl_io *)ctsio);
5107			return (CTL_RETVAL_COMPLETE);
5108		}
5109
5110		if (cdb->byte2 & SR10_LONGID)
5111			longid = 1;
5112		else
5113			thirdparty_id = cdb->thirdparty_id;
5114
5115		resv_id = cdb->resv_id;
5116		length = scsi_2btoul(cdb->length);
5117		break;
5118	}
5119	}
5120
5121
5122	/*
5123	 * XXX KDM right now, we only support LUN reservation.  We don't
5124	 * support 3rd party reservations, or extent reservations, which
5125	 * might actually need the parameter list.  If we've gotten this
5126	 * far, we've got a LUN reservation.  Anything else got kicked out
5127	 * above.  So, according to SPC, ignore the length.
5128	 */
5129	length = 0;
5130
5131	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5132	 && (length > 0)) {
5133		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5134		ctsio->kern_data_len = length;
5135		ctsio->kern_total_len = length;
5136		ctsio->kern_data_resid = 0;
5137		ctsio->kern_rel_offset = 0;
5138		ctsio->kern_sg_entries = 0;
5139		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5140		ctsio->be_move_done = ctl_config_move_done;
5141		ctl_datamove((union ctl_io *)ctsio);
5142
5143		return (CTL_RETVAL_COMPLETE);
5144	}
5145
5146	if (length > 0)
5147		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5148
5149	mtx_lock(&ctl_softc->ctl_lock);
5150
5151	/*
5152	 * According to SPC, it is not an error for an intiator to attempt
5153	 * to release a reservation on a LUN that isn't reserved, or that
5154	 * is reserved by another initiator.  The reservation can only be
5155	 * released, though, by the initiator who made it or by one of
5156	 * several reset type events.
5157	 */
5158	if (lun->flags & CTL_LUN_RESERVED) {
5159		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5160		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5161		 && (ctsio->io_hdr.nexus.targ_target.id ==
5162		     lun->rsv_nexus.targ_target.id)) {
5163			lun->flags &= ~CTL_LUN_RESERVED;
5164		}
5165	}
5166
5167	ctsio->scsi_status = SCSI_STATUS_OK;
5168	ctsio->io_hdr.status = CTL_SUCCESS;
5169
5170	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5171		free(ctsio->kern_data_ptr, M_CTL);
5172		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5173	}
5174
5175	mtx_unlock(&ctl_softc->ctl_lock);
5176
5177	ctl_done((union ctl_io *)ctsio);
5178	return (CTL_RETVAL_COMPLETE);
5179}
5180
5181int
5182ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5183{
5184	int extent, thirdparty, longid;
5185	int resv_id, length;
5186	uint64_t thirdparty_id;
5187	struct ctl_softc *ctl_softc;
5188	struct ctl_lun *lun;
5189
5190	extent = 0;
5191	thirdparty = 0;
5192	longid = 0;
5193	resv_id = 0;
5194	length = 0;
5195	thirdparty_id = 0;
5196
5197	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5198
5199	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5200	ctl_softc = control_softc;
5201
5202	switch (ctsio->cdb[0]) {
5203	case RESERVE: {
5204		struct scsi_reserve *cdb;
5205
5206		cdb = (struct scsi_reserve *)ctsio->cdb;
5207		if ((cdb->byte2 & 0x1f) != 0) {
5208			ctl_set_invalid_field(ctsio,
5209					      /*sks_valid*/ 1,
5210					      /*command*/ 1,
5211					      /*field*/ 1,
5212					      /*bit_valid*/ 0,
5213					      /*bit*/ 0);
5214			ctl_done((union ctl_io *)ctsio);
5215			return (CTL_RETVAL_COMPLETE);
5216		}
5217		resv_id = cdb->resv_id;
5218		length = scsi_2btoul(cdb->length);
5219		break;
5220	}
5221	case RESERVE_10: {
5222		struct scsi_reserve_10 *cdb;
5223
5224		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5225
5226		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5227			ctl_set_invalid_field(ctsio,
5228					      /*sks_valid*/ 1,
5229					      /*command*/ 1,
5230					      /*field*/ 1,
5231					      /*bit_valid*/ 1,
5232					      /*bit*/ 0);
5233			ctl_done((union ctl_io *)ctsio);
5234			return (CTL_RETVAL_COMPLETE);
5235		}
5236		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5237			ctl_set_invalid_field(ctsio,
5238					      /*sks_valid*/ 1,
5239					      /*command*/ 1,
5240					      /*field*/ 1,
5241					      /*bit_valid*/ 1,
5242					      /*bit*/ 4);
5243			ctl_done((union ctl_io *)ctsio);
5244			return (CTL_RETVAL_COMPLETE);
5245		}
5246		if (cdb->byte2 & SR10_LONGID)
5247			longid = 1;
5248		else
5249			thirdparty_id = cdb->thirdparty_id;
5250
5251		resv_id = cdb->resv_id;
5252		length = scsi_2btoul(cdb->length);
5253		break;
5254	}
5255	}
5256
5257	/*
5258	 * XXX KDM right now, we only support LUN reservation.  We don't
5259	 * support 3rd party reservations, or extent reservations, which
5260	 * might actually need the parameter list.  If we've gotten this
5261	 * far, we've got a LUN reservation.  Anything else got kicked out
5262	 * above.  So, according to SPC, ignore the length.
5263	 */
5264	length = 0;
5265
5266	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5267	 && (length > 0)) {
5268		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5269		ctsio->kern_data_len = length;
5270		ctsio->kern_total_len = length;
5271		ctsio->kern_data_resid = 0;
5272		ctsio->kern_rel_offset = 0;
5273		ctsio->kern_sg_entries = 0;
5274		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5275		ctsio->be_move_done = ctl_config_move_done;
5276		ctl_datamove((union ctl_io *)ctsio);
5277
5278		return (CTL_RETVAL_COMPLETE);
5279	}
5280
5281	if (length > 0)
5282		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5283
5284	mtx_lock(&ctl_softc->ctl_lock);
5285	if (lun->flags & CTL_LUN_RESERVED) {
5286		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5287		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5288		 || (ctsio->io_hdr.nexus.targ_target.id !=
5289		     lun->rsv_nexus.targ_target.id)) {
5290			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5291			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5292			goto bailout;
5293		}
5294	}
5295
5296	lun->flags |= CTL_LUN_RESERVED;
5297	lun->rsv_nexus = ctsio->io_hdr.nexus;
5298
5299	ctsio->scsi_status = SCSI_STATUS_OK;
5300	ctsio->io_hdr.status = CTL_SUCCESS;
5301
5302bailout:
5303	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5304		free(ctsio->kern_data_ptr, M_CTL);
5305		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5306	}
5307
5308	mtx_unlock(&ctl_softc->ctl_lock);
5309
5310	ctl_done((union ctl_io *)ctsio);
5311	return (CTL_RETVAL_COMPLETE);
5312}
5313
5314int
5315ctl_start_stop(struct ctl_scsiio *ctsio)
5316{
5317	struct scsi_start_stop_unit *cdb;
5318	struct ctl_lun *lun;
5319	struct ctl_softc *ctl_softc;
5320	int retval;
5321
5322	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5323
5324	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5325	ctl_softc = control_softc;
5326	retval = 0;
5327
5328	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5329
5330	/*
5331	 * XXX KDM
5332	 * We don't support the immediate bit on a stop unit.  In order to
5333	 * do that, we would need to code up a way to know that a stop is
5334	 * pending, and hold off any new commands until it completes, one
5335	 * way or another.  Then we could accept or reject those commands
5336	 * depending on its status.  We would almost need to do the reverse
5337	 * of what we do below for an immediate start -- return the copy of
5338	 * the ctl_io to the FETD with status to send to the host (and to
5339	 * free the copy!) and then free the original I/O once the stop
5340	 * actually completes.  That way, the OOA queue mechanism can work
5341	 * to block commands that shouldn't proceed.  Another alternative
5342	 * would be to put the copy in the queue in place of the original,
5343	 * and return the original back to the caller.  That could be
5344	 * slightly safer..
5345	 */
5346	if ((cdb->byte2 & SSS_IMMED)
5347	 && ((cdb->how & SSS_START) == 0)) {
5348		ctl_set_invalid_field(ctsio,
5349				      /*sks_valid*/ 1,
5350				      /*command*/ 1,
5351				      /*field*/ 1,
5352				      /*bit_valid*/ 1,
5353				      /*bit*/ 0);
5354		ctl_done((union ctl_io *)ctsio);
5355		return (CTL_RETVAL_COMPLETE);
5356	}
5357
5358	/*
5359	 * We don't support the power conditions field.  We need to check
5360	 * this prior to checking the load/eject and start/stop bits.
5361	 */
5362	if ((cdb->how & SSS_PC_MASK) != SSS_PC_START_VALID) {
5363		ctl_set_invalid_field(ctsio,
5364				      /*sks_valid*/ 1,
5365				      /*command*/ 1,
5366				      /*field*/ 4,
5367				      /*bit_valid*/ 1,
5368				      /*bit*/ 4);
5369		ctl_done((union ctl_io *)ctsio);
5370		return (CTL_RETVAL_COMPLETE);
5371	}
5372
5373	/*
5374	 * Media isn't removable, so we can't load or eject it.
5375	 */
5376	if ((cdb->how & SSS_LOEJ) != 0) {
5377		ctl_set_invalid_field(ctsio,
5378				      /*sks_valid*/ 1,
5379				      /*command*/ 1,
5380				      /*field*/ 4,
5381				      /*bit_valid*/ 1,
5382				      /*bit*/ 1);
5383		ctl_done((union ctl_io *)ctsio);
5384		return (CTL_RETVAL_COMPLETE);
5385	}
5386
5387	if ((lun->flags & CTL_LUN_PR_RESERVED)
5388	 && ((cdb->how & SSS_START)==0)) {
5389		uint32_t residx;
5390
5391		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5392		if (!lun->per_res[residx].registered
5393		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5394
5395			ctl_set_reservation_conflict(ctsio);
5396			ctl_done((union ctl_io *)ctsio);
5397			return (CTL_RETVAL_COMPLETE);
5398		}
5399	}
5400
5401	/*
5402	 * If there is no backend on this device, we can't start or stop
5403	 * it.  In theory we shouldn't get any start/stop commands in the
5404	 * first place at this level if the LUN doesn't have a backend.
5405	 * That should get stopped by the command decode code.
5406	 */
5407	if (lun->backend == NULL) {
5408		ctl_set_invalid_opcode(ctsio);
5409		ctl_done((union ctl_io *)ctsio);
5410		return (CTL_RETVAL_COMPLETE);
5411	}
5412
5413	/*
5414	 * XXX KDM Copan-specific offline behavior.
5415	 * Figure out a reasonable way to port this?
5416	 */
5417#ifdef NEEDTOPORT
5418	mtx_lock(&ctl_softc->ctl_lock);
5419
5420	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5421	 && (lun->flags & CTL_LUN_OFFLINE)) {
5422		/*
5423		 * If the LUN is offline, and the on/offline bit isn't set,
5424		 * reject the start or stop.  Otherwise, let it through.
5425		 */
5426		mtx_unlock(&ctl_softc->ctl_lock);
5427		ctl_set_lun_not_ready(ctsio);
5428		ctl_done((union ctl_io *)ctsio);
5429	} else {
5430		mtx_unlock(&ctl_softc->ctl_lock);
5431#endif /* NEEDTOPORT */
5432		/*
5433		 * This could be a start or a stop when we're online,
5434		 * or a stop/offline or start/online.  A start or stop when
5435		 * we're offline is covered in the case above.
5436		 */
5437		/*
5438		 * In the non-immediate case, we send the request to
5439		 * the backend and return status to the user when
5440		 * it is done.
5441		 *
5442		 * In the immediate case, we allocate a new ctl_io
5443		 * to hold a copy of the request, and send that to
5444		 * the backend.  We then set good status on the
5445		 * user's request and return it immediately.
5446		 */
5447		if (cdb->byte2 & SSS_IMMED) {
5448			union ctl_io *new_io;
5449
5450			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5451			if (new_io == NULL) {
5452				ctl_set_busy(ctsio);
5453				ctl_done((union ctl_io *)ctsio);
5454			} else {
5455				ctl_copy_io((union ctl_io *)ctsio,
5456					    new_io);
5457				retval = lun->backend->config_write(new_io);
5458				ctl_set_success(ctsio);
5459				ctl_done((union ctl_io *)ctsio);
5460			}
5461		} else {
5462			retval = lun->backend->config_write(
5463				(union ctl_io *)ctsio);
5464		}
5465#ifdef NEEDTOPORT
5466	}
5467#endif
5468	return (retval);
5469}
5470
5471/*
5472 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5473 * we don't really do anything with the LBA and length fields if the user
5474 * passes them in.  Instead we'll just flush out the cache for the entire
5475 * LUN.
5476 */
5477int
5478ctl_sync_cache(struct ctl_scsiio *ctsio)
5479{
5480	struct ctl_lun *lun;
5481	struct ctl_softc *ctl_softc;
5482	uint64_t starting_lba;
5483	uint32_t block_count;
5484	int reladr, immed;
5485	int retval;
5486
5487	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5488
5489	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5490	ctl_softc = control_softc;
5491	retval = 0;
5492	reladr = 0;
5493	immed = 0;
5494
5495	switch (ctsio->cdb[0]) {
5496	case SYNCHRONIZE_CACHE: {
5497		struct scsi_sync_cache *cdb;
5498		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5499
5500		if (cdb->byte2 & SSC_RELADR)
5501			reladr = 1;
5502
5503		if (cdb->byte2 & SSC_IMMED)
5504			immed = 1;
5505
5506		starting_lba = scsi_4btoul(cdb->begin_lba);
5507		block_count = scsi_2btoul(cdb->lb_count);
5508		break;
5509	}
5510	case SYNCHRONIZE_CACHE_16: {
5511		struct scsi_sync_cache_16 *cdb;
5512		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5513
5514		if (cdb->byte2 & SSC_RELADR)
5515			reladr = 1;
5516
5517		if (cdb->byte2 & SSC_IMMED)
5518			immed = 1;
5519
5520		starting_lba = scsi_8btou64(cdb->begin_lba);
5521		block_count = scsi_4btoul(cdb->lb_count);
5522		break;
5523	}
5524	default:
5525		ctl_set_invalid_opcode(ctsio);
5526		ctl_done((union ctl_io *)ctsio);
5527		goto bailout;
5528		break; /* NOTREACHED */
5529	}
5530
5531	if (immed) {
5532		/*
5533		 * We don't support the immediate bit.  Since it's in the
5534		 * same place for the 10 and 16 byte SYNCHRONIZE CACHE
5535		 * commands, we can just return the same error in either
5536		 * case.
5537		 */
5538		ctl_set_invalid_field(ctsio,
5539				      /*sks_valid*/ 1,
5540				      /*command*/ 1,
5541				      /*field*/ 1,
5542				      /*bit_valid*/ 1,
5543				      /*bit*/ 1);
5544		ctl_done((union ctl_io *)ctsio);
5545		goto bailout;
5546	}
5547
5548	if (reladr) {
5549		/*
5550		 * We don't support the reladr bit either.  It can only be
5551		 * used with linked commands, and we don't support linked
5552		 * commands.  Since the bit is in the same place for the
5553		 * 10 and 16 byte SYNCHRONIZE CACHE * commands, we can
5554		 * just return the same error in either case.
5555		 */
5556		ctl_set_invalid_field(ctsio,
5557				      /*sks_valid*/ 1,
5558				      /*command*/ 1,
5559				      /*field*/ 1,
5560				      /*bit_valid*/ 1,
5561				      /*bit*/ 0);
5562		ctl_done((union ctl_io *)ctsio);
5563		goto bailout;
5564	}
5565
5566	/*
5567	 * We check the LBA and length, but don't do anything with them.
5568	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5569	 * get flushed.  This check will just help satisfy anyone who wants
5570	 * to see an error for an out of range LBA.
5571	 */
5572	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5573		ctl_set_lba_out_of_range(ctsio);
5574		ctl_done((union ctl_io *)ctsio);
5575		goto bailout;
5576	}
5577
5578	/*
5579	 * If this LUN has no backend, we can't flush the cache anyway.
5580	 */
5581	if (lun->backend == NULL) {
5582		ctl_set_invalid_opcode(ctsio);
5583		ctl_done((union ctl_io *)ctsio);
5584		goto bailout;
5585	}
5586
5587	/*
5588	 * Check to see whether we're configured to send the SYNCHRONIZE
5589	 * CACHE command directly to the back end.
5590	 */
5591	mtx_lock(&ctl_softc->ctl_lock);
5592	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5593	 && (++(lun->sync_count) >= lun->sync_interval)) {
5594		lun->sync_count = 0;
5595		mtx_unlock(&ctl_softc->ctl_lock);
5596		retval = lun->backend->config_write((union ctl_io *)ctsio);
5597	} else {
5598		mtx_unlock(&ctl_softc->ctl_lock);
5599		ctl_set_success(ctsio);
5600		ctl_done((union ctl_io *)ctsio);
5601	}
5602
5603bailout:
5604
5605	return (retval);
5606}
5607
5608int
5609ctl_format(struct ctl_scsiio *ctsio)
5610{
5611	struct scsi_format *cdb;
5612	struct ctl_lun *lun;
5613	struct ctl_softc *ctl_softc;
5614	int length, defect_list_len;
5615
5616	CTL_DEBUG_PRINT(("ctl_format\n"));
5617
5618	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5619	ctl_softc = control_softc;
5620
5621	cdb = (struct scsi_format *)ctsio->cdb;
5622
5623	length = 0;
5624	if (cdb->byte2 & SF_FMTDATA) {
5625		if (cdb->byte2 & SF_LONGLIST)
5626			length = sizeof(struct scsi_format_header_long);
5627		else
5628			length = sizeof(struct scsi_format_header_short);
5629	}
5630
5631	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5632	 && (length > 0)) {
5633		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5634		ctsio->kern_data_len = length;
5635		ctsio->kern_total_len = length;
5636		ctsio->kern_data_resid = 0;
5637		ctsio->kern_rel_offset = 0;
5638		ctsio->kern_sg_entries = 0;
5639		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5640		ctsio->be_move_done = ctl_config_move_done;
5641		ctl_datamove((union ctl_io *)ctsio);
5642
5643		return (CTL_RETVAL_COMPLETE);
5644	}
5645
5646	defect_list_len = 0;
5647
5648	if (cdb->byte2 & SF_FMTDATA) {
5649		if (cdb->byte2 & SF_LONGLIST) {
5650			struct scsi_format_header_long *header;
5651
5652			header = (struct scsi_format_header_long *)
5653				ctsio->kern_data_ptr;
5654
5655			defect_list_len = scsi_4btoul(header->defect_list_len);
5656			if (defect_list_len != 0) {
5657				ctl_set_invalid_field(ctsio,
5658						      /*sks_valid*/ 1,
5659						      /*command*/ 0,
5660						      /*field*/ 2,
5661						      /*bit_valid*/ 0,
5662						      /*bit*/ 0);
5663				goto bailout;
5664			}
5665		} else {
5666			struct scsi_format_header_short *header;
5667
5668			header = (struct scsi_format_header_short *)
5669				ctsio->kern_data_ptr;
5670
5671			defect_list_len = scsi_2btoul(header->defect_list_len);
5672			if (defect_list_len != 0) {
5673				ctl_set_invalid_field(ctsio,
5674						      /*sks_valid*/ 1,
5675						      /*command*/ 0,
5676						      /*field*/ 2,
5677						      /*bit_valid*/ 0,
5678						      /*bit*/ 0);
5679				goto bailout;
5680			}
5681		}
5682	}
5683
5684	/*
5685	 * The format command will clear out the "Medium format corrupted"
5686	 * status if set by the configuration code.  That status is really
5687	 * just a way to notify the host that we have lost the media, and
5688	 * get them to issue a command that will basically make them think
5689	 * they're blowing away the media.
5690	 */
5691	mtx_lock(&ctl_softc->ctl_lock);
5692	lun->flags &= ~CTL_LUN_INOPERABLE;
5693	mtx_unlock(&ctl_softc->ctl_lock);
5694
5695	ctsio->scsi_status = SCSI_STATUS_OK;
5696	ctsio->io_hdr.status = CTL_SUCCESS;
5697bailout:
5698
5699	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5700		free(ctsio->kern_data_ptr, M_CTL);
5701		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5702	}
5703
5704	ctl_done((union ctl_io *)ctsio);
5705	return (CTL_RETVAL_COMPLETE);
5706}
5707
5708int
5709ctl_write_buffer(struct ctl_scsiio *ctsio)
5710{
5711	struct scsi_write_buffer *cdb;
5712	struct copan_page_header *header;
5713	struct ctl_lun *lun;
5714	struct ctl_softc *ctl_softc;
5715	int buffer_offset, len;
5716	int retval;
5717
5718	header = NULL;
5719
5720	retval = CTL_RETVAL_COMPLETE;
5721
5722	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5723
5724	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5725	ctl_softc = control_softc;
5726	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5727
5728	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5729		ctl_set_invalid_field(ctsio,
5730				      /*sks_valid*/ 1,
5731				      /*command*/ 1,
5732				      /*field*/ 1,
5733				      /*bit_valid*/ 1,
5734				      /*bit*/ 4);
5735		ctl_done((union ctl_io *)ctsio);
5736		return (CTL_RETVAL_COMPLETE);
5737	}
5738	if (cdb->buffer_id != 0) {
5739		ctl_set_invalid_field(ctsio,
5740				      /*sks_valid*/ 1,
5741				      /*command*/ 1,
5742				      /*field*/ 2,
5743				      /*bit_valid*/ 0,
5744				      /*bit*/ 0);
5745		ctl_done((union ctl_io *)ctsio);
5746		return (CTL_RETVAL_COMPLETE);
5747	}
5748
5749	len = scsi_3btoul(cdb->length);
5750	buffer_offset = scsi_3btoul(cdb->offset);
5751
5752	if (len > sizeof(lun->write_buffer)) {
5753		ctl_set_invalid_field(ctsio,
5754				      /*sks_valid*/ 1,
5755				      /*command*/ 1,
5756				      /*field*/ 6,
5757				      /*bit_valid*/ 0,
5758				      /*bit*/ 0);
5759		ctl_done((union ctl_io *)ctsio);
5760		return (CTL_RETVAL_COMPLETE);
5761	}
5762
5763	if (buffer_offset != 0) {
5764		ctl_set_invalid_field(ctsio,
5765				      /*sks_valid*/ 1,
5766				      /*command*/ 1,
5767				      /*field*/ 3,
5768				      /*bit_valid*/ 0,
5769				      /*bit*/ 0);
5770		ctl_done((union ctl_io *)ctsio);
5771		return (CTL_RETVAL_COMPLETE);
5772	}
5773
5774	/*
5775	 * If we've got a kernel request that hasn't been malloced yet,
5776	 * malloc it and tell the caller the data buffer is here.
5777	 */
5778	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5779		ctsio->kern_data_ptr = lun->write_buffer;
5780		ctsio->kern_data_len = len;
5781		ctsio->kern_total_len = len;
5782		ctsio->kern_data_resid = 0;
5783		ctsio->kern_rel_offset = 0;
5784		ctsio->kern_sg_entries = 0;
5785		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5786		ctsio->be_move_done = ctl_config_move_done;
5787		ctl_datamove((union ctl_io *)ctsio);
5788
5789		return (CTL_RETVAL_COMPLETE);
5790	}
5791
5792	ctl_done((union ctl_io *)ctsio);
5793
5794	return (CTL_RETVAL_COMPLETE);
5795}
5796
5797int
5798ctl_write_same(struct ctl_scsiio *ctsio)
5799{
5800	struct ctl_lun *lun;
5801	struct ctl_lba_len_flags *lbalen;
5802	uint64_t lba;
5803	uint32_t num_blocks;
5804	int len, retval;
5805	uint8_t byte2;
5806
5807	retval = CTL_RETVAL_COMPLETE;
5808
5809	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5810
5811	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5812
5813	switch (ctsio->cdb[0]) {
5814	case WRITE_SAME_10: {
5815		struct scsi_write_same_10 *cdb;
5816
5817		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5818
5819		lba = scsi_4btoul(cdb->addr);
5820		num_blocks = scsi_2btoul(cdb->length);
5821		byte2 = cdb->byte2;
5822		break;
5823	}
5824	case WRITE_SAME_16: {
5825		struct scsi_write_same_16 *cdb;
5826
5827		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5828
5829		lba = scsi_8btou64(cdb->addr);
5830		num_blocks = scsi_4btoul(cdb->length);
5831		byte2 = cdb->byte2;
5832		break;
5833	}
5834	default:
5835		/*
5836		 * We got a command we don't support.  This shouldn't
5837		 * happen, commands should be filtered out above us.
5838		 */
5839		ctl_set_invalid_opcode(ctsio);
5840		ctl_done((union ctl_io *)ctsio);
5841
5842		return (CTL_RETVAL_COMPLETE);
5843		break; /* NOTREACHED */
5844	}
5845
5846	/*
5847	 * The first check is to make sure we're in bounds, the second
5848	 * check is to catch wrap-around problems.  If the lba + num blocks
5849	 * is less than the lba, then we've wrapped around and the block
5850	 * range is invalid anyway.
5851	 */
5852	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5853	 || ((lba + num_blocks) < lba)) {
5854		ctl_set_lba_out_of_range(ctsio);
5855		ctl_done((union ctl_io *)ctsio);
5856		return (CTL_RETVAL_COMPLETE);
5857	}
5858
5859	/* Zero number of blocks means "to the last logical block" */
5860	if (num_blocks == 0) {
5861		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5862			ctl_set_invalid_field(ctsio,
5863					      /*sks_valid*/ 0,
5864					      /*command*/ 1,
5865					      /*field*/ 0,
5866					      /*bit_valid*/ 0,
5867					      /*bit*/ 0);
5868			ctl_done((union ctl_io *)ctsio);
5869			return (CTL_RETVAL_COMPLETE);
5870		}
5871		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5872	}
5873
5874	len = lun->be_lun->blocksize;
5875
5876	/*
5877	 * If we've got a kernel request that hasn't been malloced yet,
5878	 * malloc it and tell the caller the data buffer is here.
5879	 */
5880	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5881		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5882		ctsio->kern_data_len = len;
5883		ctsio->kern_total_len = len;
5884		ctsio->kern_data_resid = 0;
5885		ctsio->kern_rel_offset = 0;
5886		ctsio->kern_sg_entries = 0;
5887		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5888		ctsio->be_move_done = ctl_config_move_done;
5889		ctl_datamove((union ctl_io *)ctsio);
5890
5891		return (CTL_RETVAL_COMPLETE);
5892	}
5893
5894	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5895	lbalen->lba = lba;
5896	lbalen->len = num_blocks;
5897	lbalen->flags = byte2;
5898	retval = lun->backend->config_write((union ctl_io *)ctsio);
5899
5900	return (retval);
5901}
5902
5903int
5904ctl_unmap(struct ctl_scsiio *ctsio)
5905{
5906	struct ctl_lun *lun;
5907	struct scsi_unmap *cdb;
5908	struct ctl_ptr_len_flags *ptrlen;
5909	struct scsi_unmap_header *hdr;
5910	struct scsi_unmap_desc *buf, *end;
5911	uint64_t lba;
5912	uint32_t num_blocks;
5913	int len, retval;
5914	uint8_t byte2;
5915
5916	retval = CTL_RETVAL_COMPLETE;
5917
5918	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5919
5920	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5921	cdb = (struct scsi_unmap *)ctsio->cdb;
5922
5923	len = scsi_2btoul(cdb->length);
5924	byte2 = cdb->byte2;
5925
5926	/*
5927	 * If we've got a kernel request that hasn't been malloced yet,
5928	 * malloc it and tell the caller the data buffer is here.
5929	 */
5930	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5931		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5932		ctsio->kern_data_len = len;
5933		ctsio->kern_total_len = len;
5934		ctsio->kern_data_resid = 0;
5935		ctsio->kern_rel_offset = 0;
5936		ctsio->kern_sg_entries = 0;
5937		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5938		ctsio->be_move_done = ctl_config_move_done;
5939		ctl_datamove((union ctl_io *)ctsio);
5940
5941		return (CTL_RETVAL_COMPLETE);
5942	}
5943
5944	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5945	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5946	if (len < sizeof (*hdr) ||
5947	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5948	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5949	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5950		ctl_set_invalid_field(ctsio,
5951				      /*sks_valid*/ 0,
5952				      /*command*/ 0,
5953				      /*field*/ 0,
5954				      /*bit_valid*/ 0,
5955				      /*bit*/ 0);
5956		ctl_done((union ctl_io *)ctsio);
5957		return (CTL_RETVAL_COMPLETE);
5958	}
5959	len = scsi_2btoul(hdr->desc_length);
5960	buf = (struct scsi_unmap_desc *)(hdr + 1);
5961	end = buf + len / sizeof(*buf);
5962
5963	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5964	ptrlen->ptr = (void *)buf;
5965	ptrlen->len = len;
5966	ptrlen->flags = byte2;
5967
5968	for (; buf < end; buf++) {
5969		lba = scsi_8btou64(buf->lba);
5970		num_blocks = scsi_4btoul(buf->length);
5971		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5972		 || ((lba + num_blocks) < lba)) {
5973			ctl_set_lba_out_of_range(ctsio);
5974			ctl_done((union ctl_io *)ctsio);
5975			return (CTL_RETVAL_COMPLETE);
5976		}
5977	}
5978
5979	retval = lun->backend->config_write((union ctl_io *)ctsio);
5980
5981	return (retval);
5982}
5983
5984/*
5985 * Note that this function currently doesn't actually do anything inside
5986 * CTL to enforce things if the DQue bit is turned on.
5987 *
5988 * Also note that this function can't be used in the default case, because
5989 * the DQue bit isn't set in the changeable mask for the control mode page
5990 * anyway.  This is just here as an example for how to implement a page
5991 * handler, and a placeholder in case we want to allow the user to turn
5992 * tagged queueing on and off.
5993 *
5994 * The D_SENSE bit handling is functional, however, and will turn
5995 * descriptor sense on and off for a given LUN.
5996 */
5997int
5998ctl_control_page_handler(struct ctl_scsiio *ctsio,
5999			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6000{
6001	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6002	struct ctl_lun *lun;
6003	struct ctl_softc *softc;
6004	int set_ua;
6005	uint32_t initidx;
6006
6007	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6008	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6009	set_ua = 0;
6010
6011	user_cp = (struct scsi_control_page *)page_ptr;
6012	current_cp = (struct scsi_control_page *)
6013		(page_index->page_data + (page_index->page_len *
6014		CTL_PAGE_CURRENT));
6015	saved_cp = (struct scsi_control_page *)
6016		(page_index->page_data + (page_index->page_len *
6017		CTL_PAGE_SAVED));
6018
6019	softc = control_softc;
6020
6021	mtx_lock(&softc->ctl_lock);
6022	if (((current_cp->rlec & SCP_DSENSE) == 0)
6023	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6024		/*
6025		 * Descriptor sense is currently turned off and the user
6026		 * wants to turn it on.
6027		 */
6028		current_cp->rlec |= SCP_DSENSE;
6029		saved_cp->rlec |= SCP_DSENSE;
6030		lun->flags |= CTL_LUN_SENSE_DESC;
6031		set_ua = 1;
6032	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6033		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6034		/*
6035		 * Descriptor sense is currently turned on, and the user
6036		 * wants to turn it off.
6037		 */
6038		current_cp->rlec &= ~SCP_DSENSE;
6039		saved_cp->rlec &= ~SCP_DSENSE;
6040		lun->flags &= ~CTL_LUN_SENSE_DESC;
6041		set_ua = 1;
6042	}
6043	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6044		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6045#ifdef NEEDTOPORT
6046			csevent_log(CSC_CTL | CSC_SHELF_SW |
6047				    CTL_UNTAG_TO_UNTAG,
6048				    csevent_LogType_Trace,
6049				    csevent_Severity_Information,
6050				    csevent_AlertLevel_Green,
6051				    csevent_FRU_Firmware,
6052				    csevent_FRU_Unknown,
6053				    "Received untagged to untagged transition");
6054#endif /* NEEDTOPORT */
6055		} else {
6056#ifdef NEEDTOPORT
6057			csevent_log(CSC_CTL | CSC_SHELF_SW |
6058				    CTL_UNTAG_TO_TAG,
6059				    csevent_LogType_ConfigChange,
6060				    csevent_Severity_Information,
6061				    csevent_AlertLevel_Green,
6062				    csevent_FRU_Firmware,
6063				    csevent_FRU_Unknown,
6064				    "Received untagged to tagged "
6065				    "queueing transition");
6066#endif /* NEEDTOPORT */
6067
6068			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6069			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6070			set_ua = 1;
6071		}
6072	} else {
6073		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6074#ifdef NEEDTOPORT
6075			csevent_log(CSC_CTL | CSC_SHELF_SW |
6076				    CTL_TAG_TO_UNTAG,
6077				    csevent_LogType_ConfigChange,
6078				    csevent_Severity_Warning,
6079				    csevent_AlertLevel_Yellow,
6080				    csevent_FRU_Firmware,
6081				    csevent_FRU_Unknown,
6082				    "Received tagged queueing to untagged "
6083				    "transition");
6084#endif /* NEEDTOPORT */
6085
6086			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6087			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6088			set_ua = 1;
6089		} else {
6090#ifdef NEEDTOPORT
6091			csevent_log(CSC_CTL | CSC_SHELF_SW |
6092				    CTL_TAG_TO_TAG,
6093				    csevent_LogType_Trace,
6094				    csevent_Severity_Information,
6095				    csevent_AlertLevel_Green,
6096				    csevent_FRU_Firmware,
6097				    csevent_FRU_Unknown,
6098				    "Received tagged queueing to tagged "
6099				    "queueing transition");
6100#endif /* NEEDTOPORT */
6101		}
6102	}
6103	if (set_ua != 0) {
6104		int i;
6105		/*
6106		 * Let other initiators know that the mode
6107		 * parameters for this LUN have changed.
6108		 */
6109		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6110			if (i == initidx)
6111				continue;
6112
6113			lun->pending_sense[i].ua_pending |=
6114				CTL_UA_MODE_CHANGE;
6115		}
6116	}
6117	mtx_unlock(&softc->ctl_lock);
6118
6119	return (0);
6120}
6121
6122int
6123ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6124		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6125{
6126	return (0);
6127}
6128
6129int
6130ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6131			   struct ctl_page_index *page_index, int pc)
6132{
6133	struct copan_power_subpage *page;
6134
6135	page = (struct copan_power_subpage *)page_index->page_data +
6136		(page_index->page_len * pc);
6137
6138	switch (pc) {
6139	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6140		/*
6141		 * We don't update the changable bits for this page.
6142		 */
6143		break;
6144	case SMS_PAGE_CTRL_CURRENT >> 6:
6145	case SMS_PAGE_CTRL_DEFAULT >> 6:
6146	case SMS_PAGE_CTRL_SAVED >> 6:
6147#ifdef NEEDTOPORT
6148		ctl_update_power_subpage(page);
6149#endif
6150		break;
6151	default:
6152#ifdef NEEDTOPORT
6153		EPRINT(0, "Invalid PC %d!!", pc);
6154#endif
6155		break;
6156	}
6157	return (0);
6158}
6159
6160
6161int
6162ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6163		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6164{
6165	struct copan_aps_subpage *user_sp;
6166	struct copan_aps_subpage *current_sp;
6167	union ctl_modepage_info *modepage_info;
6168	struct ctl_softc *softc;
6169	struct ctl_lun *lun;
6170	int retval;
6171
6172	retval = CTL_RETVAL_COMPLETE;
6173	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6174		     (page_index->page_len * CTL_PAGE_CURRENT));
6175	softc = control_softc;
6176	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6177
6178	user_sp = (struct copan_aps_subpage *)page_ptr;
6179
6180	modepage_info = (union ctl_modepage_info *)
6181		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6182
6183	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6184	modepage_info->header.subpage = page_index->subpage;
6185	modepage_info->aps.lock_active = user_sp->lock_active;
6186
6187	mtx_lock(&softc->ctl_lock);
6188
6189	/*
6190	 * If there is a request to lock the LUN and another LUN is locked
6191	 * this is an error. If the requested LUN is already locked ignore
6192	 * the request. If no LUN is locked attempt to lock it.
6193	 * if there is a request to unlock the LUN and the LUN is currently
6194	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6195	 * if another LUN is locked or no LUN is locked.
6196	 */
6197	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6198		if (softc->aps_locked_lun == lun->lun) {
6199			/*
6200			 * This LUN is already locked, so we're done.
6201			 */
6202			retval = CTL_RETVAL_COMPLETE;
6203		} else if (softc->aps_locked_lun == 0) {
6204			/*
6205			 * No one has the lock, pass the request to the
6206			 * backend.
6207			 */
6208			retval = lun->backend->config_write(
6209				(union ctl_io *)ctsio);
6210		} else {
6211			/*
6212			 * Someone else has the lock, throw out the request.
6213			 */
6214			ctl_set_already_locked(ctsio);
6215			free(ctsio->kern_data_ptr, M_CTL);
6216			ctl_done((union ctl_io *)ctsio);
6217
6218			/*
6219			 * Set the return value so that ctl_do_mode_select()
6220			 * won't try to complete the command.  We already
6221			 * completed it here.
6222			 */
6223			retval = CTL_RETVAL_ERROR;
6224		}
6225	} else if (softc->aps_locked_lun == lun->lun) {
6226		/*
6227		 * This LUN is locked, so pass the unlock request to the
6228		 * backend.
6229		 */
6230		retval = lun->backend->config_write((union ctl_io *)ctsio);
6231	}
6232	mtx_unlock(&softc->ctl_lock);
6233
6234	return (retval);
6235}
6236
6237int
6238ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6239				struct ctl_page_index *page_index,
6240				uint8_t *page_ptr)
6241{
6242	uint8_t *c;
6243	int i;
6244
6245	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6246	ctl_time_io_secs =
6247		(c[0] << 8) |
6248		(c[1] << 0) |
6249		0;
6250	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6251	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6252	printf("page data:");
6253	for (i=0; i<8; i++)
6254		printf(" %.2x",page_ptr[i]);
6255	printf("\n");
6256	return (0);
6257}
6258
6259int
6260ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6261			       struct ctl_page_index *page_index,
6262			       int pc)
6263{
6264	struct copan_debugconf_subpage *page;
6265
6266	page = (struct copan_debugconf_subpage *)page_index->page_data +
6267		(page_index->page_len * pc);
6268
6269	switch (pc) {
6270	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6271	case SMS_PAGE_CTRL_DEFAULT >> 6:
6272	case SMS_PAGE_CTRL_SAVED >> 6:
6273		/*
6274		 * We don't update the changable or default bits for this page.
6275		 */
6276		break;
6277	case SMS_PAGE_CTRL_CURRENT >> 6:
6278		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6279		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6280		break;
6281	default:
6282#ifdef NEEDTOPORT
6283		EPRINT(0, "Invalid PC %d!!", pc);
6284#endif /* NEEDTOPORT */
6285		break;
6286	}
6287	return (0);
6288}
6289
6290
6291static int
6292ctl_do_mode_select(union ctl_io *io)
6293{
6294	struct scsi_mode_page_header *page_header;
6295	struct ctl_page_index *page_index;
6296	struct ctl_scsiio *ctsio;
6297	int control_dev, page_len;
6298	int page_len_offset, page_len_size;
6299	union ctl_modepage_info *modepage_info;
6300	struct ctl_lun *lun;
6301	int *len_left, *len_used;
6302	int retval, i;
6303
6304	ctsio = &io->scsiio;
6305	page_index = NULL;
6306	page_len = 0;
6307	retval = CTL_RETVAL_COMPLETE;
6308
6309	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6310
6311	if (lun->be_lun->lun_type != T_DIRECT)
6312		control_dev = 1;
6313	else
6314		control_dev = 0;
6315
6316	modepage_info = (union ctl_modepage_info *)
6317		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6318	len_left = &modepage_info->header.len_left;
6319	len_used = &modepage_info->header.len_used;
6320
6321do_next_page:
6322
6323	page_header = (struct scsi_mode_page_header *)
6324		(ctsio->kern_data_ptr + *len_used);
6325
6326	if (*len_left == 0) {
6327		free(ctsio->kern_data_ptr, M_CTL);
6328		ctl_set_success(ctsio);
6329		ctl_done((union ctl_io *)ctsio);
6330		return (CTL_RETVAL_COMPLETE);
6331	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6332
6333		free(ctsio->kern_data_ptr, M_CTL);
6334		ctl_set_param_len_error(ctsio);
6335		ctl_done((union ctl_io *)ctsio);
6336		return (CTL_RETVAL_COMPLETE);
6337
6338	} else if ((page_header->page_code & SMPH_SPF)
6339		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6340
6341		free(ctsio->kern_data_ptr, M_CTL);
6342		ctl_set_param_len_error(ctsio);
6343		ctl_done((union ctl_io *)ctsio);
6344		return (CTL_RETVAL_COMPLETE);
6345	}
6346
6347
6348	/*
6349	 * XXX KDM should we do something with the block descriptor?
6350	 */
6351	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6352
6353		if ((control_dev != 0)
6354		 && (lun->mode_pages.index[i].page_flags &
6355		     CTL_PAGE_FLAG_DISK_ONLY))
6356			continue;
6357
6358		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6359		    (page_header->page_code & SMPH_PC_MASK))
6360			continue;
6361
6362		/*
6363		 * If neither page has a subpage code, then we've got a
6364		 * match.
6365		 */
6366		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6367		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6368			page_index = &lun->mode_pages.index[i];
6369			page_len = page_header->page_length;
6370			break;
6371		}
6372
6373		/*
6374		 * If both pages have subpages, then the subpage numbers
6375		 * have to match.
6376		 */
6377		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6378		  && (page_header->page_code & SMPH_SPF)) {
6379			struct scsi_mode_page_header_sp *sph;
6380
6381			sph = (struct scsi_mode_page_header_sp *)page_header;
6382
6383			if (lun->mode_pages.index[i].subpage ==
6384			    sph->subpage) {
6385				page_index = &lun->mode_pages.index[i];
6386				page_len = scsi_2btoul(sph->page_length);
6387				break;
6388			}
6389		}
6390	}
6391
6392	/*
6393	 * If we couldn't find the page, or if we don't have a mode select
6394	 * handler for it, send back an error to the user.
6395	 */
6396	if ((page_index == NULL)
6397	 || (page_index->select_handler == NULL)) {
6398		ctl_set_invalid_field(ctsio,
6399				      /*sks_valid*/ 1,
6400				      /*command*/ 0,
6401				      /*field*/ *len_used,
6402				      /*bit_valid*/ 0,
6403				      /*bit*/ 0);
6404		free(ctsio->kern_data_ptr, M_CTL);
6405		ctl_done((union ctl_io *)ctsio);
6406		return (CTL_RETVAL_COMPLETE);
6407	}
6408
6409	if (page_index->page_code & SMPH_SPF) {
6410		page_len_offset = 2;
6411		page_len_size = 2;
6412	} else {
6413		page_len_size = 1;
6414		page_len_offset = 1;
6415	}
6416
6417	/*
6418	 * If the length the initiator gives us isn't the one we specify in
6419	 * the mode page header, or if they didn't specify enough data in
6420	 * the CDB to avoid truncating this page, kick out the request.
6421	 */
6422	if ((page_len != (page_index->page_len - page_len_offset -
6423			  page_len_size))
6424	 || (*len_left < page_index->page_len)) {
6425
6426
6427		ctl_set_invalid_field(ctsio,
6428				      /*sks_valid*/ 1,
6429				      /*command*/ 0,
6430				      /*field*/ *len_used + page_len_offset,
6431				      /*bit_valid*/ 0,
6432				      /*bit*/ 0);
6433		free(ctsio->kern_data_ptr, M_CTL);
6434		ctl_done((union ctl_io *)ctsio);
6435		return (CTL_RETVAL_COMPLETE);
6436	}
6437
6438	/*
6439	 * Run through the mode page, checking to make sure that the bits
6440	 * the user changed are actually legal for him to change.
6441	 */
6442	for (i = 0; i < page_index->page_len; i++) {
6443		uint8_t *user_byte, *change_mask, *current_byte;
6444		int bad_bit;
6445		int j;
6446
6447		user_byte = (uint8_t *)page_header + i;
6448		change_mask = page_index->page_data +
6449			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6450		current_byte = page_index->page_data +
6451			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6452
6453		/*
6454		 * Check to see whether the user set any bits in this byte
6455		 * that he is not allowed to set.
6456		 */
6457		if ((*user_byte & ~(*change_mask)) ==
6458		    (*current_byte & ~(*change_mask)))
6459			continue;
6460
6461		/*
6462		 * Go through bit by bit to determine which one is illegal.
6463		 */
6464		bad_bit = 0;
6465		for (j = 7; j >= 0; j--) {
6466			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6467			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6468				bad_bit = i;
6469				break;
6470			}
6471		}
6472		ctl_set_invalid_field(ctsio,
6473				      /*sks_valid*/ 1,
6474				      /*command*/ 0,
6475				      /*field*/ *len_used + i,
6476				      /*bit_valid*/ 1,
6477				      /*bit*/ bad_bit);
6478		free(ctsio->kern_data_ptr, M_CTL);
6479		ctl_done((union ctl_io *)ctsio);
6480		return (CTL_RETVAL_COMPLETE);
6481	}
6482
6483	/*
6484	 * Decrement these before we call the page handler, since we may
6485	 * end up getting called back one way or another before the handler
6486	 * returns to this context.
6487	 */
6488	*len_left -= page_index->page_len;
6489	*len_used += page_index->page_len;
6490
6491	retval = page_index->select_handler(ctsio, page_index,
6492					    (uint8_t *)page_header);
6493
6494	/*
6495	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6496	 * wait until this queued command completes to finish processing
6497	 * the mode page.  If it returns anything other than
6498	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6499	 * already set the sense information, freed the data pointer, and
6500	 * completed the io for us.
6501	 */
6502	if (retval != CTL_RETVAL_COMPLETE)
6503		goto bailout_no_done;
6504
6505	/*
6506	 * If the initiator sent us more than one page, parse the next one.
6507	 */
6508	if (*len_left > 0)
6509		goto do_next_page;
6510
6511	ctl_set_success(ctsio);
6512	free(ctsio->kern_data_ptr, M_CTL);
6513	ctl_done((union ctl_io *)ctsio);
6514
6515bailout_no_done:
6516
6517	return (CTL_RETVAL_COMPLETE);
6518
6519}
6520
6521int
6522ctl_mode_select(struct ctl_scsiio *ctsio)
6523{
6524	int param_len, pf, sp;
6525	int header_size, bd_len;
6526	int len_left, len_used;
6527	struct ctl_page_index *page_index;
6528	struct ctl_lun *lun;
6529	int control_dev, page_len;
6530	union ctl_modepage_info *modepage_info;
6531	int retval;
6532
6533	pf = 0;
6534	sp = 0;
6535	page_len = 0;
6536	len_used = 0;
6537	len_left = 0;
6538	retval = 0;
6539	bd_len = 0;
6540	page_index = NULL;
6541
6542	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6543
6544	if (lun->be_lun->lun_type != T_DIRECT)
6545		control_dev = 1;
6546	else
6547		control_dev = 0;
6548
6549	switch (ctsio->cdb[0]) {
6550	case MODE_SELECT_6: {
6551		struct scsi_mode_select_6 *cdb;
6552
6553		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6554
6555		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6556		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6557
6558		param_len = cdb->length;
6559		header_size = sizeof(struct scsi_mode_header_6);
6560		break;
6561	}
6562	case MODE_SELECT_10: {
6563		struct scsi_mode_select_10 *cdb;
6564
6565		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6566
6567		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6568		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6569
6570		param_len = scsi_2btoul(cdb->length);
6571		header_size = sizeof(struct scsi_mode_header_10);
6572		break;
6573	}
6574	default:
6575		ctl_set_invalid_opcode(ctsio);
6576		ctl_done((union ctl_io *)ctsio);
6577		return (CTL_RETVAL_COMPLETE);
6578		break; /* NOTREACHED */
6579	}
6580
6581	/*
6582	 * From SPC-3:
6583	 * "A parameter list length of zero indicates that the Data-Out Buffer
6584	 * shall be empty. This condition shall not be considered as an error."
6585	 */
6586	if (param_len == 0) {
6587		ctl_set_success(ctsio);
6588		ctl_done((union ctl_io *)ctsio);
6589		return (CTL_RETVAL_COMPLETE);
6590	}
6591
6592	/*
6593	 * Since we'll hit this the first time through, prior to
6594	 * allocation, we don't need to free a data buffer here.
6595	 */
6596	if (param_len < header_size) {
6597		ctl_set_param_len_error(ctsio);
6598		ctl_done((union ctl_io *)ctsio);
6599		return (CTL_RETVAL_COMPLETE);
6600	}
6601
6602	/*
6603	 * Allocate the data buffer and grab the user's data.  In theory,
6604	 * we shouldn't have to sanity check the parameter list length here
6605	 * because the maximum size is 64K.  We should be able to malloc
6606	 * that much without too many problems.
6607	 */
6608	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6609		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6610		ctsio->kern_data_len = param_len;
6611		ctsio->kern_total_len = param_len;
6612		ctsio->kern_data_resid = 0;
6613		ctsio->kern_rel_offset = 0;
6614		ctsio->kern_sg_entries = 0;
6615		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6616		ctsio->be_move_done = ctl_config_move_done;
6617		ctl_datamove((union ctl_io *)ctsio);
6618
6619		return (CTL_RETVAL_COMPLETE);
6620	}
6621
6622	switch (ctsio->cdb[0]) {
6623	case MODE_SELECT_6: {
6624		struct scsi_mode_header_6 *mh6;
6625
6626		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6627		bd_len = mh6->blk_desc_len;
6628		break;
6629	}
6630	case MODE_SELECT_10: {
6631		struct scsi_mode_header_10 *mh10;
6632
6633		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6634		bd_len = scsi_2btoul(mh10->blk_desc_len);
6635		break;
6636	}
6637	default:
6638		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6639		break;
6640	}
6641
6642	if (param_len < (header_size + bd_len)) {
6643		free(ctsio->kern_data_ptr, M_CTL);
6644		ctl_set_param_len_error(ctsio);
6645		ctl_done((union ctl_io *)ctsio);
6646		return (CTL_RETVAL_COMPLETE);
6647	}
6648
6649	/*
6650	 * Set the IO_CONT flag, so that if this I/O gets passed to
6651	 * ctl_config_write_done(), it'll get passed back to
6652	 * ctl_do_mode_select() for further processing, or completion if
6653	 * we're all done.
6654	 */
6655	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6656	ctsio->io_cont = ctl_do_mode_select;
6657
6658	modepage_info = (union ctl_modepage_info *)
6659		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6660
6661	memset(modepage_info, 0, sizeof(*modepage_info));
6662
6663	len_left = param_len - header_size - bd_len;
6664	len_used = header_size + bd_len;
6665
6666	modepage_info->header.len_left = len_left;
6667	modepage_info->header.len_used = len_used;
6668
6669	return (ctl_do_mode_select((union ctl_io *)ctsio));
6670}
6671
6672int
6673ctl_mode_sense(struct ctl_scsiio *ctsio)
6674{
6675	struct ctl_lun *lun;
6676	int pc, page_code, dbd, llba, subpage;
6677	int alloc_len, page_len, header_len, total_len;
6678	struct scsi_mode_block_descr *block_desc;
6679	struct ctl_page_index *page_index;
6680	int control_dev;
6681
6682	dbd = 0;
6683	llba = 0;
6684	block_desc = NULL;
6685	page_index = NULL;
6686
6687	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6688
6689	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6690
6691	if (lun->be_lun->lun_type != T_DIRECT)
6692		control_dev = 1;
6693	else
6694		control_dev = 0;
6695
6696	switch (ctsio->cdb[0]) {
6697	case MODE_SENSE_6: {
6698		struct scsi_mode_sense_6 *cdb;
6699
6700		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6701
6702		header_len = sizeof(struct scsi_mode_hdr_6);
6703		if (cdb->byte2 & SMS_DBD)
6704			dbd = 1;
6705		else
6706			header_len += sizeof(struct scsi_mode_block_descr);
6707
6708		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6709		page_code = cdb->page & SMS_PAGE_CODE;
6710		subpage = cdb->subpage;
6711		alloc_len = cdb->length;
6712		break;
6713	}
6714	case MODE_SENSE_10: {
6715		struct scsi_mode_sense_10 *cdb;
6716
6717		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6718
6719		header_len = sizeof(struct scsi_mode_hdr_10);
6720
6721		if (cdb->byte2 & SMS_DBD)
6722			dbd = 1;
6723		else
6724			header_len += sizeof(struct scsi_mode_block_descr);
6725		if (cdb->byte2 & SMS10_LLBAA)
6726			llba = 1;
6727		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6728		page_code = cdb->page & SMS_PAGE_CODE;
6729		subpage = cdb->subpage;
6730		alloc_len = scsi_2btoul(cdb->length);
6731		break;
6732	}
6733	default:
6734		ctl_set_invalid_opcode(ctsio);
6735		ctl_done((union ctl_io *)ctsio);
6736		return (CTL_RETVAL_COMPLETE);
6737		break; /* NOTREACHED */
6738	}
6739
6740	/*
6741	 * We have to make a first pass through to calculate the size of
6742	 * the pages that match the user's query.  Then we allocate enough
6743	 * memory to hold it, and actually copy the data into the buffer.
6744	 */
6745	switch (page_code) {
6746	case SMS_ALL_PAGES_PAGE: {
6747		int i;
6748
6749		page_len = 0;
6750
6751		/*
6752		 * At the moment, values other than 0 and 0xff here are
6753		 * reserved according to SPC-3.
6754		 */
6755		if ((subpage != SMS_SUBPAGE_PAGE_0)
6756		 && (subpage != SMS_SUBPAGE_ALL)) {
6757			ctl_set_invalid_field(ctsio,
6758					      /*sks_valid*/ 1,
6759					      /*command*/ 1,
6760					      /*field*/ 3,
6761					      /*bit_valid*/ 0,
6762					      /*bit*/ 0);
6763			ctl_done((union ctl_io *)ctsio);
6764			return (CTL_RETVAL_COMPLETE);
6765		}
6766
6767		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6768			if ((control_dev != 0)
6769			 && (lun->mode_pages.index[i].page_flags &
6770			     CTL_PAGE_FLAG_DISK_ONLY))
6771				continue;
6772
6773			/*
6774			 * We don't use this subpage if the user didn't
6775			 * request all subpages.
6776			 */
6777			if ((lun->mode_pages.index[i].subpage != 0)
6778			 && (subpage == SMS_SUBPAGE_PAGE_0))
6779				continue;
6780
6781#if 0
6782			printf("found page %#x len %d\n",
6783			       lun->mode_pages.index[i].page_code &
6784			       SMPH_PC_MASK,
6785			       lun->mode_pages.index[i].page_len);
6786#endif
6787			page_len += lun->mode_pages.index[i].page_len;
6788		}
6789		break;
6790	}
6791	default: {
6792		int i;
6793
6794		page_len = 0;
6795
6796		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6797			/* Look for the right page code */
6798			if ((lun->mode_pages.index[i].page_code &
6799			     SMPH_PC_MASK) != page_code)
6800				continue;
6801
6802			/* Look for the right subpage or the subpage wildcard*/
6803			if ((lun->mode_pages.index[i].subpage != subpage)
6804			 && (subpage != SMS_SUBPAGE_ALL))
6805				continue;
6806
6807			/* Make sure the page is supported for this dev type */
6808			if ((control_dev != 0)
6809			 && (lun->mode_pages.index[i].page_flags &
6810			     CTL_PAGE_FLAG_DISK_ONLY))
6811				continue;
6812
6813#if 0
6814			printf("found page %#x len %d\n",
6815			       lun->mode_pages.index[i].page_code &
6816			       SMPH_PC_MASK,
6817			       lun->mode_pages.index[i].page_len);
6818#endif
6819
6820			page_len += lun->mode_pages.index[i].page_len;
6821		}
6822
6823		if (page_len == 0) {
6824			ctl_set_invalid_field(ctsio,
6825					      /*sks_valid*/ 1,
6826					      /*command*/ 1,
6827					      /*field*/ 2,
6828					      /*bit_valid*/ 1,
6829					      /*bit*/ 5);
6830			ctl_done((union ctl_io *)ctsio);
6831			return (CTL_RETVAL_COMPLETE);
6832		}
6833		break;
6834	}
6835	}
6836
6837	total_len = header_len + page_len;
6838#if 0
6839	printf("header_len = %d, page_len = %d, total_len = %d\n",
6840	       header_len, page_len, total_len);
6841#endif
6842
6843	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6844	ctsio->kern_sg_entries = 0;
6845	ctsio->kern_data_resid = 0;
6846	ctsio->kern_rel_offset = 0;
6847	if (total_len < alloc_len) {
6848		ctsio->residual = alloc_len - total_len;
6849		ctsio->kern_data_len = total_len;
6850		ctsio->kern_total_len = total_len;
6851	} else {
6852		ctsio->residual = 0;
6853		ctsio->kern_data_len = alloc_len;
6854		ctsio->kern_total_len = alloc_len;
6855	}
6856
6857	switch (ctsio->cdb[0]) {
6858	case MODE_SENSE_6: {
6859		struct scsi_mode_hdr_6 *header;
6860
6861		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6862
6863		header->datalen = ctl_min(total_len - 1, 254);
6864
6865		if (dbd)
6866			header->block_descr_len = 0;
6867		else
6868			header->block_descr_len =
6869				sizeof(struct scsi_mode_block_descr);
6870		block_desc = (struct scsi_mode_block_descr *)&header[1];
6871		break;
6872	}
6873	case MODE_SENSE_10: {
6874		struct scsi_mode_hdr_10 *header;
6875		int datalen;
6876
6877		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6878
6879		datalen = ctl_min(total_len - 2, 65533);
6880		scsi_ulto2b(datalen, header->datalen);
6881		if (dbd)
6882			scsi_ulto2b(0, header->block_descr_len);
6883		else
6884			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6885				    header->block_descr_len);
6886		block_desc = (struct scsi_mode_block_descr *)&header[1];
6887		break;
6888	}
6889	default:
6890		panic("invalid CDB type %#x", ctsio->cdb[0]);
6891		break; /* NOTREACHED */
6892	}
6893
6894	/*
6895	 * If we've got a disk, use its blocksize in the block
6896	 * descriptor.  Otherwise, just set it to 0.
6897	 */
6898	if (dbd == 0) {
6899		if (control_dev != 0)
6900			scsi_ulto3b(lun->be_lun->blocksize,
6901				    block_desc->block_len);
6902		else
6903			scsi_ulto3b(0, block_desc->block_len);
6904	}
6905
6906	switch (page_code) {
6907	case SMS_ALL_PAGES_PAGE: {
6908		int i, data_used;
6909
6910		data_used = header_len;
6911		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6912			struct ctl_page_index *page_index;
6913
6914			page_index = &lun->mode_pages.index[i];
6915
6916			if ((control_dev != 0)
6917			 && (page_index->page_flags &
6918			    CTL_PAGE_FLAG_DISK_ONLY))
6919				continue;
6920
6921			/*
6922			 * We don't use this subpage if the user didn't
6923			 * request all subpages.  We already checked (above)
6924			 * to make sure the user only specified a subpage
6925			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6926			 */
6927			if ((page_index->subpage != 0)
6928			 && (subpage == SMS_SUBPAGE_PAGE_0))
6929				continue;
6930
6931			/*
6932			 * Call the handler, if it exists, to update the
6933			 * page to the latest values.
6934			 */
6935			if (page_index->sense_handler != NULL)
6936				page_index->sense_handler(ctsio, page_index,pc);
6937
6938			memcpy(ctsio->kern_data_ptr + data_used,
6939			       page_index->page_data +
6940			       (page_index->page_len * pc),
6941			       page_index->page_len);
6942			data_used += page_index->page_len;
6943		}
6944		break;
6945	}
6946	default: {
6947		int i, data_used;
6948
6949		data_used = header_len;
6950
6951		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6952			struct ctl_page_index *page_index;
6953
6954			page_index = &lun->mode_pages.index[i];
6955
6956			/* Look for the right page code */
6957			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6958				continue;
6959
6960			/* Look for the right subpage or the subpage wildcard*/
6961			if ((page_index->subpage != subpage)
6962			 && (subpage != SMS_SUBPAGE_ALL))
6963				continue;
6964
6965			/* Make sure the page is supported for this dev type */
6966			if ((control_dev != 0)
6967			 && (page_index->page_flags &
6968			     CTL_PAGE_FLAG_DISK_ONLY))
6969				continue;
6970
6971			/*
6972			 * Call the handler, if it exists, to update the
6973			 * page to the latest values.
6974			 */
6975			if (page_index->sense_handler != NULL)
6976				page_index->sense_handler(ctsio, page_index,pc);
6977
6978			memcpy(ctsio->kern_data_ptr + data_used,
6979			       page_index->page_data +
6980			       (page_index->page_len * pc),
6981			       page_index->page_len);
6982			data_used += page_index->page_len;
6983		}
6984		break;
6985	}
6986	}
6987
6988	ctsio->scsi_status = SCSI_STATUS_OK;
6989
6990	ctsio->be_move_done = ctl_config_move_done;
6991	ctl_datamove((union ctl_io *)ctsio);
6992
6993	return (CTL_RETVAL_COMPLETE);
6994}
6995
6996int
6997ctl_read_capacity(struct ctl_scsiio *ctsio)
6998{
6999	struct scsi_read_capacity *cdb;
7000	struct scsi_read_capacity_data *data;
7001	struct ctl_lun *lun;
7002	uint32_t lba;
7003
7004	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7005
7006	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7007
7008	lba = scsi_4btoul(cdb->addr);
7009	if (((cdb->pmi & SRC_PMI) == 0)
7010	 && (lba != 0)) {
7011		ctl_set_invalid_field(/*ctsio*/ ctsio,
7012				      /*sks_valid*/ 1,
7013				      /*command*/ 1,
7014				      /*field*/ 2,
7015				      /*bit_valid*/ 0,
7016				      /*bit*/ 0);
7017		ctl_done((union ctl_io *)ctsio);
7018		return (CTL_RETVAL_COMPLETE);
7019	}
7020
7021	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7022
7023	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7024	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7025	ctsio->residual = 0;
7026	ctsio->kern_data_len = sizeof(*data);
7027	ctsio->kern_total_len = sizeof(*data);
7028	ctsio->kern_data_resid = 0;
7029	ctsio->kern_rel_offset = 0;
7030	ctsio->kern_sg_entries = 0;
7031
7032	/*
7033	 * If the maximum LBA is greater than 0xfffffffe, the user must
7034	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7035	 * serivce action set.
7036	 */
7037	if (lun->be_lun->maxlba > 0xfffffffe)
7038		scsi_ulto4b(0xffffffff, data->addr);
7039	else
7040		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7041
7042	/*
7043	 * XXX KDM this may not be 512 bytes...
7044	 */
7045	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7046
7047	ctsio->scsi_status = SCSI_STATUS_OK;
7048
7049	ctsio->be_move_done = ctl_config_move_done;
7050	ctl_datamove((union ctl_io *)ctsio);
7051
7052	return (CTL_RETVAL_COMPLETE);
7053}
7054
7055static int
7056ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7057{
7058	struct scsi_read_capacity_16 *cdb;
7059	struct scsi_read_capacity_data_long *data;
7060	struct ctl_lun *lun;
7061	uint64_t lba;
7062	uint32_t alloc_len;
7063
7064	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7065
7066	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7067
7068	alloc_len = scsi_4btoul(cdb->alloc_len);
7069	lba = scsi_8btou64(cdb->addr);
7070
7071	if ((cdb->reladr & SRC16_PMI)
7072	 && (lba != 0)) {
7073		ctl_set_invalid_field(/*ctsio*/ ctsio,
7074				      /*sks_valid*/ 1,
7075				      /*command*/ 1,
7076				      /*field*/ 2,
7077				      /*bit_valid*/ 0,
7078				      /*bit*/ 0);
7079		ctl_done((union ctl_io *)ctsio);
7080		return (CTL_RETVAL_COMPLETE);
7081	}
7082
7083	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7084
7085	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7086	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7087
7088	if (sizeof(*data) < alloc_len) {
7089		ctsio->residual = alloc_len - sizeof(*data);
7090		ctsio->kern_data_len = sizeof(*data);
7091		ctsio->kern_total_len = sizeof(*data);
7092	} else {
7093		ctsio->residual = 0;
7094		ctsio->kern_data_len = alloc_len;
7095		ctsio->kern_total_len = alloc_len;
7096	}
7097	ctsio->kern_data_resid = 0;
7098	ctsio->kern_rel_offset = 0;
7099	ctsio->kern_sg_entries = 0;
7100
7101	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7102	/* XXX KDM this may not be 512 bytes... */
7103	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7104	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7105	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7106	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7107		data->lalba_lbp[0] |= SRC16_LBPME;
7108
7109	ctsio->scsi_status = SCSI_STATUS_OK;
7110
7111	ctsio->be_move_done = ctl_config_move_done;
7112	ctl_datamove((union ctl_io *)ctsio);
7113
7114	return (CTL_RETVAL_COMPLETE);
7115}
7116
7117int
7118ctl_service_action_in(struct ctl_scsiio *ctsio)
7119{
7120	struct scsi_service_action_in *cdb;
7121	int retval;
7122
7123	CTL_DEBUG_PRINT(("ctl_service_action_in\n"));
7124
7125	cdb = (struct scsi_service_action_in *)ctsio->cdb;
7126
7127	retval = CTL_RETVAL_COMPLETE;
7128
7129	switch (cdb->service_action) {
7130	case SRC16_SERVICE_ACTION:
7131		retval = ctl_read_capacity_16(ctsio);
7132		break;
7133	default:
7134		ctl_set_invalid_field(/*ctsio*/ ctsio,
7135				      /*sks_valid*/ 1,
7136				      /*command*/ 1,
7137				      /*field*/ 1,
7138				      /*bit_valid*/ 1,
7139				      /*bit*/ 4);
7140		ctl_done((union ctl_io *)ctsio);
7141		break;
7142	}
7143
7144	return (retval);
7145}
7146
7147int
7148ctl_maintenance_in(struct ctl_scsiio *ctsio)
7149{
7150	struct scsi_maintenance_in *cdb;
7151	int retval;
7152	int alloc_len, total_len = 0;
7153	int num_target_port_groups, single;
7154	struct ctl_lun *lun;
7155	struct ctl_softc *softc;
7156	struct scsi_target_group_data *rtg_ptr;
7157	struct scsi_target_port_group_descriptor *tpg_desc_ptr1, *tpg_desc_ptr2;
7158	struct scsi_target_port_descriptor  *tp_desc_ptr1_1, *tp_desc_ptr1_2,
7159	                                    *tp_desc_ptr2_1, *tp_desc_ptr2_2;
7160
7161	CTL_DEBUG_PRINT(("ctl_maintenance_in\n"));
7162
7163	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7164	softc = control_softc;
7165	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7166
7167	retval = CTL_RETVAL_COMPLETE;
7168
7169	if ((cdb->byte2 & SERVICE_ACTION_MASK) != SA_RPRT_TRGT_GRP) {
7170		ctl_set_invalid_field(/*ctsio*/ ctsio,
7171				      /*sks_valid*/ 1,
7172				      /*command*/ 1,
7173				      /*field*/ 1,
7174				      /*bit_valid*/ 1,
7175				      /*bit*/ 4);
7176		ctl_done((union ctl_io *)ctsio);
7177		return(retval);
7178	}
7179
7180	mtx_lock(&softc->ctl_lock);
7181	single = ctl_is_single;
7182	mtx_unlock(&softc->ctl_lock);
7183
7184	if (single)
7185        	num_target_port_groups = NUM_TARGET_PORT_GROUPS - 1;
7186	else
7187        	num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7188
7189	total_len = sizeof(struct scsi_target_group_data) +
7190		sizeof(struct scsi_target_port_group_descriptor) *
7191		num_target_port_groups +
7192		sizeof(struct scsi_target_port_descriptor) *
7193		NUM_PORTS_PER_GRP * num_target_port_groups;
7194
7195	alloc_len = scsi_4btoul(cdb->length);
7196
7197	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7198
7199	ctsio->kern_sg_entries = 0;
7200
7201	if (total_len < alloc_len) {
7202		ctsio->residual = alloc_len - total_len;
7203		ctsio->kern_data_len = total_len;
7204		ctsio->kern_total_len = total_len;
7205	} else {
7206		ctsio->residual = 0;
7207		ctsio->kern_data_len = alloc_len;
7208		ctsio->kern_total_len = alloc_len;
7209	}
7210	ctsio->kern_data_resid = 0;
7211	ctsio->kern_rel_offset = 0;
7212
7213	rtg_ptr = (struct scsi_target_group_data *)ctsio->kern_data_ptr;
7214
7215	tpg_desc_ptr1 = &rtg_ptr->groups[0];
7216	tp_desc_ptr1_1 = &tpg_desc_ptr1->descriptors[0];
7217	tp_desc_ptr1_2 = (struct scsi_target_port_descriptor *)
7218	        &tp_desc_ptr1_1->desc_list[0];
7219
7220	if (single == 0) {
7221		tpg_desc_ptr2 = (struct scsi_target_port_group_descriptor *)
7222	                &tp_desc_ptr1_2->desc_list[0];
7223		tp_desc_ptr2_1 = &tpg_desc_ptr2->descriptors[0];
7224		tp_desc_ptr2_2 = (struct scsi_target_port_descriptor *)
7225	        	&tp_desc_ptr2_1->desc_list[0];
7226        } else {
7227		tpg_desc_ptr2 = NULL;
7228		tp_desc_ptr2_1 = NULL;
7229		tp_desc_ptr2_2 = NULL;
7230	}
7231
7232	scsi_ulto4b(total_len - 4, rtg_ptr->length);
7233	if (single == 0) {
7234        	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7235			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7236				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7237				tpg_desc_ptr2->pref_state =
7238					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7239			} else {
7240				tpg_desc_ptr1->pref_state =
7241					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7242				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7243			}
7244		} else {
7245			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7246				tpg_desc_ptr1->pref_state =
7247					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7248				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7249			} else {
7250				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7251				tpg_desc_ptr2->pref_state =
7252					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7253			}
7254		}
7255	} else {
7256		tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7257	}
7258	tpg_desc_ptr1->support = 0;
7259	tpg_desc_ptr1->target_port_group[1] = 1;
7260	tpg_desc_ptr1->status = TPG_IMPLICIT;
7261	tpg_desc_ptr1->target_port_count= NUM_PORTS_PER_GRP;
7262
7263	if (single == 0) {
7264		tpg_desc_ptr2->support = 0;
7265		tpg_desc_ptr2->target_port_group[1] = 2;
7266		tpg_desc_ptr2->status = TPG_IMPLICIT;
7267		tpg_desc_ptr2->target_port_count = NUM_PORTS_PER_GRP;
7268
7269		tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7270		tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7271
7272		tp_desc_ptr2_1->relative_target_port_identifier[1] = 9;
7273		tp_desc_ptr2_2->relative_target_port_identifier[1] = 10;
7274	} else {
7275        	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7276			tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7277			tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7278		} else {
7279			tp_desc_ptr1_1->relative_target_port_identifier[1] = 9;
7280			tp_desc_ptr1_2->relative_target_port_identifier[1] = 10;
7281		}
7282	}
7283
7284	ctsio->be_move_done = ctl_config_move_done;
7285
7286	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7287			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7288			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7289			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7290			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7291
7292	ctl_datamove((union ctl_io *)ctsio);
7293	return(retval);
7294}
7295
7296int
7297ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7298{
7299	struct scsi_per_res_in *cdb;
7300	int alloc_len, total_len = 0;
7301	/* struct scsi_per_res_in_rsrv in_data; */
7302	struct ctl_lun *lun;
7303	struct ctl_softc *softc;
7304
7305	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7306
7307	softc = control_softc;
7308
7309	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7310
7311	alloc_len = scsi_2btoul(cdb->length);
7312
7313	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7314
7315retry:
7316	mtx_lock(&softc->ctl_lock);
7317	switch (cdb->action) {
7318	case SPRI_RK: /* read keys */
7319		total_len = sizeof(struct scsi_per_res_in_keys) +
7320			lun->pr_key_count *
7321			sizeof(struct scsi_per_res_key);
7322		break;
7323	case SPRI_RR: /* read reservation */
7324		if (lun->flags & CTL_LUN_PR_RESERVED)
7325			total_len = sizeof(struct scsi_per_res_in_rsrv);
7326		else
7327			total_len = sizeof(struct scsi_per_res_in_header);
7328		break;
7329	case SPRI_RC: /* report capabilities */
7330		total_len = sizeof(struct scsi_per_res_cap);
7331		break;
7332	case SPRI_RS: /* read full status */
7333	default:
7334		mtx_unlock(&softc->ctl_lock);
7335		ctl_set_invalid_field(ctsio,
7336				      /*sks_valid*/ 1,
7337				      /*command*/ 1,
7338				      /*field*/ 1,
7339				      /*bit_valid*/ 1,
7340				      /*bit*/ 0);
7341		ctl_done((union ctl_io *)ctsio);
7342		return (CTL_RETVAL_COMPLETE);
7343		break; /* NOTREACHED */
7344	}
7345	mtx_unlock(&softc->ctl_lock);
7346
7347	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7348
7349	if (total_len < alloc_len) {
7350		ctsio->residual = alloc_len - total_len;
7351		ctsio->kern_data_len = total_len;
7352		ctsio->kern_total_len = total_len;
7353	} else {
7354		ctsio->residual = 0;
7355		ctsio->kern_data_len = alloc_len;
7356		ctsio->kern_total_len = alloc_len;
7357	}
7358
7359	ctsio->kern_data_resid = 0;
7360	ctsio->kern_rel_offset = 0;
7361	ctsio->kern_sg_entries = 0;
7362
7363	mtx_lock(&softc->ctl_lock);
7364	switch (cdb->action) {
7365	case SPRI_RK: { // read keys
7366        struct scsi_per_res_in_keys *res_keys;
7367		int i, key_count;
7368
7369		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7370
7371		/*
7372		 * We had to drop the lock to allocate our buffer, which
7373		 * leaves time for someone to come in with another
7374		 * persistent reservation.  (That is unlikely, though,
7375		 * since this should be the only persistent reservation
7376		 * command active right now.)
7377		 */
7378		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7379		    (lun->pr_key_count *
7380		     sizeof(struct scsi_per_res_key)))){
7381			mtx_unlock(&softc->ctl_lock);
7382			free(ctsio->kern_data_ptr, M_CTL);
7383			printf("%s: reservation length changed, retrying\n",
7384			       __func__);
7385			goto retry;
7386		}
7387
7388		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7389
7390		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7391			     lun->pr_key_count, res_keys->header.length);
7392
7393		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7394			if (!lun->per_res[i].registered)
7395				continue;
7396
7397			/*
7398			 * We used lun->pr_key_count to calculate the
7399			 * size to allocate.  If it turns out the number of
7400			 * initiators with the registered flag set is
7401			 * larger than that (i.e. they haven't been kept in
7402			 * sync), we've got a problem.
7403			 */
7404			if (key_count >= lun->pr_key_count) {
7405#ifdef NEEDTOPORT
7406				csevent_log(CSC_CTL | CSC_SHELF_SW |
7407					    CTL_PR_ERROR,
7408					    csevent_LogType_Fault,
7409					    csevent_AlertLevel_Yellow,
7410					    csevent_FRU_ShelfController,
7411					    csevent_FRU_Firmware,
7412				        csevent_FRU_Unknown,
7413					    "registered keys %d >= key "
7414					    "count %d", key_count,
7415					    lun->pr_key_count);
7416#endif
7417				key_count++;
7418				continue;
7419			}
7420			memcpy(res_keys->keys[key_count].key,
7421			       lun->per_res[i].res_key.key,
7422			       ctl_min(sizeof(res_keys->keys[key_count].key),
7423			       sizeof(lun->per_res[i].res_key)));
7424			key_count++;
7425		}
7426		break;
7427	}
7428	case SPRI_RR: { // read reservation
7429		struct scsi_per_res_in_rsrv *res;
7430		int tmp_len, header_only;
7431
7432		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7433
7434		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7435
7436		if (lun->flags & CTL_LUN_PR_RESERVED)
7437		{
7438			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7439			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7440				    res->header.length);
7441			header_only = 0;
7442		} else {
7443			tmp_len = sizeof(struct scsi_per_res_in_header);
7444			scsi_ulto4b(0, res->header.length);
7445			header_only = 1;
7446		}
7447
7448		/*
7449		 * We had to drop the lock to allocate our buffer, which
7450		 * leaves time for someone to come in with another
7451		 * persistent reservation.  (That is unlikely, though,
7452		 * since this should be the only persistent reservation
7453		 * command active right now.)
7454		 */
7455		if (tmp_len != total_len) {
7456			mtx_unlock(&softc->ctl_lock);
7457			free(ctsio->kern_data_ptr, M_CTL);
7458			printf("%s: reservation status changed, retrying\n",
7459			       __func__);
7460			goto retry;
7461		}
7462
7463		/*
7464		 * No reservation held, so we're done.
7465		 */
7466		if (header_only != 0)
7467			break;
7468
7469		/*
7470		 * If the registration is an All Registrants type, the key
7471		 * is 0, since it doesn't really matter.
7472		 */
7473		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7474			memcpy(res->data.reservation,
7475			       &lun->per_res[lun->pr_res_idx].res_key,
7476			       sizeof(struct scsi_per_res_key));
7477		}
7478		res->data.scopetype = lun->res_type;
7479		break;
7480	}
7481	case SPRI_RC:     //report capabilities
7482	{
7483		struct scsi_per_res_cap *res_cap;
7484		uint16_t type_mask;
7485
7486		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7487		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7488		res_cap->flags2 |= SPRI_TMV;
7489		type_mask = SPRI_TM_WR_EX_AR |
7490			    SPRI_TM_EX_AC_RO |
7491			    SPRI_TM_WR_EX_RO |
7492			    SPRI_TM_EX_AC |
7493			    SPRI_TM_WR_EX |
7494			    SPRI_TM_EX_AC_AR;
7495		scsi_ulto2b(type_mask, res_cap->type_mask);
7496		break;
7497	}
7498	case SPRI_RS: //read full status
7499	default:
7500		/*
7501		 * This is a bug, because we just checked for this above,
7502		 * and should have returned an error.
7503		 */
7504		panic("Invalid PR type %x", cdb->action);
7505		break; /* NOTREACHED */
7506	}
7507	mtx_unlock(&softc->ctl_lock);
7508
7509	ctsio->be_move_done = ctl_config_move_done;
7510
7511	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7512			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7513			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7514			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7515			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7516
7517	ctl_datamove((union ctl_io *)ctsio);
7518
7519	return (CTL_RETVAL_COMPLETE);
7520}
7521
7522/*
7523 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7524 * it should return.
7525 */
7526static int
7527ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7528		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7529		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7530		struct scsi_per_res_out_parms* param)
7531{
7532	union ctl_ha_msg persis_io;
7533	int retval, i;
7534	int isc_retval;
7535
7536	retval = 0;
7537
7538	if (sa_res_key == 0) {
7539		mtx_lock(&softc->ctl_lock);
7540		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7541			/* validate scope and type */
7542			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7543			     SPR_LU_SCOPE) {
7544				mtx_unlock(&softc->ctl_lock);
7545				ctl_set_invalid_field(/*ctsio*/ ctsio,
7546						      /*sks_valid*/ 1,
7547						      /*command*/ 1,
7548						      /*field*/ 2,
7549						      /*bit_valid*/ 1,
7550						      /*bit*/ 4);
7551				ctl_done((union ctl_io *)ctsio);
7552				return (1);
7553			}
7554
7555		        if (type>8 || type==2 || type==4 || type==0) {
7556				mtx_unlock(&softc->ctl_lock);
7557				ctl_set_invalid_field(/*ctsio*/ ctsio,
7558       	           				      /*sks_valid*/ 1,
7559						      /*command*/ 1,
7560						      /*field*/ 2,
7561						      /*bit_valid*/ 1,
7562						      /*bit*/ 0);
7563				ctl_done((union ctl_io *)ctsio);
7564				return (1);
7565		        }
7566
7567			/* temporarily unregister this nexus */
7568			lun->per_res[residx].registered = 0;
7569
7570			/*
7571			 * Unregister everybody else and build UA for
7572			 * them
7573			 */
7574			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7575				if (lun->per_res[i].registered == 0)
7576					continue;
7577
7578				if (!persis_offset
7579				 && i <CTL_MAX_INITIATORS)
7580					lun->pending_sense[i].ua_pending |=
7581						CTL_UA_REG_PREEMPT;
7582				else if (persis_offset
7583				      && i >= persis_offset)
7584					lun->pending_sense[i-persis_offset
7585						].ua_pending |=
7586						CTL_UA_REG_PREEMPT;
7587				lun->per_res[i].registered = 0;
7588				memset(&lun->per_res[i].res_key, 0,
7589				       sizeof(struct scsi_per_res_key));
7590			}
7591			lun->per_res[residx].registered = 1;
7592			lun->pr_key_count = 1;
7593			lun->res_type = type;
7594			if (lun->res_type != SPR_TYPE_WR_EX_AR
7595			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7596				lun->pr_res_idx = residx;
7597
7598			mtx_unlock(&softc->ctl_lock);
7599			/* send msg to other side */
7600			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7601			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7602			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7603			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7604			persis_io.pr.pr_info.res_type = type;
7605			memcpy(persis_io.pr.pr_info.sa_res_key,
7606			       param->serv_act_res_key,
7607			       sizeof(param->serv_act_res_key));
7608			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7609			     &persis_io, sizeof(persis_io), 0)) >
7610			     CTL_HA_STATUS_SUCCESS) {
7611				printf("CTL:Persis Out error returned "
7612				       "from ctl_ha_msg_send %d\n",
7613				       isc_retval);
7614			}
7615		} else {
7616			/* not all registrants */
7617			mtx_unlock(&softc->ctl_lock);
7618			free(ctsio->kern_data_ptr, M_CTL);
7619			ctl_set_invalid_field(ctsio,
7620					      /*sks_valid*/ 1,
7621					      /*command*/ 0,
7622					      /*field*/ 8,
7623					      /*bit_valid*/ 0,
7624					      /*bit*/ 0);
7625			ctl_done((union ctl_io *)ctsio);
7626			return (1);
7627		}
7628	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7629		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7630		int found = 0;
7631
7632		mtx_lock(&softc->ctl_lock);
7633		if (res_key == sa_res_key) {
7634			/* special case */
7635			/*
7636			 * The spec implies this is not good but doesn't
7637			 * say what to do. There are two choices either
7638			 * generate a res conflict or check condition
7639			 * with illegal field in parameter data. Since
7640			 * that is what is done when the sa_res_key is
7641			 * zero I'll take that approach since this has
7642			 * to do with the sa_res_key.
7643			 */
7644			mtx_unlock(&softc->ctl_lock);
7645			free(ctsio->kern_data_ptr, M_CTL);
7646			ctl_set_invalid_field(ctsio,
7647					      /*sks_valid*/ 1,
7648					      /*command*/ 0,
7649					      /*field*/ 8,
7650					      /*bit_valid*/ 0,
7651					      /*bit*/ 0);
7652			ctl_done((union ctl_io *)ctsio);
7653			return (1);
7654		}
7655
7656		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7657			if (lun->per_res[i].registered
7658			 && memcmp(param->serv_act_res_key,
7659			    lun->per_res[i].res_key.key,
7660			    sizeof(struct scsi_per_res_key)) != 0)
7661				continue;
7662
7663			found = 1;
7664			lun->per_res[i].registered = 0;
7665			memset(&lun->per_res[i].res_key, 0,
7666			       sizeof(struct scsi_per_res_key));
7667			lun->pr_key_count--;
7668
7669			if (!persis_offset
7670			 && i < CTL_MAX_INITIATORS)
7671				lun->pending_sense[i].ua_pending |=
7672					CTL_UA_REG_PREEMPT;
7673			else if (persis_offset
7674			      && i >= persis_offset)
7675				lun->pending_sense[i-persis_offset].ua_pending|=
7676					CTL_UA_REG_PREEMPT;
7677		}
7678		mtx_unlock(&softc->ctl_lock);
7679		if (!found) {
7680			free(ctsio->kern_data_ptr, M_CTL);
7681			ctl_set_reservation_conflict(ctsio);
7682			ctl_done((union ctl_io *)ctsio);
7683			return (CTL_RETVAL_COMPLETE);
7684		}
7685		/* send msg to other side */
7686		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7687		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7688		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7689		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7690		persis_io.pr.pr_info.res_type = type;
7691		memcpy(persis_io.pr.pr_info.sa_res_key,
7692		       param->serv_act_res_key,
7693		       sizeof(param->serv_act_res_key));
7694		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7695		     &persis_io, sizeof(persis_io), 0)) >
7696		     CTL_HA_STATUS_SUCCESS) {
7697			printf("CTL:Persis Out error returned from "
7698			       "ctl_ha_msg_send %d\n", isc_retval);
7699		}
7700	} else {
7701		/* Reserved but not all registrants */
7702		/* sa_res_key is res holder */
7703		if (memcmp(param->serv_act_res_key,
7704                   lun->per_res[lun->pr_res_idx].res_key.key,
7705                   sizeof(struct scsi_per_res_key)) == 0) {
7706			/* validate scope and type */
7707			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7708			     SPR_LU_SCOPE) {
7709				ctl_set_invalid_field(/*ctsio*/ ctsio,
7710						      /*sks_valid*/ 1,
7711						      /*command*/ 1,
7712						      /*field*/ 2,
7713						      /*bit_valid*/ 1,
7714						      /*bit*/ 4);
7715				ctl_done((union ctl_io *)ctsio);
7716				return (1);
7717			}
7718
7719			if (type>8 || type==2 || type==4 || type==0) {
7720				ctl_set_invalid_field(/*ctsio*/ ctsio,
7721						      /*sks_valid*/ 1,
7722						      /*command*/ 1,
7723						      /*field*/ 2,
7724						      /*bit_valid*/ 1,
7725						      /*bit*/ 0);
7726				ctl_done((union ctl_io *)ctsio);
7727				return (1);
7728			}
7729
7730			/*
7731			 * Do the following:
7732			 * if sa_res_key != res_key remove all
7733			 * registrants w/sa_res_key and generate UA
7734			 * for these registrants(Registrations
7735			 * Preempted) if it wasn't an exclusive
7736			 * reservation generate UA(Reservations
7737			 * Preempted) for all other registered nexuses
7738			 * if the type has changed. Establish the new
7739			 * reservation and holder. If res_key and
7740			 * sa_res_key are the same do the above
7741			 * except don't unregister the res holder.
7742			 */
7743
7744			/*
7745			 * Temporarily unregister so it won't get
7746			 * removed or UA generated
7747			 */
7748			lun->per_res[residx].registered = 0;
7749			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7750				if (lun->per_res[i].registered == 0)
7751					continue;
7752
7753				if (memcmp(param->serv_act_res_key,
7754				    lun->per_res[i].res_key.key,
7755				    sizeof(struct scsi_per_res_key)) == 0) {
7756					lun->per_res[i].registered = 0;
7757					memset(&lun->per_res[i].res_key,
7758					       0,
7759					       sizeof(struct scsi_per_res_key));
7760					lun->pr_key_count--;
7761
7762					if (!persis_offset
7763					 && i < CTL_MAX_INITIATORS)
7764						lun->pending_sense[i
7765							].ua_pending |=
7766							CTL_UA_REG_PREEMPT;
7767					else if (persis_offset
7768					      && i >= persis_offset)
7769						lun->pending_sense[
7770						  i-persis_offset].ua_pending |=
7771						  CTL_UA_REG_PREEMPT;
7772				} else if (type != lun->res_type
7773					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7774					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7775						if (!persis_offset
7776						 && i < CTL_MAX_INITIATORS)
7777							lun->pending_sense[i
7778							].ua_pending |=
7779							CTL_UA_RES_RELEASE;
7780						else if (persis_offset
7781						      && i >= persis_offset)
7782							lun->pending_sense[
7783							i-persis_offset
7784							].ua_pending |=
7785							CTL_UA_RES_RELEASE;
7786				}
7787			}
7788			lun->per_res[residx].registered = 1;
7789			lun->res_type = type;
7790			if (lun->res_type != SPR_TYPE_WR_EX_AR
7791			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7792				lun->pr_res_idx = residx;
7793			else
7794				lun->pr_res_idx =
7795					CTL_PR_ALL_REGISTRANTS;
7796
7797			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7798			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7799			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7800			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7801			persis_io.pr.pr_info.res_type = type;
7802			memcpy(persis_io.pr.pr_info.sa_res_key,
7803			       param->serv_act_res_key,
7804			       sizeof(param->serv_act_res_key));
7805			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7806			     &persis_io, sizeof(persis_io), 0)) >
7807			     CTL_HA_STATUS_SUCCESS) {
7808				printf("CTL:Persis Out error returned "
7809				       "from ctl_ha_msg_send %d\n",
7810				       isc_retval);
7811			}
7812		} else {
7813			/*
7814			 * sa_res_key is not the res holder just
7815			 * remove registrants
7816			 */
7817			int found=0;
7818			mtx_lock(&softc->ctl_lock);
7819
7820			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7821				if (memcmp(param->serv_act_res_key,
7822				    lun->per_res[i].res_key.key,
7823				    sizeof(struct scsi_per_res_key)) != 0)
7824					continue;
7825
7826				found = 1;
7827				lun->per_res[i].registered = 0;
7828				memset(&lun->per_res[i].res_key, 0,
7829				       sizeof(struct scsi_per_res_key));
7830				lun->pr_key_count--;
7831
7832				if (!persis_offset
7833				 && i < CTL_MAX_INITIATORS)
7834					lun->pending_sense[i].ua_pending |=
7835						CTL_UA_REG_PREEMPT;
7836				else if (persis_offset
7837				      && i >= persis_offset)
7838					lun->pending_sense[
7839						i-persis_offset].ua_pending |=
7840						CTL_UA_REG_PREEMPT;
7841			}
7842
7843			if (!found) {
7844				mtx_unlock(&softc->ctl_lock);
7845				free(ctsio->kern_data_ptr, M_CTL);
7846				ctl_set_reservation_conflict(ctsio);
7847				ctl_done((union ctl_io *)ctsio);
7848		        	return (1);
7849			}
7850			mtx_unlock(&softc->ctl_lock);
7851			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7852			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7853			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7854			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7855			persis_io.pr.pr_info.res_type = type;
7856			memcpy(persis_io.pr.pr_info.sa_res_key,
7857			       param->serv_act_res_key,
7858			       sizeof(param->serv_act_res_key));
7859			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7860			     &persis_io, sizeof(persis_io), 0)) >
7861			     CTL_HA_STATUS_SUCCESS) {
7862				printf("CTL:Persis Out error returned "
7863				       "from ctl_ha_msg_send %d\n",
7864				isc_retval);
7865			}
7866		}
7867	}
7868
7869	lun->PRGeneration++;
7870
7871	return (retval);
7872}
7873
7874static void
7875ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7876{
7877	int i;
7878
7879	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7880	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7881	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
7882		   msg->pr.pr_info.sa_res_key,
7883		   sizeof(struct scsi_per_res_key)) != 0) {
7884		uint64_t sa_res_key;
7885		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7886
7887		if (sa_res_key == 0) {
7888			/* temporarily unregister this nexus */
7889			lun->per_res[msg->pr.pr_info.residx].registered = 0;
7890
7891			/*
7892			 * Unregister everybody else and build UA for
7893			 * them
7894			 */
7895			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7896				if (lun->per_res[i].registered == 0)
7897					continue;
7898
7899				if (!persis_offset
7900				 && i < CTL_MAX_INITIATORS)
7901					lun->pending_sense[i].ua_pending |=
7902						CTL_UA_REG_PREEMPT;
7903				else if (persis_offset && i >= persis_offset)
7904					lun->pending_sense[i -
7905						persis_offset].ua_pending |=
7906						CTL_UA_REG_PREEMPT;
7907				lun->per_res[i].registered = 0;
7908				memset(&lun->per_res[i].res_key, 0,
7909				       sizeof(struct scsi_per_res_key));
7910			}
7911
7912			lun->per_res[msg->pr.pr_info.residx].registered = 1;
7913			lun->pr_key_count = 1;
7914			lun->res_type = msg->pr.pr_info.res_type;
7915			if (lun->res_type != SPR_TYPE_WR_EX_AR
7916			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7917				lun->pr_res_idx = msg->pr.pr_info.residx;
7918		} else {
7919		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7920				if (memcmp(msg->pr.pr_info.sa_res_key,
7921		                   lun->per_res[i].res_key.key,
7922		                   sizeof(struct scsi_per_res_key)) != 0)
7923					continue;
7924
7925				lun->per_res[i].registered = 0;
7926				memset(&lun->per_res[i].res_key, 0,
7927				       sizeof(struct scsi_per_res_key));
7928				lun->pr_key_count--;
7929
7930				if (!persis_offset
7931				 && i < persis_offset)
7932					lun->pending_sense[i].ua_pending |=
7933						CTL_UA_REG_PREEMPT;
7934				else if (persis_offset
7935				      && i >= persis_offset)
7936					lun->pending_sense[i -
7937						persis_offset].ua_pending |=
7938						CTL_UA_REG_PREEMPT;
7939			}
7940		}
7941	} else {
7942		/*
7943		 * Temporarily unregister so it won't get removed
7944		 * or UA generated
7945		 */
7946		lun->per_res[msg->pr.pr_info.residx].registered = 0;
7947		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7948			if (lun->per_res[i].registered == 0)
7949				continue;
7950
7951			if (memcmp(msg->pr.pr_info.sa_res_key,
7952	                   lun->per_res[i].res_key.key,
7953	                   sizeof(struct scsi_per_res_key)) == 0) {
7954				lun->per_res[i].registered = 0;
7955				memset(&lun->per_res[i].res_key, 0,
7956				       sizeof(struct scsi_per_res_key));
7957				lun->pr_key_count--;
7958				if (!persis_offset
7959				 && i < CTL_MAX_INITIATORS)
7960					lun->pending_sense[i].ua_pending |=
7961						CTL_UA_REG_PREEMPT;
7962				else if (persis_offset
7963				      && i >= persis_offset)
7964					lun->pending_sense[i -
7965						persis_offset].ua_pending |=
7966						CTL_UA_REG_PREEMPT;
7967			} else if (msg->pr.pr_info.res_type != lun->res_type
7968				&& (lun->res_type == SPR_TYPE_WR_EX_RO
7969				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
7970					if (!persis_offset
7971					 && i < persis_offset)
7972						lun->pending_sense[i
7973							].ua_pending |=
7974							CTL_UA_RES_RELEASE;
7975					else if (persis_offset
7976					      && i >= persis_offset)
7977					lun->pending_sense[i -
7978						persis_offset].ua_pending |=
7979						CTL_UA_RES_RELEASE;
7980			}
7981		}
7982		lun->per_res[msg->pr.pr_info.residx].registered = 1;
7983		lun->res_type = msg->pr.pr_info.res_type;
7984		if (lun->res_type != SPR_TYPE_WR_EX_AR
7985		 && lun->res_type != SPR_TYPE_EX_AC_AR)
7986			lun->pr_res_idx = msg->pr.pr_info.residx;
7987		else
7988			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7989	}
7990	lun->PRGeneration++;
7991
7992}
7993
7994
7995int
7996ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
7997{
7998	int retval;
7999	int isc_retval;
8000	u_int32_t param_len;
8001	struct scsi_per_res_out *cdb;
8002	struct ctl_lun *lun;
8003	struct scsi_per_res_out_parms* param;
8004	struct ctl_softc *softc;
8005	uint32_t residx;
8006	uint64_t res_key, sa_res_key;
8007	uint8_t type;
8008	union ctl_ha_msg persis_io;
8009	int    i;
8010
8011	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8012
8013	retval = CTL_RETVAL_COMPLETE;
8014
8015	softc = control_softc;
8016
8017	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8018	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8019
8020	/*
8021	 * We only support whole-LUN scope.  The scope & type are ignored for
8022	 * register, register and ignore existing key and clear.
8023	 * We sometimes ignore scope and type on preempts too!!
8024	 * Verify reservation type here as well.
8025	 */
8026	type = cdb->scope_type & SPR_TYPE_MASK;
8027	if ((cdb->action == SPRO_RESERVE)
8028	 || (cdb->action == SPRO_RELEASE)) {
8029		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8030			ctl_set_invalid_field(/*ctsio*/ ctsio,
8031					      /*sks_valid*/ 1,
8032					      /*command*/ 1,
8033					      /*field*/ 2,
8034					      /*bit_valid*/ 1,
8035					      /*bit*/ 4);
8036			ctl_done((union ctl_io *)ctsio);
8037			return (CTL_RETVAL_COMPLETE);
8038		}
8039
8040		if (type>8 || type==2 || type==4 || type==0) {
8041			ctl_set_invalid_field(/*ctsio*/ ctsio,
8042					      /*sks_valid*/ 1,
8043					      /*command*/ 1,
8044					      /*field*/ 2,
8045					      /*bit_valid*/ 1,
8046					      /*bit*/ 0);
8047			ctl_done((union ctl_io *)ctsio);
8048			return (CTL_RETVAL_COMPLETE);
8049		}
8050	}
8051
8052	switch (cdb->action & SPRO_ACTION_MASK) {
8053	case SPRO_REGISTER:
8054	case SPRO_RESERVE:
8055	case SPRO_RELEASE:
8056	case SPRO_CLEAR:
8057	case SPRO_PREEMPT:
8058	case SPRO_REG_IGNO:
8059		break;
8060	case SPRO_REG_MOVE:
8061	case SPRO_PRE_ABO:
8062	default:
8063		ctl_set_invalid_field(/*ctsio*/ ctsio,
8064				      /*sks_valid*/ 1,
8065				      /*command*/ 1,
8066				      /*field*/ 1,
8067				      /*bit_valid*/ 1,
8068				      /*bit*/ 0);
8069		ctl_done((union ctl_io *)ctsio);
8070		return (CTL_RETVAL_COMPLETE);
8071		break; /* NOTREACHED */
8072	}
8073
8074	param_len = scsi_4btoul(cdb->length);
8075
8076	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8077		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8078		ctsio->kern_data_len = param_len;
8079		ctsio->kern_total_len = param_len;
8080		ctsio->kern_data_resid = 0;
8081		ctsio->kern_rel_offset = 0;
8082		ctsio->kern_sg_entries = 0;
8083		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8084		ctsio->be_move_done = ctl_config_move_done;
8085		ctl_datamove((union ctl_io *)ctsio);
8086
8087		return (CTL_RETVAL_COMPLETE);
8088	}
8089
8090	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8091
8092	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8093	res_key = scsi_8btou64(param->res_key.key);
8094	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8095
8096	/*
8097	 * Validate the reservation key here except for SPRO_REG_IGNO
8098	 * This must be done for all other service actions
8099	 */
8100	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8101		mtx_lock(&softc->ctl_lock);
8102		if (lun->per_res[residx].registered) {
8103		    if (memcmp(param->res_key.key,
8104			       lun->per_res[residx].res_key.key,
8105			       ctl_min(sizeof(param->res_key),
8106			       sizeof(lun->per_res[residx].res_key))) != 0) {
8107				/*
8108				 * The current key passed in doesn't match
8109				 * the one the initiator previously
8110				 * registered.
8111				 */
8112				mtx_unlock(&softc->ctl_lock);
8113				free(ctsio->kern_data_ptr, M_CTL);
8114				ctl_set_reservation_conflict(ctsio);
8115				ctl_done((union ctl_io *)ctsio);
8116				return (CTL_RETVAL_COMPLETE);
8117			}
8118		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8119			/*
8120			 * We are not registered
8121			 */
8122			mtx_unlock(&softc->ctl_lock);
8123			free(ctsio->kern_data_ptr, M_CTL);
8124			ctl_set_reservation_conflict(ctsio);
8125			ctl_done((union ctl_io *)ctsio);
8126			return (CTL_RETVAL_COMPLETE);
8127		} else if (res_key != 0) {
8128			/*
8129			 * We are not registered and trying to register but
8130			 * the register key isn't zero.
8131			 */
8132			mtx_unlock(&softc->ctl_lock);
8133			free(ctsio->kern_data_ptr, M_CTL);
8134			ctl_set_reservation_conflict(ctsio);
8135			ctl_done((union ctl_io *)ctsio);
8136			return (CTL_RETVAL_COMPLETE);
8137		}
8138		mtx_unlock(&softc->ctl_lock);
8139	}
8140
8141	switch (cdb->action & SPRO_ACTION_MASK) {
8142	case SPRO_REGISTER:
8143	case SPRO_REG_IGNO: {
8144
8145#if 0
8146		printf("Registration received\n");
8147#endif
8148
8149		/*
8150		 * We don't support any of these options, as we report in
8151		 * the read capabilities request (see
8152		 * ctl_persistent_reserve_in(), above).
8153		 */
8154		if ((param->flags & SPR_SPEC_I_PT)
8155		 || (param->flags & SPR_ALL_TG_PT)
8156		 || (param->flags & SPR_APTPL)) {
8157			int bit_ptr;
8158
8159			if (param->flags & SPR_APTPL)
8160				bit_ptr = 0;
8161			else if (param->flags & SPR_ALL_TG_PT)
8162				bit_ptr = 2;
8163			else /* SPR_SPEC_I_PT */
8164				bit_ptr = 3;
8165
8166			free(ctsio->kern_data_ptr, M_CTL);
8167			ctl_set_invalid_field(ctsio,
8168					      /*sks_valid*/ 1,
8169					      /*command*/ 0,
8170					      /*field*/ 20,
8171					      /*bit_valid*/ 1,
8172					      /*bit*/ bit_ptr);
8173			ctl_done((union ctl_io *)ctsio);
8174			return (CTL_RETVAL_COMPLETE);
8175		}
8176
8177		mtx_lock(&softc->ctl_lock);
8178
8179		/*
8180		 * The initiator wants to clear the
8181		 * key/unregister.
8182		 */
8183		if (sa_res_key == 0) {
8184			if ((res_key == 0
8185			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8186			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8187			  && !lun->per_res[residx].registered)) {
8188				mtx_unlock(&softc->ctl_lock);
8189				goto done;
8190			}
8191
8192			lun->per_res[residx].registered = 0;
8193			memset(&lun->per_res[residx].res_key,
8194			       0, sizeof(lun->per_res[residx].res_key));
8195			lun->pr_key_count--;
8196
8197			if (residx == lun->pr_res_idx) {
8198				lun->flags &= ~CTL_LUN_PR_RESERVED;
8199				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8200
8201				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8202				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8203				 && lun->pr_key_count) {
8204					/*
8205					 * If the reservation is a registrants
8206					 * only type we need to generate a UA
8207					 * for other registered inits.  The
8208					 * sense code should be RESERVATIONS
8209					 * RELEASED
8210					 */
8211
8212					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8213						if (lun->per_res[
8214						    i+persis_offset].registered
8215						    == 0)
8216							continue;
8217						lun->pending_sense[i
8218							].ua_pending |=
8219							CTL_UA_RES_RELEASE;
8220					}
8221				}
8222				lun->res_type = 0;
8223			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8224				if (lun->pr_key_count==0) {
8225					lun->flags &= ~CTL_LUN_PR_RESERVED;
8226					lun->res_type = 0;
8227					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8228				}
8229			}
8230			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8231			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8232			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8233			persis_io.pr.pr_info.residx = residx;
8234			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8235			     &persis_io, sizeof(persis_io), 0 )) >
8236			     CTL_HA_STATUS_SUCCESS) {
8237				printf("CTL:Persis Out error returned from "
8238				       "ctl_ha_msg_send %d\n", isc_retval);
8239			}
8240			mtx_unlock(&softc->ctl_lock);
8241		} else /* sa_res_key != 0 */ {
8242
8243			/*
8244			 * If we aren't registered currently then increment
8245			 * the key count and set the registered flag.
8246			 */
8247			if (!lun->per_res[residx].registered) {
8248				lun->pr_key_count++;
8249				lun->per_res[residx].registered = 1;
8250			}
8251
8252			memcpy(&lun->per_res[residx].res_key,
8253			       param->serv_act_res_key,
8254			       ctl_min(sizeof(param->serv_act_res_key),
8255			       sizeof(lun->per_res[residx].res_key)));
8256
8257			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8258			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8259			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8260			persis_io.pr.pr_info.residx = residx;
8261			memcpy(persis_io.pr.pr_info.sa_res_key,
8262			       param->serv_act_res_key,
8263			       sizeof(param->serv_act_res_key));
8264			mtx_unlock(&softc->ctl_lock);
8265			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8266			     &persis_io, sizeof(persis_io), 0)) >
8267			     CTL_HA_STATUS_SUCCESS) {
8268				printf("CTL:Persis Out error returned from "
8269				       "ctl_ha_msg_send %d\n", isc_retval);
8270			}
8271		}
8272		lun->PRGeneration++;
8273
8274		break;
8275	}
8276	case SPRO_RESERVE:
8277#if 0
8278                printf("Reserve executed type %d\n", type);
8279#endif
8280		mtx_lock(&softc->ctl_lock);
8281		if (lun->flags & CTL_LUN_PR_RESERVED) {
8282			/*
8283			 * if this isn't the reservation holder and it's
8284			 * not a "all registrants" type or if the type is
8285			 * different then we have a conflict
8286			 */
8287			if ((lun->pr_res_idx != residx
8288			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8289			 || lun->res_type != type) {
8290				mtx_unlock(&softc->ctl_lock);
8291				free(ctsio->kern_data_ptr, M_CTL);
8292				ctl_set_reservation_conflict(ctsio);
8293				ctl_done((union ctl_io *)ctsio);
8294				return (CTL_RETVAL_COMPLETE);
8295			}
8296			mtx_unlock(&softc->ctl_lock);
8297		} else /* create a reservation */ {
8298			/*
8299			 * If it's not an "all registrants" type record
8300			 * reservation holder
8301			 */
8302			if (type != SPR_TYPE_WR_EX_AR
8303			 && type != SPR_TYPE_EX_AC_AR)
8304				lun->pr_res_idx = residx; /* Res holder */
8305			else
8306				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8307
8308			lun->flags |= CTL_LUN_PR_RESERVED;
8309			lun->res_type = type;
8310
8311			mtx_unlock(&softc->ctl_lock);
8312
8313			/* send msg to other side */
8314			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8315			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8316			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8317			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8318			persis_io.pr.pr_info.res_type = type;
8319			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8320			     &persis_io, sizeof(persis_io), 0)) >
8321			     CTL_HA_STATUS_SUCCESS) {
8322				printf("CTL:Persis Out error returned from "
8323				       "ctl_ha_msg_send %d\n", isc_retval);
8324			}
8325		}
8326		break;
8327
8328	case SPRO_RELEASE:
8329		mtx_lock(&softc->ctl_lock);
8330		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8331			/* No reservation exists return good status */
8332			mtx_unlock(&softc->ctl_lock);
8333			goto done;
8334		}
8335		/*
8336		 * Is this nexus a reservation holder?
8337		 */
8338		if (lun->pr_res_idx != residx
8339		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8340			/*
8341			 * not a res holder return good status but
8342			 * do nothing
8343			 */
8344			mtx_unlock(&softc->ctl_lock);
8345			goto done;
8346		}
8347
8348		if (lun->res_type != type) {
8349			mtx_unlock(&softc->ctl_lock);
8350			free(ctsio->kern_data_ptr, M_CTL);
8351			ctl_set_illegal_pr_release(ctsio);
8352			ctl_done((union ctl_io *)ctsio);
8353			return (CTL_RETVAL_COMPLETE);
8354		}
8355
8356		/* okay to release */
8357		lun->flags &= ~CTL_LUN_PR_RESERVED;
8358		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8359		lun->res_type = 0;
8360
8361		/*
8362		 * if this isn't an exclusive access
8363		 * res generate UA for all other
8364		 * registrants.
8365		 */
8366		if (type != SPR_TYPE_EX_AC
8367		 && type != SPR_TYPE_WR_EX) {
8368			/*
8369			 * temporarily unregister so we don't generate UA
8370			 */
8371			lun->per_res[residx].registered = 0;
8372
8373			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8374				if (lun->per_res[i+persis_offset].registered
8375				    == 0)
8376					continue;
8377				lun->pending_sense[i].ua_pending |=
8378					CTL_UA_RES_RELEASE;
8379			}
8380
8381			lun->per_res[residx].registered = 1;
8382		}
8383		mtx_unlock(&softc->ctl_lock);
8384		/* Send msg to other side */
8385		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8386		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8387		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8388		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8389		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8390			printf("CTL:Persis Out error returned from "
8391			       "ctl_ha_msg_send %d\n", isc_retval);
8392		}
8393		break;
8394
8395	case SPRO_CLEAR:
8396		/* send msg to other side */
8397
8398		mtx_lock(&softc->ctl_lock);
8399		lun->flags &= ~CTL_LUN_PR_RESERVED;
8400		lun->res_type = 0;
8401		lun->pr_key_count = 0;
8402		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8403
8404
8405		memset(&lun->per_res[residx].res_key,
8406		       0, sizeof(lun->per_res[residx].res_key));
8407		lun->per_res[residx].registered = 0;
8408
8409		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8410			if (lun->per_res[i].registered) {
8411				if (!persis_offset && i < CTL_MAX_INITIATORS)
8412					lun->pending_sense[i].ua_pending |=
8413						CTL_UA_RES_PREEMPT;
8414				else if (persis_offset && i >= persis_offset)
8415					lun->pending_sense[i-persis_offset
8416					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8417
8418				memset(&lun->per_res[i].res_key,
8419				       0, sizeof(struct scsi_per_res_key));
8420				lun->per_res[i].registered = 0;
8421			}
8422		lun->PRGeneration++;
8423		mtx_unlock(&softc->ctl_lock);
8424		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8425		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8426		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8427		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8428		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8429			printf("CTL:Persis Out error returned from "
8430			       "ctl_ha_msg_send %d\n", isc_retval);
8431		}
8432		break;
8433
8434	case SPRO_PREEMPT: {
8435		int nretval;
8436
8437		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8438					  residx, ctsio, cdb, param);
8439		if (nretval != 0)
8440			return (CTL_RETVAL_COMPLETE);
8441		break;
8442	}
8443	case SPRO_REG_MOVE:
8444	case SPRO_PRE_ABO:
8445	default:
8446		free(ctsio->kern_data_ptr, M_CTL);
8447		ctl_set_invalid_field(/*ctsio*/ ctsio,
8448				      /*sks_valid*/ 1,
8449				      /*command*/ 1,
8450				      /*field*/ 1,
8451				      /*bit_valid*/ 1,
8452				      /*bit*/ 0);
8453		ctl_done((union ctl_io *)ctsio);
8454		return (CTL_RETVAL_COMPLETE);
8455		break; /* NOTREACHED */
8456	}
8457
8458done:
8459	free(ctsio->kern_data_ptr, M_CTL);
8460	ctl_set_success(ctsio);
8461	ctl_done((union ctl_io *)ctsio);
8462
8463	return (retval);
8464}
8465
8466/*
8467 * This routine is for handling a message from the other SC pertaining to
8468 * persistent reserve out. All the error checking will have been done
8469 * so only perorming the action need be done here to keep the two
8470 * in sync.
8471 */
8472static void
8473ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8474{
8475	struct ctl_lun *lun;
8476	struct ctl_softc *softc;
8477	int i;
8478	uint32_t targ_lun;
8479
8480	softc = control_softc;
8481
8482	mtx_lock(&softc->ctl_lock);
8483
8484	targ_lun = msg->hdr.nexus.targ_lun;
8485	if (msg->hdr.nexus.lun_map_fn != NULL)
8486		targ_lun = msg->hdr.nexus.lun_map_fn(msg->hdr.nexus.lun_map_arg, targ_lun);
8487	lun = softc->ctl_luns[targ_lun];
8488	switch(msg->pr.pr_info.action) {
8489	case CTL_PR_REG_KEY:
8490		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8491			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8492			lun->pr_key_count++;
8493		}
8494		lun->PRGeneration++;
8495		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8496		       msg->pr.pr_info.sa_res_key,
8497		       sizeof(struct scsi_per_res_key));
8498		break;
8499
8500	case CTL_PR_UNREG_KEY:
8501		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8502		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8503		       0, sizeof(struct scsi_per_res_key));
8504		lun->pr_key_count--;
8505
8506		/* XXX Need to see if the reservation has been released */
8507		/* if so do we need to generate UA? */
8508		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8509			lun->flags &= ~CTL_LUN_PR_RESERVED;
8510			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8511
8512			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8513			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8514			 && lun->pr_key_count) {
8515				/*
8516				 * If the reservation is a registrants
8517				 * only type we need to generate a UA
8518				 * for other registered inits.  The
8519				 * sense code should be RESERVATIONS
8520				 * RELEASED
8521				 */
8522
8523				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8524					if (lun->per_res[i+
8525					    persis_offset].registered == 0)
8526						continue;
8527
8528					lun->pending_sense[i
8529						].ua_pending |=
8530						CTL_UA_RES_RELEASE;
8531				}
8532			}
8533			lun->res_type = 0;
8534		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8535			if (lun->pr_key_count==0) {
8536				lun->flags &= ~CTL_LUN_PR_RESERVED;
8537				lun->res_type = 0;
8538				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8539			}
8540		}
8541		lun->PRGeneration++;
8542		break;
8543
8544	case CTL_PR_RESERVE:
8545		lun->flags |= CTL_LUN_PR_RESERVED;
8546		lun->res_type = msg->pr.pr_info.res_type;
8547		lun->pr_res_idx = msg->pr.pr_info.residx;
8548
8549		break;
8550
8551	case CTL_PR_RELEASE:
8552		/*
8553		 * if this isn't an exclusive access res generate UA for all
8554		 * other registrants.
8555		 */
8556		if (lun->res_type != SPR_TYPE_EX_AC
8557		 && lun->res_type != SPR_TYPE_WR_EX) {
8558			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8559				if (lun->per_res[i+persis_offset].registered)
8560					lun->pending_sense[i].ua_pending |=
8561						CTL_UA_RES_RELEASE;
8562		}
8563
8564		lun->flags &= ~CTL_LUN_PR_RESERVED;
8565		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8566		lun->res_type = 0;
8567		break;
8568
8569	case CTL_PR_PREEMPT:
8570		ctl_pro_preempt_other(lun, msg);
8571		break;
8572	case CTL_PR_CLEAR:
8573		lun->flags &= ~CTL_LUN_PR_RESERVED;
8574		lun->res_type = 0;
8575		lun->pr_key_count = 0;
8576		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8577
8578		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8579			if (lun->per_res[i].registered == 0)
8580				continue;
8581			if (!persis_offset
8582			 && i < CTL_MAX_INITIATORS)
8583				lun->pending_sense[i].ua_pending |=
8584					CTL_UA_RES_PREEMPT;
8585			else if (persis_offset
8586			      && i >= persis_offset)
8587   				lun->pending_sense[i-persis_offset].ua_pending|=
8588					CTL_UA_RES_PREEMPT;
8589			memset(&lun->per_res[i].res_key, 0,
8590			       sizeof(struct scsi_per_res_key));
8591			lun->per_res[i].registered = 0;
8592		}
8593		lun->PRGeneration++;
8594		break;
8595	}
8596
8597	mtx_unlock(&softc->ctl_lock);
8598}
8599
8600int
8601ctl_read_write(struct ctl_scsiio *ctsio)
8602{
8603	struct ctl_lun *lun;
8604	struct ctl_lba_len_flags *lbalen;
8605	uint64_t lba;
8606	uint32_t num_blocks;
8607	int reladdr, fua, dpo, ebp;
8608	int retval;
8609	int isread;
8610
8611	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8612
8613	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8614
8615	reladdr = 0;
8616	fua = 0;
8617	dpo = 0;
8618	ebp = 0;
8619
8620	retval = CTL_RETVAL_COMPLETE;
8621
8622	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8623	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8624	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8625		uint32_t residx;
8626
8627		/*
8628		 * XXX KDM need a lock here.
8629		 */
8630		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8631		if ((lun->res_type == SPR_TYPE_EX_AC
8632		  && residx != lun->pr_res_idx)
8633		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8634		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8635		  && !lun->per_res[residx].registered)) {
8636			ctl_set_reservation_conflict(ctsio);
8637			ctl_done((union ctl_io *)ctsio);
8638			return (CTL_RETVAL_COMPLETE);
8639	        }
8640	}
8641
8642	switch (ctsio->cdb[0]) {
8643	case READ_6:
8644	case WRITE_6: {
8645		struct scsi_rw_6 *cdb;
8646
8647		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8648
8649		lba = scsi_3btoul(cdb->addr);
8650		/* only 5 bits are valid in the most significant address byte */
8651		lba &= 0x1fffff;
8652		num_blocks = cdb->length;
8653		/*
8654		 * This is correct according to SBC-2.
8655		 */
8656		if (num_blocks == 0)
8657			num_blocks = 256;
8658		break;
8659	}
8660	case READ_10:
8661	case WRITE_10: {
8662		struct scsi_rw_10 *cdb;
8663
8664		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8665
8666		if (cdb->byte2 & SRW10_RELADDR)
8667			reladdr = 1;
8668		if (cdb->byte2 & SRW10_FUA)
8669			fua = 1;
8670		if (cdb->byte2 & SRW10_DPO)
8671			dpo = 1;
8672
8673		if ((cdb->opcode == WRITE_10)
8674		 && (cdb->byte2 & SRW10_EBP))
8675			ebp = 1;
8676
8677		lba = scsi_4btoul(cdb->addr);
8678		num_blocks = scsi_2btoul(cdb->length);
8679		break;
8680	}
8681	case WRITE_VERIFY_10: {
8682		struct scsi_write_verify_10 *cdb;
8683
8684		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8685
8686		/*
8687		 * XXX KDM we should do actual write verify support at some
8688		 * point.  This is obviously fake, we're just translating
8689		 * things to a write.  So we don't even bother checking the
8690		 * BYTCHK field, since we don't do any verification.  If
8691		 * the user asks for it, we'll just pretend we did it.
8692		 */
8693		if (cdb->byte2 & SWV_DPO)
8694			dpo = 1;
8695
8696		lba = scsi_4btoul(cdb->addr);
8697		num_blocks = scsi_2btoul(cdb->length);
8698		break;
8699	}
8700	case READ_12:
8701	case WRITE_12: {
8702		struct scsi_rw_12 *cdb;
8703
8704		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8705
8706		if (cdb->byte2 & SRW12_RELADDR)
8707			reladdr = 1;
8708		if (cdb->byte2 & SRW12_FUA)
8709			fua = 1;
8710		if (cdb->byte2 & SRW12_DPO)
8711			dpo = 1;
8712		lba = scsi_4btoul(cdb->addr);
8713		num_blocks = scsi_4btoul(cdb->length);
8714		break;
8715	}
8716	case WRITE_VERIFY_12: {
8717		struct scsi_write_verify_12 *cdb;
8718
8719		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8720
8721		if (cdb->byte2 & SWV_DPO)
8722			dpo = 1;
8723
8724		lba = scsi_4btoul(cdb->addr);
8725		num_blocks = scsi_4btoul(cdb->length);
8726
8727		break;
8728	}
8729	case READ_16:
8730	case WRITE_16: {
8731		struct scsi_rw_16 *cdb;
8732
8733		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8734
8735		if (cdb->byte2 & SRW12_RELADDR)
8736			reladdr = 1;
8737		if (cdb->byte2 & SRW12_FUA)
8738			fua = 1;
8739		if (cdb->byte2 & SRW12_DPO)
8740			dpo = 1;
8741
8742		lba = scsi_8btou64(cdb->addr);
8743		num_blocks = scsi_4btoul(cdb->length);
8744		break;
8745	}
8746	case WRITE_VERIFY_16: {
8747		struct scsi_write_verify_16 *cdb;
8748
8749		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8750
8751		if (cdb->byte2 & SWV_DPO)
8752			dpo = 1;
8753
8754		lba = scsi_8btou64(cdb->addr);
8755		num_blocks = scsi_4btoul(cdb->length);
8756		break;
8757	}
8758	default:
8759		/*
8760		 * We got a command we don't support.  This shouldn't
8761		 * happen, commands should be filtered out above us.
8762		 */
8763		ctl_set_invalid_opcode(ctsio);
8764		ctl_done((union ctl_io *)ctsio);
8765
8766		return (CTL_RETVAL_COMPLETE);
8767		break; /* NOTREACHED */
8768	}
8769
8770	/*
8771	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8772	 * interesting for us, but if RAIDCore is in write-back mode,
8773	 * getting it to do write-through for a particular transaction may
8774	 * not be possible.
8775	 */
8776	/*
8777	 * We don't support relative addressing.  That also requires
8778	 * supporting linked commands, which we don't do.
8779	 */
8780	if (reladdr != 0) {
8781		ctl_set_invalid_field(ctsio,
8782				      /*sks_valid*/ 1,
8783				      /*command*/ 1,
8784				      /*field*/ 1,
8785				      /*bit_valid*/ 1,
8786				      /*bit*/ 0);
8787		ctl_done((union ctl_io *)ctsio);
8788		return (CTL_RETVAL_COMPLETE);
8789	}
8790
8791	/*
8792	 * The first check is to make sure we're in bounds, the second
8793	 * check is to catch wrap-around problems.  If the lba + num blocks
8794	 * is less than the lba, then we've wrapped around and the block
8795	 * range is invalid anyway.
8796	 */
8797	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8798	 || ((lba + num_blocks) < lba)) {
8799		ctl_set_lba_out_of_range(ctsio);
8800		ctl_done((union ctl_io *)ctsio);
8801		return (CTL_RETVAL_COMPLETE);
8802	}
8803
8804	/*
8805	 * According to SBC-3, a transfer length of 0 is not an error.
8806	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8807	 * translates to 256 blocks for those commands.
8808	 */
8809	if (num_blocks == 0) {
8810		ctl_set_success(ctsio);
8811		ctl_done((union ctl_io *)ctsio);
8812		return (CTL_RETVAL_COMPLETE);
8813	}
8814
8815	lbalen = (struct ctl_lba_len_flags *)
8816	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8817	lbalen->lba = lba;
8818	lbalen->len = num_blocks;
8819	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
8820
8821	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8822	ctsio->kern_rel_offset = 0;
8823
8824	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8825
8826	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8827
8828	return (retval);
8829}
8830
8831static int
8832ctl_cnw_cont(union ctl_io *io)
8833{
8834	struct ctl_scsiio *ctsio;
8835	struct ctl_lun *lun;
8836	struct ctl_lba_len_flags *lbalen;
8837	int retval;
8838
8839	ctsio = &io->scsiio;
8840	ctsio->io_hdr.status = CTL_STATUS_NONE;
8841	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8842	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8843	lbalen = (struct ctl_lba_len_flags *)
8844	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8845	lbalen->flags = CTL_LLF_WRITE;
8846
8847	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8848	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8849	return (retval);
8850}
8851
8852int
8853ctl_cnw(struct ctl_scsiio *ctsio)
8854{
8855	struct ctl_lun *lun;
8856	struct ctl_lba_len_flags *lbalen;
8857	uint64_t lba;
8858	uint32_t num_blocks;
8859	int fua, dpo;
8860	int retval;
8861
8862	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8863
8864	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8865
8866	fua = 0;
8867	dpo = 0;
8868
8869	retval = CTL_RETVAL_COMPLETE;
8870
8871	switch (ctsio->cdb[0]) {
8872	case COMPARE_AND_WRITE: {
8873		struct scsi_compare_and_write *cdb;
8874
8875		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8876
8877		if (cdb->byte2 & SRW10_FUA)
8878			fua = 1;
8879		if (cdb->byte2 & SRW10_DPO)
8880			dpo = 1;
8881		lba = scsi_8btou64(cdb->addr);
8882		num_blocks = cdb->length;
8883		break;
8884	}
8885	default:
8886		/*
8887		 * We got a command we don't support.  This shouldn't
8888		 * happen, commands should be filtered out above us.
8889		 */
8890		ctl_set_invalid_opcode(ctsio);
8891		ctl_done((union ctl_io *)ctsio);
8892
8893		return (CTL_RETVAL_COMPLETE);
8894		break; /* NOTREACHED */
8895	}
8896
8897	/*
8898	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8899	 * interesting for us, but if RAIDCore is in write-back mode,
8900	 * getting it to do write-through for a particular transaction may
8901	 * not be possible.
8902	 */
8903
8904	/*
8905	 * The first check is to make sure we're in bounds, the second
8906	 * check is to catch wrap-around problems.  If the lba + num blocks
8907	 * is less than the lba, then we've wrapped around and the block
8908	 * range is invalid anyway.
8909	 */
8910	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8911	 || ((lba + num_blocks) < lba)) {
8912		ctl_set_lba_out_of_range(ctsio);
8913		ctl_done((union ctl_io *)ctsio);
8914		return (CTL_RETVAL_COMPLETE);
8915	}
8916
8917	/*
8918	 * According to SBC-3, a transfer length of 0 is not an error.
8919	 */
8920	if (num_blocks == 0) {
8921		ctl_set_success(ctsio);
8922		ctl_done((union ctl_io *)ctsio);
8923		return (CTL_RETVAL_COMPLETE);
8924	}
8925
8926	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8927	ctsio->kern_rel_offset = 0;
8928
8929	/*
8930	 * Set the IO_CONT flag, so that if this I/O gets passed to
8931	 * ctl_data_submit_done(), it'll get passed back to
8932	 * ctl_ctl_cnw_cont() for further processing.
8933	 */
8934	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8935	ctsio->io_cont = ctl_cnw_cont;
8936
8937	lbalen = (struct ctl_lba_len_flags *)
8938	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8939	lbalen->lba = lba;
8940	lbalen->len = num_blocks;
8941	lbalen->flags = CTL_LLF_COMPARE;
8942
8943	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8944	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8945	return (retval);
8946}
8947
8948int
8949ctl_verify(struct ctl_scsiio *ctsio)
8950{
8951	struct ctl_lun *lun;
8952	struct ctl_lba_len_flags *lbalen;
8953	uint64_t lba;
8954	uint32_t num_blocks;
8955	int bytchk, dpo;
8956	int retval;
8957
8958	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8959
8960	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8961
8962	bytchk = 0;
8963	dpo = 0;
8964	retval = CTL_RETVAL_COMPLETE;
8965
8966	switch (ctsio->cdb[0]) {
8967	case VERIFY_10: {
8968		struct scsi_verify_10 *cdb;
8969
8970		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8971		if (cdb->byte2 & SVFY_BYTCHK)
8972			bytchk = 1;
8973		if (cdb->byte2 & SVFY_DPO)
8974			dpo = 1;
8975		lba = scsi_4btoul(cdb->addr);
8976		num_blocks = scsi_2btoul(cdb->length);
8977		break;
8978	}
8979	case VERIFY_12: {
8980		struct scsi_verify_12 *cdb;
8981
8982		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8983		if (cdb->byte2 & SVFY_BYTCHK)
8984			bytchk = 1;
8985		if (cdb->byte2 & SVFY_DPO)
8986			dpo = 1;
8987		lba = scsi_4btoul(cdb->addr);
8988		num_blocks = scsi_4btoul(cdb->length);
8989		break;
8990	}
8991	case VERIFY_16: {
8992		struct scsi_rw_16 *cdb;
8993
8994		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8995		if (cdb->byte2 & SVFY_BYTCHK)
8996			bytchk = 1;
8997		if (cdb->byte2 & SVFY_DPO)
8998			dpo = 1;
8999		lba = scsi_8btou64(cdb->addr);
9000		num_blocks = scsi_4btoul(cdb->length);
9001		break;
9002	}
9003	default:
9004		/*
9005		 * We got a command we don't support.  This shouldn't
9006		 * happen, commands should be filtered out above us.
9007		 */
9008		ctl_set_invalid_opcode(ctsio);
9009		ctl_done((union ctl_io *)ctsio);
9010		return (CTL_RETVAL_COMPLETE);
9011	}
9012
9013	/*
9014	 * The first check is to make sure we're in bounds, the second
9015	 * check is to catch wrap-around problems.  If the lba + num blocks
9016	 * is less than the lba, then we've wrapped around and the block
9017	 * range is invalid anyway.
9018	 */
9019	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9020	 || ((lba + num_blocks) < lba)) {
9021		ctl_set_lba_out_of_range(ctsio);
9022		ctl_done((union ctl_io *)ctsio);
9023		return (CTL_RETVAL_COMPLETE);
9024	}
9025
9026	/*
9027	 * According to SBC-3, a transfer length of 0 is not an error.
9028	 */
9029	if (num_blocks == 0) {
9030		ctl_set_success(ctsio);
9031		ctl_done((union ctl_io *)ctsio);
9032		return (CTL_RETVAL_COMPLETE);
9033	}
9034
9035	lbalen = (struct ctl_lba_len_flags *)
9036	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9037	lbalen->lba = lba;
9038	lbalen->len = num_blocks;
9039	if (bytchk) {
9040		lbalen->flags = CTL_LLF_COMPARE;
9041		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9042	} else {
9043		lbalen->flags = CTL_LLF_VERIFY;
9044		ctsio->kern_total_len = 0;
9045	}
9046	ctsio->kern_rel_offset = 0;
9047
9048	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9049	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9050	return (retval);
9051}
9052
9053int
9054ctl_report_luns(struct ctl_scsiio *ctsio)
9055{
9056	struct scsi_report_luns *cdb;
9057	struct scsi_report_luns_data *lun_data;
9058	struct ctl_lun *lun, *request_lun;
9059	int num_luns, retval;
9060	uint32_t alloc_len, lun_datalen;
9061	int num_filled, well_known;
9062	uint32_t initidx, targ_lun_id, lun_id;
9063
9064	retval = CTL_RETVAL_COMPLETE;
9065	well_known = 0;
9066
9067	cdb = (struct scsi_report_luns *)ctsio->cdb;
9068
9069	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9070
9071	mtx_lock(&control_softc->ctl_lock);
9072	num_luns = control_softc->num_luns;
9073	mtx_unlock(&control_softc->ctl_lock);
9074
9075	switch (cdb->select_report) {
9076	case RPL_REPORT_DEFAULT:
9077	case RPL_REPORT_ALL:
9078		break;
9079	case RPL_REPORT_WELLKNOWN:
9080		well_known = 1;
9081		num_luns = 0;
9082		break;
9083	default:
9084		ctl_set_invalid_field(ctsio,
9085				      /*sks_valid*/ 1,
9086				      /*command*/ 1,
9087				      /*field*/ 2,
9088				      /*bit_valid*/ 0,
9089				      /*bit*/ 0);
9090		ctl_done((union ctl_io *)ctsio);
9091		return (retval);
9092		break; /* NOTREACHED */
9093	}
9094
9095	alloc_len = scsi_4btoul(cdb->length);
9096	/*
9097	 * The initiator has to allocate at least 16 bytes for this request,
9098	 * so he can at least get the header and the first LUN.  Otherwise
9099	 * we reject the request (per SPC-3 rev 14, section 6.21).
9100	 */
9101	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9102	    sizeof(struct scsi_report_luns_lundata))) {
9103		ctl_set_invalid_field(ctsio,
9104				      /*sks_valid*/ 1,
9105				      /*command*/ 1,
9106				      /*field*/ 6,
9107				      /*bit_valid*/ 0,
9108				      /*bit*/ 0);
9109		ctl_done((union ctl_io *)ctsio);
9110		return (retval);
9111	}
9112
9113	request_lun = (struct ctl_lun *)
9114		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9115
9116	lun_datalen = sizeof(*lun_data) +
9117		(num_luns * sizeof(struct scsi_report_luns_lundata));
9118
9119	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9120	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9121	ctsio->kern_sg_entries = 0;
9122
9123	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9124
9125	mtx_lock(&control_softc->ctl_lock);
9126	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9127		lun_id = targ_lun_id;
9128		if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
9129			lun_id = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, lun_id);
9130		if (lun_id >= CTL_MAX_LUNS)
9131			continue;
9132		lun = control_softc->ctl_luns[lun_id];
9133		if (lun == NULL)
9134			continue;
9135
9136		if (targ_lun_id <= 0xff) {
9137			/*
9138			 * Peripheral addressing method, bus number 0.
9139			 */
9140			lun_data->luns[num_filled].lundata[0] =
9141				RPL_LUNDATA_ATYP_PERIPH;
9142			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9143			num_filled++;
9144		} else if (targ_lun_id <= 0x3fff) {
9145			/*
9146			 * Flat addressing method.
9147			 */
9148			lun_data->luns[num_filled].lundata[0] =
9149				RPL_LUNDATA_ATYP_FLAT |
9150				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9151#ifdef OLDCTLHEADERS
9152				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9153				(targ_lun_id & SRLD_BUS_LUN_MASK);
9154#endif
9155			lun_data->luns[num_filled].lundata[1] =
9156#ifdef OLDCTLHEADERS
9157				targ_lun_id >> SRLD_BUS_LUN_BITS;
9158#endif
9159				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9160			num_filled++;
9161		} else {
9162			printf("ctl_report_luns: bogus LUN number %jd, "
9163			       "skipping\n", (intmax_t)targ_lun_id);
9164		}
9165		/*
9166		 * According to SPC-3, rev 14 section 6.21:
9167		 *
9168		 * "The execution of a REPORT LUNS command to any valid and
9169		 * installed logical unit shall clear the REPORTED LUNS DATA
9170		 * HAS CHANGED unit attention condition for all logical
9171		 * units of that target with respect to the requesting
9172		 * initiator. A valid and installed logical unit is one
9173		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9174		 * INQUIRY data (see 6.4.2)."
9175		 *
9176		 * If request_lun is NULL, the LUN this report luns command
9177		 * was issued to is either disabled or doesn't exist. In that
9178		 * case, we shouldn't clear any pending lun change unit
9179		 * attention.
9180		 */
9181		if (request_lun != NULL)
9182			lun->pending_sense[initidx].ua_pending &=
9183				~CTL_UA_LUN_CHANGE;
9184	}
9185	mtx_unlock(&control_softc->ctl_lock);
9186
9187	/*
9188	 * It's quite possible that we've returned fewer LUNs than we allocated
9189	 * space for.  Trim it.
9190	 */
9191	lun_datalen = sizeof(*lun_data) +
9192		(num_filled * sizeof(struct scsi_report_luns_lundata));
9193
9194	if (lun_datalen < alloc_len) {
9195		ctsio->residual = alloc_len - lun_datalen;
9196		ctsio->kern_data_len = lun_datalen;
9197		ctsio->kern_total_len = lun_datalen;
9198	} else {
9199		ctsio->residual = 0;
9200		ctsio->kern_data_len = alloc_len;
9201		ctsio->kern_total_len = alloc_len;
9202	}
9203	ctsio->kern_data_resid = 0;
9204	ctsio->kern_rel_offset = 0;
9205	ctsio->kern_sg_entries = 0;
9206
9207	/*
9208	 * We set this to the actual data length, regardless of how much
9209	 * space we actually have to return results.  If the user looks at
9210	 * this value, he'll know whether or not he allocated enough space
9211	 * and reissue the command if necessary.  We don't support well
9212	 * known logical units, so if the user asks for that, return none.
9213	 */
9214	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9215
9216	/*
9217	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9218	 * this request.
9219	 */
9220	ctsio->scsi_status = SCSI_STATUS_OK;
9221
9222	ctsio->be_move_done = ctl_config_move_done;
9223	ctl_datamove((union ctl_io *)ctsio);
9224
9225	return (retval);
9226}
9227
9228int
9229ctl_request_sense(struct ctl_scsiio *ctsio)
9230{
9231	struct scsi_request_sense *cdb;
9232	struct scsi_sense_data *sense_ptr;
9233	struct ctl_lun *lun;
9234	uint32_t initidx;
9235	int have_error;
9236	scsi_sense_data_type sense_format;
9237
9238	cdb = (struct scsi_request_sense *)ctsio->cdb;
9239
9240	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9241
9242	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9243
9244	/*
9245	 * Determine which sense format the user wants.
9246	 */
9247	if (cdb->byte2 & SRS_DESC)
9248		sense_format = SSD_TYPE_DESC;
9249	else
9250		sense_format = SSD_TYPE_FIXED;
9251
9252	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9253	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9254	ctsio->kern_sg_entries = 0;
9255
9256	/*
9257	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9258	 * larger than the largest allowed value for the length field in the
9259	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9260	 */
9261	ctsio->residual = 0;
9262	ctsio->kern_data_len = cdb->length;
9263	ctsio->kern_total_len = cdb->length;
9264
9265	ctsio->kern_data_resid = 0;
9266	ctsio->kern_rel_offset = 0;
9267	ctsio->kern_sg_entries = 0;
9268
9269	/*
9270	 * If we don't have a LUN, we don't have any pending sense.
9271	 */
9272	if (lun == NULL)
9273		goto no_sense;
9274
9275	have_error = 0;
9276	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9277	/*
9278	 * Check for pending sense, and then for pending unit attentions.
9279	 * Pending sense gets returned first, then pending unit attentions.
9280	 */
9281	mtx_lock(&lun->ctl_softc->ctl_lock);
9282	if (ctl_is_set(lun->have_ca, initidx)) {
9283		scsi_sense_data_type stored_format;
9284
9285		/*
9286		 * Check to see which sense format was used for the stored
9287		 * sense data.
9288		 */
9289		stored_format = scsi_sense_type(
9290		    &lun->pending_sense[initidx].sense);
9291
9292		/*
9293		 * If the user requested a different sense format than the
9294		 * one we stored, then we need to convert it to the other
9295		 * format.  If we're going from descriptor to fixed format
9296		 * sense data, we may lose things in translation, depending
9297		 * on what options were used.
9298		 *
9299		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9300		 * for some reason we'll just copy it out as-is.
9301		 */
9302		if ((stored_format == SSD_TYPE_FIXED)
9303		 && (sense_format == SSD_TYPE_DESC))
9304			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9305			    &lun->pending_sense[initidx].sense,
9306			    (struct scsi_sense_data_desc *)sense_ptr);
9307		else if ((stored_format == SSD_TYPE_DESC)
9308		      && (sense_format == SSD_TYPE_FIXED))
9309			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9310			    &lun->pending_sense[initidx].sense,
9311			    (struct scsi_sense_data_fixed *)sense_ptr);
9312		else
9313			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9314			       ctl_min(sizeof(*sense_ptr),
9315			       sizeof(lun->pending_sense[initidx].sense)));
9316
9317		ctl_clear_mask(lun->have_ca, initidx);
9318		have_error = 1;
9319	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9320		ctl_ua_type ua_type;
9321
9322		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9323				       sense_ptr, sense_format);
9324		if (ua_type != CTL_UA_NONE) {
9325			have_error = 1;
9326			/* We're reporting this UA, so clear it */
9327			lun->pending_sense[initidx].ua_pending &= ~ua_type;
9328		}
9329	}
9330	mtx_unlock(&lun->ctl_softc->ctl_lock);
9331
9332	/*
9333	 * We already have a pending error, return it.
9334	 */
9335	if (have_error != 0) {
9336		/*
9337		 * We report the SCSI status as OK, since the status of the
9338		 * request sense command itself is OK.
9339		 */
9340		ctsio->scsi_status = SCSI_STATUS_OK;
9341
9342		/*
9343		 * We report 0 for the sense length, because we aren't doing
9344		 * autosense in this case.  We're reporting sense as
9345		 * parameter data.
9346		 */
9347		ctsio->sense_len = 0;
9348
9349		ctsio->be_move_done = ctl_config_move_done;
9350		ctl_datamove((union ctl_io *)ctsio);
9351
9352		return (CTL_RETVAL_COMPLETE);
9353	}
9354
9355no_sense:
9356
9357	/*
9358	 * No sense information to report, so we report that everything is
9359	 * okay.
9360	 */
9361	ctl_set_sense_data(sense_ptr,
9362			   lun,
9363			   sense_format,
9364			   /*current_error*/ 1,
9365			   /*sense_key*/ SSD_KEY_NO_SENSE,
9366			   /*asc*/ 0x00,
9367			   /*ascq*/ 0x00,
9368			   SSD_ELEM_NONE);
9369
9370	ctsio->scsi_status = SCSI_STATUS_OK;
9371
9372	/*
9373	 * We report 0 for the sense length, because we aren't doing
9374	 * autosense in this case.  We're reporting sense as parameter data.
9375	 */
9376	ctsio->sense_len = 0;
9377	ctsio->be_move_done = ctl_config_move_done;
9378	ctl_datamove((union ctl_io *)ctsio);
9379
9380	return (CTL_RETVAL_COMPLETE);
9381}
9382
9383int
9384ctl_tur(struct ctl_scsiio *ctsio)
9385{
9386	struct ctl_lun *lun;
9387
9388	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9389
9390	CTL_DEBUG_PRINT(("ctl_tur\n"));
9391
9392	if (lun == NULL)
9393		return (-EINVAL);
9394
9395	ctsio->scsi_status = SCSI_STATUS_OK;
9396	ctsio->io_hdr.status = CTL_SUCCESS;
9397
9398	ctl_done((union ctl_io *)ctsio);
9399
9400	return (CTL_RETVAL_COMPLETE);
9401}
9402
9403#ifdef notyet
9404static int
9405ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9406{
9407
9408}
9409#endif
9410
9411static int
9412ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9413{
9414	struct scsi_vpd_supported_pages *pages;
9415	int sup_page_size;
9416	struct ctl_lun *lun;
9417
9418	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9419
9420	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9421	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9422	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9423	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9424	ctsio->kern_sg_entries = 0;
9425
9426	if (sup_page_size < alloc_len) {
9427		ctsio->residual = alloc_len - sup_page_size;
9428		ctsio->kern_data_len = sup_page_size;
9429		ctsio->kern_total_len = sup_page_size;
9430	} else {
9431		ctsio->residual = 0;
9432		ctsio->kern_data_len = alloc_len;
9433		ctsio->kern_total_len = alloc_len;
9434	}
9435	ctsio->kern_data_resid = 0;
9436	ctsio->kern_rel_offset = 0;
9437	ctsio->kern_sg_entries = 0;
9438
9439	/*
9440	 * The control device is always connected.  The disk device, on the
9441	 * other hand, may not be online all the time.  Need to change this
9442	 * to figure out whether the disk device is actually online or not.
9443	 */
9444	if (lun != NULL)
9445		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9446				lun->be_lun->lun_type;
9447	else
9448		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9449
9450	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9451	/* Supported VPD pages */
9452	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9453	/* Serial Number */
9454	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9455	/* Device Identification */
9456	pages->page_list[2] = SVPD_DEVICE_ID;
9457	/* Block limits */
9458	pages->page_list[3] = SVPD_BLOCK_LIMITS;
9459	/* Logical Block Provisioning */
9460	pages->page_list[4] = SVPD_LBP;
9461
9462	ctsio->scsi_status = SCSI_STATUS_OK;
9463
9464	ctsio->be_move_done = ctl_config_move_done;
9465	ctl_datamove((union ctl_io *)ctsio);
9466
9467	return (CTL_RETVAL_COMPLETE);
9468}
9469
9470static int
9471ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9472{
9473	struct scsi_vpd_unit_serial_number *sn_ptr;
9474	struct ctl_lun *lun;
9475
9476	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9477
9478	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9479	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9480	ctsio->kern_sg_entries = 0;
9481
9482	if (sizeof(*sn_ptr) < alloc_len) {
9483		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9484		ctsio->kern_data_len = sizeof(*sn_ptr);
9485		ctsio->kern_total_len = sizeof(*sn_ptr);
9486	} else {
9487		ctsio->residual = 0;
9488		ctsio->kern_data_len = alloc_len;
9489		ctsio->kern_total_len = alloc_len;
9490	}
9491	ctsio->kern_data_resid = 0;
9492	ctsio->kern_rel_offset = 0;
9493	ctsio->kern_sg_entries = 0;
9494
9495	/*
9496	 * The control device is always connected.  The disk device, on the
9497	 * other hand, may not be online all the time.  Need to change this
9498	 * to figure out whether the disk device is actually online or not.
9499	 */
9500	if (lun != NULL)
9501		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9502				  lun->be_lun->lun_type;
9503	else
9504		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9505
9506	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9507	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9508	/*
9509	 * If we don't have a LUN, we just leave the serial number as
9510	 * all spaces.
9511	 */
9512	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9513	if (lun != NULL) {
9514		strncpy((char *)sn_ptr->serial_num,
9515			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9516	}
9517	ctsio->scsi_status = SCSI_STATUS_OK;
9518
9519	ctsio->be_move_done = ctl_config_move_done;
9520	ctl_datamove((union ctl_io *)ctsio);
9521
9522	return (CTL_RETVAL_COMPLETE);
9523}
9524
9525
9526static int
9527ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9528{
9529	struct scsi_vpd_device_id *devid_ptr;
9530	struct scsi_vpd_id_descriptor *desc, *desc1;
9531	struct scsi_vpd_id_descriptor *desc2, *desc3; /* for types 4h and 5h */
9532	struct scsi_vpd_id_t10 *t10id;
9533	struct ctl_softc *ctl_softc;
9534	struct ctl_lun *lun;
9535	struct ctl_frontend *fe;
9536	char *val;
9537	int data_len, devid_len;
9538
9539	ctl_softc = control_softc;
9540
9541	mtx_lock(&ctl_softc->ctl_lock);
9542	fe = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9543	mtx_unlock(&ctl_softc->ctl_lock);
9544
9545	if (fe->devid != NULL)
9546		return ((fe->devid)(ctsio, alloc_len));
9547
9548	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9549
9550	if (lun == NULL) {
9551		devid_len = CTL_DEVID_MIN_LEN;
9552	} else {
9553		devid_len = max(CTL_DEVID_MIN_LEN,
9554		    strnlen(lun->be_lun->device_id, CTL_DEVID_LEN));
9555	}
9556
9557	data_len = sizeof(struct scsi_vpd_device_id) +
9558		sizeof(struct scsi_vpd_id_descriptor) +
9559		sizeof(struct scsi_vpd_id_t10) + devid_len +
9560		sizeof(struct scsi_vpd_id_descriptor) + CTL_WWPN_LEN +
9561		sizeof(struct scsi_vpd_id_descriptor) +
9562		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9563		sizeof(struct scsi_vpd_id_descriptor) +
9564		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9565
9566	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9567	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9568	ctsio->kern_sg_entries = 0;
9569
9570	if (data_len < alloc_len) {
9571		ctsio->residual = alloc_len - data_len;
9572		ctsio->kern_data_len = data_len;
9573		ctsio->kern_total_len = data_len;
9574	} else {
9575		ctsio->residual = 0;
9576		ctsio->kern_data_len = alloc_len;
9577		ctsio->kern_total_len = alloc_len;
9578	}
9579	ctsio->kern_data_resid = 0;
9580	ctsio->kern_rel_offset = 0;
9581	ctsio->kern_sg_entries = 0;
9582
9583	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9584	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
9585	desc1 = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9586		sizeof(struct scsi_vpd_id_t10) + devid_len);
9587	desc2 = (struct scsi_vpd_id_descriptor *)(&desc1->identifier[0] +
9588	          CTL_WWPN_LEN);
9589	desc3 = (struct scsi_vpd_id_descriptor *)(&desc2->identifier[0] +
9590	         sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9591
9592	/*
9593	 * The control device is always connected.  The disk device, on the
9594	 * other hand, may not be online all the time.
9595	 */
9596	if (lun != NULL)
9597		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9598				     lun->be_lun->lun_type;
9599	else
9600		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9601
9602	devid_ptr->page_code = SVPD_DEVICE_ID;
9603
9604	scsi_ulto2b(data_len - 4, devid_ptr->length);
9605
9606	mtx_lock(&ctl_softc->ctl_lock);
9607
9608	/*
9609	 * For Fibre channel,
9610	 */
9611	if (fe->port_type == CTL_PORT_FC)
9612	{
9613		desc->proto_codeset = (SCSI_PROTO_FC << 4) |
9614				      SVPD_ID_CODESET_ASCII;
9615        	desc1->proto_codeset = (SCSI_PROTO_FC << 4) |
9616		              SVPD_ID_CODESET_BINARY;
9617	}
9618	else
9619	{
9620		desc->proto_codeset = (SCSI_PROTO_SPI << 4) |
9621				      SVPD_ID_CODESET_ASCII;
9622        	desc1->proto_codeset = (SCSI_PROTO_SPI << 4) |
9623		              SVPD_ID_CODESET_BINARY;
9624	}
9625	desc2->proto_codeset = desc3->proto_codeset = desc1->proto_codeset;
9626	mtx_unlock(&ctl_softc->ctl_lock);
9627
9628	/*
9629	 * We're using a LUN association here.  i.e., this device ID is a
9630	 * per-LUN identifier.
9631	 */
9632	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
9633	desc->length = sizeof(*t10id) + devid_len;
9634	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "vendor")) == NULL) {
9635		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
9636	} else {
9637		memset(t10id->vendor, ' ', sizeof(t10id->vendor));
9638		strncpy(t10id->vendor, val,
9639		    min(sizeof(t10id->vendor), strlen(val)));
9640	}
9641
9642	/*
9643	 * desc1 is for the WWPN which is a port asscociation.
9644	 */
9645	desc1->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT | SVPD_ID_TYPE_NAA;
9646	desc1->length = CTL_WWPN_LEN;
9647	/* XXX Call Reggie's get_WWNN func here then add port # to the end */
9648	/* For testing just create the WWPN */
9649#if 0
9650	ddb_GetWWNN((char *)desc1->identifier);
9651
9652	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9653	/* This is so Copancontrol will return something sane */
9654	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9655	    ctsio->io_hdr.nexus.targ_port!=8)
9656		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port-1;
9657	else
9658		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port;
9659#endif
9660
9661	be64enc(desc1->identifier, fe->wwpn);
9662
9663	/*
9664	 * desc2 is for the Relative Target Port(type 4h) identifier
9665	 */
9666	desc2->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9667	                 | SVPD_ID_TYPE_RELTARG;
9668	desc2->length = 4;
9669//#if 0
9670	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9671	/* This is so Copancontrol will return something sane */
9672	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9673	    ctsio->io_hdr.nexus.targ_port!=8)
9674		desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port - 1;
9675	else
9676	        desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port;
9677//#endif
9678
9679	/*
9680	 * desc3 is for the Target Port Group(type 5h) identifier
9681	 */
9682	desc3->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9683	                 | SVPD_ID_TYPE_TPORTGRP;
9684	desc3->length = 4;
9685	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS || ctl_is_single)
9686		desc3->identifier[3] = 1;
9687	else
9688		desc3->identifier[3] = 2;
9689
9690	/*
9691	 * If we've actually got a backend, copy the device id from the
9692	 * per-LUN data.  Otherwise, set it to all spaces.
9693	 */
9694	if (lun != NULL) {
9695		/*
9696		 * Copy the backend's LUN ID.
9697		 */
9698		strncpy((char *)t10id->vendor_spec_id,
9699			(char *)lun->be_lun->device_id, devid_len);
9700	} else {
9701		/*
9702		 * No backend, set this to spaces.
9703		 */
9704		memset(t10id->vendor_spec_id, 0x20, devid_len);
9705	}
9706
9707	ctsio->scsi_status = SCSI_STATUS_OK;
9708
9709	ctsio->be_move_done = ctl_config_move_done;
9710	ctl_datamove((union ctl_io *)ctsio);
9711
9712	return (CTL_RETVAL_COMPLETE);
9713}
9714
9715static int
9716ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9717{
9718	struct scsi_vpd_block_limits *bl_ptr;
9719	struct ctl_lun *lun;
9720	int bs;
9721
9722	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9723	bs = lun->be_lun->blocksize;
9724
9725	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9726	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9727	ctsio->kern_sg_entries = 0;
9728
9729	if (sizeof(*bl_ptr) < alloc_len) {
9730		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9731		ctsio->kern_data_len = sizeof(*bl_ptr);
9732		ctsio->kern_total_len = sizeof(*bl_ptr);
9733	} else {
9734		ctsio->residual = 0;
9735		ctsio->kern_data_len = alloc_len;
9736		ctsio->kern_total_len = alloc_len;
9737	}
9738	ctsio->kern_data_resid = 0;
9739	ctsio->kern_rel_offset = 0;
9740	ctsio->kern_sg_entries = 0;
9741
9742	/*
9743	 * The control device is always connected.  The disk device, on the
9744	 * other hand, may not be online all the time.  Need to change this
9745	 * to figure out whether the disk device is actually online or not.
9746	 */
9747	if (lun != NULL)
9748		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9749				  lun->be_lun->lun_type;
9750	else
9751		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9752
9753	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9754	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
9755	bl_ptr->max_cmp_write_len = 0xff;
9756	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9757	scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
9758	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9759		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9760		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9761	}
9762	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9763
9764	ctsio->scsi_status = SCSI_STATUS_OK;
9765	ctsio->be_move_done = ctl_config_move_done;
9766	ctl_datamove((union ctl_io *)ctsio);
9767
9768	return (CTL_RETVAL_COMPLETE);
9769}
9770
9771static int
9772ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9773{
9774	struct scsi_vpd_logical_block_prov *lbp_ptr;
9775	struct ctl_lun *lun;
9776	int bs;
9777
9778	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9779	bs = lun->be_lun->blocksize;
9780
9781	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9782	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9783	ctsio->kern_sg_entries = 0;
9784
9785	if (sizeof(*lbp_ptr) < alloc_len) {
9786		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9787		ctsio->kern_data_len = sizeof(*lbp_ptr);
9788		ctsio->kern_total_len = sizeof(*lbp_ptr);
9789	} else {
9790		ctsio->residual = 0;
9791		ctsio->kern_data_len = alloc_len;
9792		ctsio->kern_total_len = alloc_len;
9793	}
9794	ctsio->kern_data_resid = 0;
9795	ctsio->kern_rel_offset = 0;
9796	ctsio->kern_sg_entries = 0;
9797
9798	/*
9799	 * The control device is always connected.  The disk device, on the
9800	 * other hand, may not be online all the time.  Need to change this
9801	 * to figure out whether the disk device is actually online or not.
9802	 */
9803	if (lun != NULL)
9804		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9805				  lun->be_lun->lun_type;
9806	else
9807		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9808
9809	lbp_ptr->page_code = SVPD_LBP;
9810	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
9811		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
9812
9813	ctsio->scsi_status = SCSI_STATUS_OK;
9814	ctsio->be_move_done = ctl_config_move_done;
9815	ctl_datamove((union ctl_io *)ctsio);
9816
9817	return (CTL_RETVAL_COMPLETE);
9818}
9819
9820static int
9821ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9822{
9823	struct scsi_inquiry *cdb;
9824	struct ctl_lun *lun;
9825	int alloc_len, retval;
9826
9827	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9828	cdb = (struct scsi_inquiry *)ctsio->cdb;
9829
9830	retval = CTL_RETVAL_COMPLETE;
9831
9832	alloc_len = scsi_2btoul(cdb->length);
9833
9834	switch (cdb->page_code) {
9835	case SVPD_SUPPORTED_PAGES:
9836		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9837		break;
9838	case SVPD_UNIT_SERIAL_NUMBER:
9839		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9840		break;
9841	case SVPD_DEVICE_ID:
9842		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9843		break;
9844	case SVPD_BLOCK_LIMITS:
9845		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9846		break;
9847	case SVPD_LBP:
9848		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9849		break;
9850	default:
9851		ctl_set_invalid_field(ctsio,
9852				      /*sks_valid*/ 1,
9853				      /*command*/ 1,
9854				      /*field*/ 2,
9855				      /*bit_valid*/ 0,
9856				      /*bit*/ 0);
9857		ctl_done((union ctl_io *)ctsio);
9858		retval = CTL_RETVAL_COMPLETE;
9859		break;
9860	}
9861
9862	return (retval);
9863}
9864
9865static int
9866ctl_inquiry_std(struct ctl_scsiio *ctsio)
9867{
9868	struct scsi_inquiry_data *inq_ptr;
9869	struct scsi_inquiry *cdb;
9870	struct ctl_softc *ctl_softc;
9871	struct ctl_lun *lun;
9872	char *val;
9873	uint32_t alloc_len;
9874	int is_fc;
9875
9876	ctl_softc = control_softc;
9877
9878	/*
9879	 * Figure out whether we're talking to a Fibre Channel port or not.
9880	 * We treat the ioctl front end, and any SCSI adapters, as packetized
9881	 * SCSI front ends.
9882	 */
9883	mtx_lock(&ctl_softc->ctl_lock);
9884	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
9885	    CTL_PORT_FC)
9886		is_fc = 0;
9887	else
9888		is_fc = 1;
9889	mtx_unlock(&ctl_softc->ctl_lock);
9890
9891	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9892	cdb = (struct scsi_inquiry *)ctsio->cdb;
9893	alloc_len = scsi_2btoul(cdb->length);
9894
9895	/*
9896	 * We malloc the full inquiry data size here and fill it
9897	 * in.  If the user only asks for less, we'll give him
9898	 * that much.
9899	 */
9900	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
9901	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9902	ctsio->kern_sg_entries = 0;
9903	ctsio->kern_data_resid = 0;
9904	ctsio->kern_rel_offset = 0;
9905
9906	if (sizeof(*inq_ptr) < alloc_len) {
9907		ctsio->residual = alloc_len - sizeof(*inq_ptr);
9908		ctsio->kern_data_len = sizeof(*inq_ptr);
9909		ctsio->kern_total_len = sizeof(*inq_ptr);
9910	} else {
9911		ctsio->residual = 0;
9912		ctsio->kern_data_len = alloc_len;
9913		ctsio->kern_total_len = alloc_len;
9914	}
9915
9916	/*
9917	 * If we have a LUN configured, report it as connected.  Otherwise,
9918	 * report that it is offline or no device is supported, depending
9919	 * on the value of inquiry_pq_no_lun.
9920	 *
9921	 * According to the spec (SPC-4 r34), the peripheral qualifier
9922	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9923	 *
9924	 * "A peripheral device having the specified peripheral device type
9925	 * is not connected to this logical unit. However, the device
9926	 * server is capable of supporting the specified peripheral device
9927	 * type on this logical unit."
9928	 *
9929	 * According to the same spec, the peripheral qualifier
9930	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
9931	 *
9932	 * "The device server is not capable of supporting a peripheral
9933	 * device on this logical unit. For this peripheral qualifier the
9934	 * peripheral device type shall be set to 1Fh. All other peripheral
9935	 * device type values are reserved for this peripheral qualifier."
9936	 *
9937	 * Given the text, it would seem that we probably want to report that
9938	 * the LUN is offline here.  There is no LUN connected, but we can
9939	 * support a LUN at the given LUN number.
9940	 *
9941	 * In the real world, though, it sounds like things are a little
9942	 * different:
9943	 *
9944	 * - Linux, when presented with a LUN with the offline peripheral
9945	 *   qualifier, will create an sg driver instance for it.  So when
9946	 *   you attach it to CTL, you wind up with a ton of sg driver
9947	 *   instances.  (One for every LUN that Linux bothered to probe.)
9948	 *   Linux does this despite the fact that it issues a REPORT LUNs
9949	 *   to LUN 0 to get the inventory of supported LUNs.
9950	 *
9951	 * - There is other anecdotal evidence (from Emulex folks) about
9952	 *   arrays that use the offline peripheral qualifier for LUNs that
9953	 *   are on the "passive" path in an active/passive array.
9954	 *
9955	 * So the solution is provide a hopefully reasonable default
9956	 * (return bad/no LUN) and allow the user to change the behavior
9957	 * with a tunable/sysctl variable.
9958	 */
9959	if (lun != NULL)
9960		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9961				  lun->be_lun->lun_type;
9962	else if (ctl_softc->inquiry_pq_no_lun == 0)
9963		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9964	else
9965		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9966
9967	/* RMB in byte 2 is 0 */
9968	inq_ptr->version = SCSI_REV_SPC3;
9969
9970	/*
9971	 * According to SAM-3, even if a device only supports a single
9972	 * level of LUN addressing, it should still set the HISUP bit:
9973	 *
9974	 * 4.9.1 Logical unit numbers overview
9975	 *
9976	 * All logical unit number formats described in this standard are
9977	 * hierarchical in structure even when only a single level in that
9978	 * hierarchy is used. The HISUP bit shall be set to one in the
9979	 * standard INQUIRY data (see SPC-2) when any logical unit number
9980	 * format described in this standard is used.  Non-hierarchical
9981	 * formats are outside the scope of this standard.
9982	 *
9983	 * Therefore we set the HiSup bit here.
9984	 *
9985	 * The reponse format is 2, per SPC-3.
9986	 */
9987	inq_ptr->response_format = SID_HiSup | 2;
9988
9989	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
9990	CTL_DEBUG_PRINT(("additional_length = %d\n",
9991			 inq_ptr->additional_length));
9992
9993	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
9994	/* 16 bit addressing */
9995	if (is_fc == 0)
9996		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
9997	/* XXX set the SID_MultiP bit here if we're actually going to
9998	   respond on multiple ports */
9999	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10000
10001	/* 16 bit data bus, synchronous transfers */
10002	/* XXX these flags don't apply for FC */
10003	if (is_fc == 0)
10004		inq_ptr->flags = SID_WBus16 | SID_Sync;
10005	/*
10006	 * XXX KDM do we want to support tagged queueing on the control
10007	 * device at all?
10008	 */
10009	if ((lun == NULL)
10010	 || (lun->be_lun->lun_type != T_PROCESSOR))
10011		inq_ptr->flags |= SID_CmdQue;
10012	/*
10013	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10014	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10015	 * name and 4 bytes for the revision.
10016	 */
10017	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "vendor")) == NULL) {
10018		strcpy(inq_ptr->vendor, CTL_VENDOR);
10019	} else {
10020		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10021		strncpy(inq_ptr->vendor, val,
10022		    min(sizeof(inq_ptr->vendor), strlen(val)));
10023	}
10024	if (lun == NULL) {
10025		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10026	} else if ((val = ctl_get_opt(lun->be_lun, "product")) == NULL) {
10027		switch (lun->be_lun->lun_type) {
10028		case T_DIRECT:
10029			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10030			break;
10031		case T_PROCESSOR:
10032			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10033			break;
10034		default:
10035			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10036			break;
10037		}
10038	} else {
10039		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10040		strncpy(inq_ptr->product, val,
10041		    min(sizeof(inq_ptr->product), strlen(val)));
10042	}
10043
10044	/*
10045	 * XXX make this a macro somewhere so it automatically gets
10046	 * incremented when we make changes.
10047	 */
10048	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "revision")) == NULL) {
10049		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10050	} else {
10051		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10052		strncpy(inq_ptr->revision, val,
10053		    min(sizeof(inq_ptr->revision), strlen(val)));
10054	}
10055
10056	/*
10057	 * For parallel SCSI, we support double transition and single
10058	 * transition clocking.  We also support QAS (Quick Arbitration
10059	 * and Selection) and Information Unit transfers on both the
10060	 * control and array devices.
10061	 */
10062	if (is_fc == 0)
10063		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10064				    SID_SPI_IUS;
10065
10066	/* SAM-3 */
10067	scsi_ulto2b(0x0060, inq_ptr->version1);
10068	/* SPC-3 (no version claimed) XXX should we claim a version? */
10069	scsi_ulto2b(0x0300, inq_ptr->version2);
10070	if (is_fc) {
10071		/* FCP-2 ANSI INCITS.350:2003 */
10072		scsi_ulto2b(0x0917, inq_ptr->version3);
10073	} else {
10074		/* SPI-4 ANSI INCITS.362:200x */
10075		scsi_ulto2b(0x0B56, inq_ptr->version3);
10076	}
10077
10078	if (lun == NULL) {
10079		/* SBC-2 (no version claimed) XXX should we claim a version? */
10080		scsi_ulto2b(0x0320, inq_ptr->version4);
10081	} else {
10082		switch (lun->be_lun->lun_type) {
10083		case T_DIRECT:
10084			/*
10085			 * SBC-2 (no version claimed) XXX should we claim a
10086			 * version?
10087			 */
10088			scsi_ulto2b(0x0320, inq_ptr->version4);
10089			break;
10090		case T_PROCESSOR:
10091		default:
10092			break;
10093		}
10094	}
10095
10096	ctsio->scsi_status = SCSI_STATUS_OK;
10097	if (ctsio->kern_data_len > 0) {
10098		ctsio->be_move_done = ctl_config_move_done;
10099		ctl_datamove((union ctl_io *)ctsio);
10100	} else {
10101		ctsio->io_hdr.status = CTL_SUCCESS;
10102		ctl_done((union ctl_io *)ctsio);
10103	}
10104
10105	return (CTL_RETVAL_COMPLETE);
10106}
10107
10108int
10109ctl_inquiry(struct ctl_scsiio *ctsio)
10110{
10111	struct scsi_inquiry *cdb;
10112	int retval;
10113
10114	cdb = (struct scsi_inquiry *)ctsio->cdb;
10115
10116	retval = 0;
10117
10118	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10119
10120	/*
10121	 * Right now, we don't support the CmdDt inquiry information.
10122	 * This would be nice to support in the future.  When we do
10123	 * support it, we should change this test so that it checks to make
10124	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10125	 */
10126#ifdef notyet
10127	if (((cdb->byte2 & SI_EVPD)
10128	 && (cdb->byte2 & SI_CMDDT)))
10129#endif
10130	if (cdb->byte2 & SI_CMDDT) {
10131		/*
10132		 * Point to the SI_CMDDT bit.  We might change this
10133		 * when we support SI_CMDDT, but since both bits would be
10134		 * "wrong", this should probably just stay as-is then.
10135		 */
10136		ctl_set_invalid_field(ctsio,
10137				      /*sks_valid*/ 1,
10138				      /*command*/ 1,
10139				      /*field*/ 1,
10140				      /*bit_valid*/ 1,
10141				      /*bit*/ 1);
10142		ctl_done((union ctl_io *)ctsio);
10143		return (CTL_RETVAL_COMPLETE);
10144	}
10145	if (cdb->byte2 & SI_EVPD)
10146		retval = ctl_inquiry_evpd(ctsio);
10147#ifdef notyet
10148	else if (cdb->byte2 & SI_CMDDT)
10149		retval = ctl_inquiry_cmddt(ctsio);
10150#endif
10151	else
10152		retval = ctl_inquiry_std(ctsio);
10153
10154	return (retval);
10155}
10156
10157/*
10158 * For known CDB types, parse the LBA and length.
10159 */
10160static int
10161ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10162{
10163	if (io->io_hdr.io_type != CTL_IO_SCSI)
10164		return (1);
10165
10166	switch (io->scsiio.cdb[0]) {
10167	case COMPARE_AND_WRITE: {
10168		struct scsi_compare_and_write *cdb;
10169
10170		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10171
10172		*lba = scsi_8btou64(cdb->addr);
10173		*len = cdb->length;
10174		break;
10175	}
10176	case READ_6:
10177	case WRITE_6: {
10178		struct scsi_rw_6 *cdb;
10179
10180		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10181
10182		*lba = scsi_3btoul(cdb->addr);
10183		/* only 5 bits are valid in the most significant address byte */
10184		*lba &= 0x1fffff;
10185		*len = cdb->length;
10186		break;
10187	}
10188	case READ_10:
10189	case WRITE_10: {
10190		struct scsi_rw_10 *cdb;
10191
10192		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10193
10194		*lba = scsi_4btoul(cdb->addr);
10195		*len = scsi_2btoul(cdb->length);
10196		break;
10197	}
10198	case WRITE_VERIFY_10: {
10199		struct scsi_write_verify_10 *cdb;
10200
10201		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10202
10203		*lba = scsi_4btoul(cdb->addr);
10204		*len = scsi_2btoul(cdb->length);
10205		break;
10206	}
10207	case READ_12:
10208	case WRITE_12: {
10209		struct scsi_rw_12 *cdb;
10210
10211		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10212
10213		*lba = scsi_4btoul(cdb->addr);
10214		*len = scsi_4btoul(cdb->length);
10215		break;
10216	}
10217	case WRITE_VERIFY_12: {
10218		struct scsi_write_verify_12 *cdb;
10219
10220		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10221
10222		*lba = scsi_4btoul(cdb->addr);
10223		*len = scsi_4btoul(cdb->length);
10224		break;
10225	}
10226	case READ_16:
10227	case WRITE_16: {
10228		struct scsi_rw_16 *cdb;
10229
10230		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10231
10232		*lba = scsi_8btou64(cdb->addr);
10233		*len = scsi_4btoul(cdb->length);
10234		break;
10235	}
10236	case WRITE_VERIFY_16: {
10237		struct scsi_write_verify_16 *cdb;
10238
10239		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10240
10241
10242		*lba = scsi_8btou64(cdb->addr);
10243		*len = scsi_4btoul(cdb->length);
10244		break;
10245	}
10246	case WRITE_SAME_10: {
10247		struct scsi_write_same_10 *cdb;
10248
10249		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10250
10251		*lba = scsi_4btoul(cdb->addr);
10252		*len = scsi_2btoul(cdb->length);
10253		break;
10254	}
10255	case WRITE_SAME_16: {
10256		struct scsi_write_same_16 *cdb;
10257
10258		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10259
10260		*lba = scsi_8btou64(cdb->addr);
10261		*len = scsi_4btoul(cdb->length);
10262		break;
10263	}
10264	case VERIFY_10: {
10265		struct scsi_verify_10 *cdb;
10266
10267		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10268
10269		*lba = scsi_4btoul(cdb->addr);
10270		*len = scsi_2btoul(cdb->length);
10271		break;
10272	}
10273	case VERIFY_12: {
10274		struct scsi_verify_12 *cdb;
10275
10276		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10277
10278		*lba = scsi_4btoul(cdb->addr);
10279		*len = scsi_4btoul(cdb->length);
10280		break;
10281	}
10282	case VERIFY_16: {
10283		struct scsi_verify_16 *cdb;
10284
10285		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10286
10287		*lba = scsi_8btou64(cdb->addr);
10288		*len = scsi_4btoul(cdb->length);
10289		break;
10290	}
10291	default:
10292		return (1);
10293		break; /* NOTREACHED */
10294	}
10295
10296	return (0);
10297}
10298
10299static ctl_action
10300ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10301{
10302	uint64_t endlba1, endlba2;
10303
10304	endlba1 = lba1 + len1 - 1;
10305	endlba2 = lba2 + len2 - 1;
10306
10307	if ((endlba1 < lba2)
10308	 || (endlba2 < lba1))
10309		return (CTL_ACTION_PASS);
10310	else
10311		return (CTL_ACTION_BLOCK);
10312}
10313
10314static ctl_action
10315ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10316{
10317	uint64_t lba1, lba2;
10318	uint32_t len1, len2;
10319	int retval;
10320
10321	retval = ctl_get_lba_len(io1, &lba1, &len1);
10322	if (retval != 0)
10323		return (CTL_ACTION_ERROR);
10324
10325	retval = ctl_get_lba_len(io2, &lba2, &len2);
10326	if (retval != 0)
10327		return (CTL_ACTION_ERROR);
10328
10329	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10330}
10331
10332static ctl_action
10333ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10334{
10335	struct ctl_cmd_entry *pending_entry, *ooa_entry;
10336	ctl_serialize_action *serialize_row;
10337
10338	/*
10339	 * The initiator attempted multiple untagged commands at the same
10340	 * time.  Can't do that.
10341	 */
10342	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10343	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10344	 && ((pending_io->io_hdr.nexus.targ_port ==
10345	      ooa_io->io_hdr.nexus.targ_port)
10346	  && (pending_io->io_hdr.nexus.initid.id ==
10347	      ooa_io->io_hdr.nexus.initid.id))
10348	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10349		return (CTL_ACTION_OVERLAP);
10350
10351	/*
10352	 * The initiator attempted to send multiple tagged commands with
10353	 * the same ID.  (It's fine if different initiators have the same
10354	 * tag ID.)
10355	 *
10356	 * Even if all of those conditions are true, we don't kill the I/O
10357	 * if the command ahead of us has been aborted.  We won't end up
10358	 * sending it to the FETD, and it's perfectly legal to resend a
10359	 * command with the same tag number as long as the previous
10360	 * instance of this tag number has been aborted somehow.
10361	 */
10362	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10363	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10364	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10365	 && ((pending_io->io_hdr.nexus.targ_port ==
10366	      ooa_io->io_hdr.nexus.targ_port)
10367	  && (pending_io->io_hdr.nexus.initid.id ==
10368	      ooa_io->io_hdr.nexus.initid.id))
10369	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10370		return (CTL_ACTION_OVERLAP_TAG);
10371
10372	/*
10373	 * If we get a head of queue tag, SAM-3 says that we should
10374	 * immediately execute it.
10375	 *
10376	 * What happens if this command would normally block for some other
10377	 * reason?  e.g. a request sense with a head of queue tag
10378	 * immediately after a write.  Normally that would block, but this
10379	 * will result in its getting executed immediately...
10380	 *
10381	 * We currently return "pass" instead of "skip", so we'll end up
10382	 * going through the rest of the queue to check for overlapped tags.
10383	 *
10384	 * XXX KDM check for other types of blockage first??
10385	 */
10386	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10387		return (CTL_ACTION_PASS);
10388
10389	/*
10390	 * Ordered tags have to block until all items ahead of them
10391	 * have completed.  If we get called with an ordered tag, we always
10392	 * block, if something else is ahead of us in the queue.
10393	 */
10394	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10395		return (CTL_ACTION_BLOCK);
10396
10397	/*
10398	 * Simple tags get blocked until all head of queue and ordered tags
10399	 * ahead of them have completed.  I'm lumping untagged commands in
10400	 * with simple tags here.  XXX KDM is that the right thing to do?
10401	 */
10402	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10403	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10404	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10405	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10406		return (CTL_ACTION_BLOCK);
10407
10408	pending_entry = &ctl_cmd_table[pending_io->scsiio.cdb[0]];
10409	ooa_entry = &ctl_cmd_table[ooa_io->scsiio.cdb[0]];
10410
10411	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10412
10413	switch (serialize_row[pending_entry->seridx]) {
10414	case CTL_SER_BLOCK:
10415		return (CTL_ACTION_BLOCK);
10416		break; /* NOTREACHED */
10417	case CTL_SER_EXTENT:
10418		return (ctl_extent_check(pending_io, ooa_io));
10419		break; /* NOTREACHED */
10420	case CTL_SER_PASS:
10421		return (CTL_ACTION_PASS);
10422		break; /* NOTREACHED */
10423	case CTL_SER_SKIP:
10424		return (CTL_ACTION_SKIP);
10425		break;
10426	default:
10427		panic("invalid serialization value %d",
10428		      serialize_row[pending_entry->seridx]);
10429		break; /* NOTREACHED */
10430	}
10431
10432	return (CTL_ACTION_ERROR);
10433}
10434
10435/*
10436 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10437 * Assumptions:
10438 * - pending_io is generally either incoming, or on the blocked queue
10439 * - starting I/O is the I/O we want to start the check with.
10440 */
10441static ctl_action
10442ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10443	      union ctl_io *starting_io)
10444{
10445	union ctl_io *ooa_io;
10446	ctl_action action;
10447
10448	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
10449
10450	/*
10451	 * Run back along the OOA queue, starting with the current
10452	 * blocked I/O and going through every I/O before it on the
10453	 * queue.  If starting_io is NULL, we'll just end up returning
10454	 * CTL_ACTION_PASS.
10455	 */
10456	for (ooa_io = starting_io; ooa_io != NULL;
10457	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10458	     ooa_links)){
10459
10460		/*
10461		 * This routine just checks to see whether
10462		 * cur_blocked is blocked by ooa_io, which is ahead
10463		 * of it in the queue.  It doesn't queue/dequeue
10464		 * cur_blocked.
10465		 */
10466		action = ctl_check_for_blockage(pending_io, ooa_io);
10467		switch (action) {
10468		case CTL_ACTION_BLOCK:
10469		case CTL_ACTION_OVERLAP:
10470		case CTL_ACTION_OVERLAP_TAG:
10471		case CTL_ACTION_SKIP:
10472		case CTL_ACTION_ERROR:
10473			return (action);
10474			break; /* NOTREACHED */
10475		case CTL_ACTION_PASS:
10476			break;
10477		default:
10478			panic("invalid action %d", action);
10479			break;  /* NOTREACHED */
10480		}
10481	}
10482
10483	return (CTL_ACTION_PASS);
10484}
10485
10486/*
10487 * Assumptions:
10488 * - An I/O has just completed, and has been removed from the per-LUN OOA
10489 *   queue, so some items on the blocked queue may now be unblocked.
10490 */
10491static int
10492ctl_check_blocked(struct ctl_lun *lun)
10493{
10494	union ctl_io *cur_blocked, *next_blocked;
10495
10496	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
10497
10498	/*
10499	 * Run forward from the head of the blocked queue, checking each
10500	 * entry against the I/Os prior to it on the OOA queue to see if
10501	 * there is still any blockage.
10502	 *
10503	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10504	 * with our removing a variable on it while it is traversing the
10505	 * list.
10506	 */
10507	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10508	     cur_blocked != NULL; cur_blocked = next_blocked) {
10509		union ctl_io *prev_ooa;
10510		ctl_action action;
10511
10512		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10513							  blocked_links);
10514
10515		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10516						      ctl_ooaq, ooa_links);
10517
10518		/*
10519		 * If cur_blocked happens to be the first item in the OOA
10520		 * queue now, prev_ooa will be NULL, and the action
10521		 * returned will just be CTL_ACTION_PASS.
10522		 */
10523		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10524
10525		switch (action) {
10526		case CTL_ACTION_BLOCK:
10527			/* Nothing to do here, still blocked */
10528			break;
10529		case CTL_ACTION_OVERLAP:
10530		case CTL_ACTION_OVERLAP_TAG:
10531			/*
10532			 * This shouldn't happen!  In theory we've already
10533			 * checked this command for overlap...
10534			 */
10535			break;
10536		case CTL_ACTION_PASS:
10537		case CTL_ACTION_SKIP: {
10538			struct ctl_softc *softc;
10539			struct ctl_cmd_entry *entry;
10540			uint32_t initidx;
10541			uint8_t opcode;
10542			int isc_retval;
10543
10544			/*
10545			 * The skip case shouldn't happen, this transaction
10546			 * should have never made it onto the blocked queue.
10547			 */
10548			/*
10549			 * This I/O is no longer blocked, we can remove it
10550			 * from the blocked queue.  Since this is a TAILQ
10551			 * (doubly linked list), we can do O(1) removals
10552			 * from any place on the list.
10553			 */
10554			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10555				     blocked_links);
10556			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10557
10558			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10559				/*
10560				 * Need to send IO back to original side to
10561				 * run
10562				 */
10563				union ctl_ha_msg msg_info;
10564
10565				msg_info.hdr.original_sc =
10566					cur_blocked->io_hdr.original_sc;
10567				msg_info.hdr.serializing_sc = cur_blocked;
10568				msg_info.hdr.msg_type = CTL_MSG_R2R;
10569				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10570				     &msg_info, sizeof(msg_info), 0)) >
10571				     CTL_HA_STATUS_SUCCESS) {
10572					printf("CTL:Check Blocked error from "
10573					       "ctl_ha_msg_send %d\n",
10574					       isc_retval);
10575				}
10576				break;
10577			}
10578			opcode = cur_blocked->scsiio.cdb[0];
10579			entry = &ctl_cmd_table[opcode];
10580			softc = control_softc;
10581
10582			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10583
10584			/*
10585			 * Check this I/O for LUN state changes that may
10586			 * have happened while this command was blocked.
10587			 * The LUN state may have been changed by a command
10588			 * ahead of us in the queue, so we need to re-check
10589			 * for any states that can be caused by SCSI
10590			 * commands.
10591			 */
10592			if (ctl_scsiio_lun_check(softc, lun, entry,
10593						 &cur_blocked->scsiio) == 0) {
10594				cur_blocked->io_hdr.flags |=
10595				                      CTL_FLAG_IS_WAS_ON_RTR;
10596				STAILQ_INSERT_TAIL(&lun->ctl_softc->rtr_queue,
10597						   &cur_blocked->io_hdr, links);
10598				/*
10599				 * In the non CTL_DONE_THREAD case, we need
10600				 * to wake up the work thread here.  When
10601				 * we're processing completed requests from
10602				 * the work thread context, we'll pop back
10603				 * around and end up pulling things off the
10604				 * RtR queue.  When we aren't processing
10605				 * things from the work thread context,
10606				 * though, we won't ever check the RtR queue.
10607				 * So we need to wake up the thread to clear
10608				 * things off the queue.  Otherwise this
10609				 * transaction will just sit on the RtR queue
10610				 * until a new I/O comes in.  (Which may or
10611				 * may not happen...)
10612				 */
10613#ifndef CTL_DONE_THREAD
10614				ctl_wakeup_thread();
10615#endif
10616			} else
10617				ctl_done_lock(cur_blocked, /*have_lock*/ 1);
10618			break;
10619		}
10620		default:
10621			/*
10622			 * This probably shouldn't happen -- we shouldn't
10623			 * get CTL_ACTION_ERROR, or anything else.
10624			 */
10625			break;
10626		}
10627	}
10628
10629	return (CTL_RETVAL_COMPLETE);
10630}
10631
10632/*
10633 * This routine (with one exception) checks LUN flags that can be set by
10634 * commands ahead of us in the OOA queue.  These flags have to be checked
10635 * when a command initially comes in, and when we pull a command off the
10636 * blocked queue and are preparing to execute it.  The reason we have to
10637 * check these flags for commands on the blocked queue is that the LUN
10638 * state may have been changed by a command ahead of us while we're on the
10639 * blocked queue.
10640 *
10641 * Ordering is somewhat important with these checks, so please pay
10642 * careful attention to the placement of any new checks.
10643 */
10644static int
10645ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10646		     struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10647{
10648	int retval;
10649
10650	retval = 0;
10651
10652	/*
10653	 * If this shelf is a secondary shelf controller, we have to reject
10654	 * any media access commands.
10655	 */
10656#if 0
10657	/* No longer needed for HA */
10658	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10659	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10660		ctl_set_lun_standby(ctsio);
10661		retval = 1;
10662		goto bailout;
10663	}
10664#endif
10665
10666	/*
10667	 * Check for a reservation conflict.  If this command isn't allowed
10668	 * even on reserved LUNs, and if this initiator isn't the one who
10669	 * reserved us, reject the command with a reservation conflict.
10670	 */
10671	if ((lun->flags & CTL_LUN_RESERVED)
10672	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10673		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10674		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10675		 || (ctsio->io_hdr.nexus.targ_target.id !=
10676		     lun->rsv_nexus.targ_target.id)) {
10677			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10678			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10679			retval = 1;
10680			goto bailout;
10681		}
10682	}
10683
10684	if ( (lun->flags & CTL_LUN_PR_RESERVED)
10685	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10686		uint32_t residx;
10687
10688		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10689		/*
10690		 * if we aren't registered or it's a res holder type
10691		 * reservation and this isn't the res holder then set a
10692		 * conflict.
10693		 * NOTE: Commands which might be allowed on write exclusive
10694		 * type reservations are checked in the particular command
10695		 * for a conflict. Read and SSU are the only ones.
10696		 */
10697		if (!lun->per_res[residx].registered
10698		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10699			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10700			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10701			retval = 1;
10702			goto bailout;
10703		}
10704
10705	}
10706
10707	if ((lun->flags & CTL_LUN_OFFLINE)
10708	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10709		ctl_set_lun_not_ready(ctsio);
10710		retval = 1;
10711		goto bailout;
10712	}
10713
10714	/*
10715	 * If the LUN is stopped, see if this particular command is allowed
10716	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10717	 */
10718	if ((lun->flags & CTL_LUN_STOPPED)
10719	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10720		/* "Logical unit not ready, initializing cmd. required" */
10721		ctl_set_lun_stopped(ctsio);
10722		retval = 1;
10723		goto bailout;
10724	}
10725
10726	if ((lun->flags & CTL_LUN_INOPERABLE)
10727	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10728		/* "Medium format corrupted" */
10729		ctl_set_medium_format_corrupted(ctsio);
10730		retval = 1;
10731		goto bailout;
10732	}
10733
10734bailout:
10735	return (retval);
10736
10737}
10738
10739static void
10740ctl_failover_io(union ctl_io *io, int have_lock)
10741{
10742	ctl_set_busy(&io->scsiio);
10743	ctl_done_lock(io, have_lock);
10744}
10745
10746static void
10747ctl_failover(void)
10748{
10749	struct ctl_lun *lun;
10750	struct ctl_softc *ctl_softc;
10751	union ctl_io *next_io, *pending_io;
10752	union ctl_io *io;
10753	int lun_idx;
10754	int i;
10755
10756	ctl_softc = control_softc;
10757
10758	mtx_lock(&ctl_softc->ctl_lock);
10759	/*
10760	 * Remove any cmds from the other SC from the rtr queue.  These
10761	 * will obviously only be for LUNs for which we're the primary.
10762	 * We can't send status or get/send data for these commands.
10763	 * Since they haven't been executed yet, we can just remove them.
10764	 * We'll either abort them or delete them below, depending on
10765	 * which HA mode we're in.
10766	 */
10767	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10768	     io != NULL; io = next_io) {
10769		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10770		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10771			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10772				      ctl_io_hdr, links);
10773	}
10774
10775	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
10776		lun = ctl_softc->ctl_luns[lun_idx];
10777		if (lun==NULL)
10778			continue;
10779
10780		/*
10781		 * Processor LUNs are primary on both sides.
10782		 * XXX will this always be true?
10783		 */
10784		if (lun->be_lun->lun_type == T_PROCESSOR)
10785			continue;
10786
10787		if ((lun->flags & CTL_LUN_PRIMARY_SC)
10788		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10789			printf("FAILOVER: primary lun %d\n", lun_idx);
10790		        /*
10791			 * Remove all commands from the other SC. First from the
10792			 * blocked queue then from the ooa queue. Once we have
10793			 * removed them. Call ctl_check_blocked to see if there
10794			 * is anything that can run.
10795			 */
10796			for (io = (union ctl_io *)TAILQ_FIRST(
10797			     &lun->blocked_queue); io != NULL; io = next_io) {
10798
10799		        	next_io = (union ctl_io *)TAILQ_NEXT(
10800				    &io->io_hdr, blocked_links);
10801
10802				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10803					TAILQ_REMOVE(&lun->blocked_queue,
10804						     &io->io_hdr,blocked_links);
10805					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10806					TAILQ_REMOVE(&lun->ooa_queue,
10807						     &io->io_hdr, ooa_links);
10808
10809					ctl_free_io(io);
10810				}
10811			}
10812
10813			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10814	     		     io != NULL; io = next_io) {
10815
10816		        	next_io = (union ctl_io *)TAILQ_NEXT(
10817				    &io->io_hdr, ooa_links);
10818
10819				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10820
10821					TAILQ_REMOVE(&lun->ooa_queue,
10822						&io->io_hdr,
10823					     	ooa_links);
10824
10825					ctl_free_io(io);
10826				}
10827			}
10828			ctl_check_blocked(lun);
10829		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10830			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10831
10832			printf("FAILOVER: primary lun %d\n", lun_idx);
10833			/*
10834			 * Abort all commands from the other SC.  We can't
10835			 * send status back for them now.  These should get
10836			 * cleaned up when they are completed or come out
10837			 * for a datamove operation.
10838			 */
10839			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10840	     		     io != NULL; io = next_io) {
10841		        	next_io = (union ctl_io *)TAILQ_NEXT(
10842					&io->io_hdr, ooa_links);
10843
10844				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10845					io->io_hdr.flags |= CTL_FLAG_ABORT;
10846			}
10847		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10848			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10849
10850			printf("FAILOVER: secondary lun %d\n", lun_idx);
10851
10852			lun->flags |= CTL_LUN_PRIMARY_SC;
10853
10854			/*
10855			 * We send all I/O that was sent to this controller
10856			 * and redirected to the other side back with
10857			 * busy status, and have the initiator retry it.
10858			 * Figuring out how much data has been transferred,
10859			 * etc. and picking up where we left off would be
10860			 * very tricky.
10861			 *
10862			 * XXX KDM need to remove I/O from the blocked
10863			 * queue as well!
10864			 */
10865			for (pending_io = (union ctl_io *)TAILQ_FIRST(
10866			     &lun->ooa_queue); pending_io != NULL;
10867			     pending_io = next_io) {
10868
10869				next_io =  (union ctl_io *)TAILQ_NEXT(
10870					&pending_io->io_hdr, ooa_links);
10871
10872				pending_io->io_hdr.flags &=
10873					~CTL_FLAG_SENT_2OTHER_SC;
10874
10875				if (pending_io->io_hdr.flags &
10876				    CTL_FLAG_IO_ACTIVE) {
10877					pending_io->io_hdr.flags |=
10878						CTL_FLAG_FAILOVER;
10879				} else {
10880					ctl_set_busy(&pending_io->scsiio);
10881					ctl_done_lock(pending_io,
10882						      /*have_lock*/1);
10883				}
10884			}
10885
10886			/*
10887			 * Build Unit Attention
10888			 */
10889			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10890				lun->pending_sense[i].ua_pending |=
10891				                     CTL_UA_ASYM_ACC_CHANGE;
10892			}
10893		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10894			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10895			printf("FAILOVER: secondary lun %d\n", lun_idx);
10896			/*
10897			 * if the first io on the OOA is not on the RtR queue
10898			 * add it.
10899			 */
10900			lun->flags |= CTL_LUN_PRIMARY_SC;
10901
10902			pending_io = (union ctl_io *)TAILQ_FIRST(
10903			    &lun->ooa_queue);
10904			if (pending_io==NULL) {
10905				printf("Nothing on OOA queue\n");
10906				continue;
10907			}
10908
10909			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10910			if ((pending_io->io_hdr.flags &
10911			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
10912				pending_io->io_hdr.flags |=
10913				    CTL_FLAG_IS_WAS_ON_RTR;
10914				STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
10915						   &pending_io->io_hdr, links);
10916			}
10917#if 0
10918			else
10919			{
10920				printf("Tag 0x%04x is running\n",
10921				      pending_io->scsiio.tag_num);
10922			}
10923#endif
10924
10925			next_io = (union ctl_io *)TAILQ_NEXT(
10926			    &pending_io->io_hdr, ooa_links);
10927			for (pending_io=next_io; pending_io != NULL;
10928			     pending_io = next_io) {
10929				pending_io->io_hdr.flags &=
10930				    ~CTL_FLAG_SENT_2OTHER_SC;
10931				next_io = (union ctl_io *)TAILQ_NEXT(
10932					&pending_io->io_hdr, ooa_links);
10933				if (pending_io->io_hdr.flags &
10934				    CTL_FLAG_IS_WAS_ON_RTR) {
10935#if 0
10936				        printf("Tag 0x%04x is running\n",
10937				      		pending_io->scsiio.tag_num);
10938#endif
10939					continue;
10940				}
10941
10942				switch (ctl_check_ooa(lun, pending_io,
10943			            (union ctl_io *)TAILQ_PREV(
10944				    &pending_io->io_hdr, ctl_ooaq,
10945				    ooa_links))) {
10946
10947				case CTL_ACTION_BLOCK:
10948					TAILQ_INSERT_TAIL(&lun->blocked_queue,
10949							  &pending_io->io_hdr,
10950							  blocked_links);
10951					pending_io->io_hdr.flags |=
10952					    CTL_FLAG_BLOCKED;
10953					break;
10954				case CTL_ACTION_PASS:
10955				case CTL_ACTION_SKIP:
10956					pending_io->io_hdr.flags |=
10957					    CTL_FLAG_IS_WAS_ON_RTR;
10958					STAILQ_INSERT_TAIL(
10959					    &ctl_softc->rtr_queue,
10960					    &pending_io->io_hdr, links);
10961					break;
10962				case CTL_ACTION_OVERLAP:
10963					ctl_set_overlapped_cmd(
10964					    (struct ctl_scsiio *)pending_io);
10965					ctl_done_lock(pending_io,
10966						      /*have_lock*/ 1);
10967					break;
10968				case CTL_ACTION_OVERLAP_TAG:
10969					ctl_set_overlapped_tag(
10970					    (struct ctl_scsiio *)pending_io,
10971					    pending_io->scsiio.tag_num & 0xff);
10972					ctl_done_lock(pending_io,
10973						      /*have_lock*/ 1);
10974					break;
10975				case CTL_ACTION_ERROR:
10976				default:
10977					ctl_set_internal_failure(
10978						(struct ctl_scsiio *)pending_io,
10979						0,  // sks_valid
10980						0); //retry count
10981					ctl_done_lock(pending_io,
10982						      /*have_lock*/ 1);
10983					break;
10984				}
10985			}
10986
10987			/*
10988			 * Build Unit Attention
10989			 */
10990			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10991				lun->pending_sense[i].ua_pending |=
10992				                     CTL_UA_ASYM_ACC_CHANGE;
10993			}
10994		} else {
10995			panic("Unhandled HA mode failover, LUN flags = %#x, "
10996			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
10997		}
10998	}
10999	ctl_pause_rtr = 0;
11000	mtx_unlock(&ctl_softc->ctl_lock);
11001}
11002
11003static int
11004ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11005{
11006	struct ctl_lun *lun;
11007	struct ctl_cmd_entry *entry;
11008	uint8_t opcode;
11009	uint32_t initidx, targ_lun;
11010	int retval;
11011
11012	retval = 0;
11013
11014	lun = NULL;
11015
11016	opcode = ctsio->cdb[0];
11017
11018	mtx_lock(&ctl_softc->ctl_lock);
11019
11020	targ_lun = ctsio->io_hdr.nexus.targ_lun;
11021	if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
11022		targ_lun = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, targ_lun);
11023	if ((targ_lun < CTL_MAX_LUNS)
11024	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11025		lun = ctl_softc->ctl_luns[targ_lun];
11026		/*
11027		 * If the LUN is invalid, pretend that it doesn't exist.
11028		 * It will go away as soon as all pending I/O has been
11029		 * completed.
11030		 */
11031		if (lun->flags & CTL_LUN_DISABLED) {
11032			lun = NULL;
11033		} else {
11034			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11035			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11036				lun->be_lun;
11037			if (lun->be_lun->lun_type == T_PROCESSOR) {
11038				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11039			}
11040		}
11041	} else {
11042		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11043		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11044	}
11045
11046	entry = &ctl_cmd_table[opcode];
11047
11048	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11049	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11050
11051	/*
11052	 * Check to see whether we can send this command to LUNs that don't
11053	 * exist.  This should pretty much only be the case for inquiry
11054	 * and request sense.  Further checks, below, really require having
11055	 * a LUN, so we can't really check the command anymore.  Just put
11056	 * it on the rtr queue.
11057	 */
11058	if (lun == NULL) {
11059		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
11060			goto queue_rtr;
11061
11062		ctl_set_unsupported_lun(ctsio);
11063		mtx_unlock(&ctl_softc->ctl_lock);
11064		ctl_done((union ctl_io *)ctsio);
11065		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11066		goto bailout;
11067	} else {
11068		/*
11069		 * Every I/O goes into the OOA queue for a particular LUN, and
11070		 * stays there until completion.
11071		 */
11072		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11073
11074		/*
11075		 * Make sure we support this particular command on this LUN.
11076		 * e.g., we don't support writes to the control LUN.
11077		 */
11078		switch (lun->be_lun->lun_type) {
11079		case T_PROCESSOR:
11080		 	if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11081			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
11082			      == 0)) {
11083				ctl_set_invalid_opcode(ctsio);
11084				mtx_unlock(&ctl_softc->ctl_lock);
11085				ctl_done((union ctl_io *)ctsio);
11086				goto bailout;
11087			}
11088			break;
11089		case T_DIRECT:
11090			if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11091			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
11092			      == 0)){
11093				ctl_set_invalid_opcode(ctsio);
11094				mtx_unlock(&ctl_softc->ctl_lock);
11095				ctl_done((union ctl_io *)ctsio);
11096				goto bailout;
11097			}
11098			break;
11099		default:
11100			printf("Unsupported CTL LUN type %d\n",
11101			       lun->be_lun->lun_type);
11102			panic("Unsupported CTL LUN type %d\n",
11103			      lun->be_lun->lun_type);
11104			break; /* NOTREACHED */
11105		}
11106	}
11107
11108	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11109
11110	/*
11111	 * If we've got a request sense, it'll clear the contingent
11112	 * allegiance condition.  Otherwise, if we have a CA condition for
11113	 * this initiator, clear it, because it sent down a command other
11114	 * than request sense.
11115	 */
11116	if ((opcode != REQUEST_SENSE)
11117	 && (ctl_is_set(lun->have_ca, initidx)))
11118		ctl_clear_mask(lun->have_ca, initidx);
11119
11120	/*
11121	 * If the command has this flag set, it handles its own unit
11122	 * attention reporting, we shouldn't do anything.  Otherwise we
11123	 * check for any pending unit attentions, and send them back to the
11124	 * initiator.  We only do this when a command initially comes in,
11125	 * not when we pull it off the blocked queue.
11126	 *
11127	 * According to SAM-3, section 5.3.2, the order that things get
11128	 * presented back to the host is basically unit attentions caused
11129	 * by some sort of reset event, busy status, reservation conflicts
11130	 * or task set full, and finally any other status.
11131	 *
11132	 * One issue here is that some of the unit attentions we report
11133	 * don't fall into the "reset" category (e.g. "reported luns data
11134	 * has changed").  So reporting it here, before the reservation
11135	 * check, may be technically wrong.  I guess the only thing to do
11136	 * would be to check for and report the reset events here, and then
11137	 * check for the other unit attention types after we check for a
11138	 * reservation conflict.
11139	 *
11140	 * XXX KDM need to fix this
11141	 */
11142	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11143		ctl_ua_type ua_type;
11144
11145		ua_type = lun->pending_sense[initidx].ua_pending;
11146		if (ua_type != CTL_UA_NONE) {
11147			scsi_sense_data_type sense_format;
11148
11149			if (lun != NULL)
11150				sense_format = (lun->flags &
11151				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11152				    SSD_TYPE_FIXED;
11153			else
11154				sense_format = SSD_TYPE_FIXED;
11155
11156			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11157					       sense_format);
11158			if (ua_type != CTL_UA_NONE) {
11159				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11160				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11161						       CTL_AUTOSENSE;
11162				ctsio->sense_len = SSD_FULL_SIZE;
11163				lun->pending_sense[initidx].ua_pending &=
11164					~ua_type;
11165				mtx_unlock(&ctl_softc->ctl_lock);
11166				ctl_done((union ctl_io *)ctsio);
11167				goto bailout;
11168			}
11169		}
11170	}
11171
11172
11173	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11174		mtx_unlock(&ctl_softc->ctl_lock);
11175		ctl_done((union ctl_io *)ctsio);
11176		goto bailout;
11177	}
11178
11179	/*
11180	 * XXX CHD this is where we want to send IO to other side if
11181	 * this LUN is secondary on this SC. We will need to make a copy
11182	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11183	 * the copy we send as FROM_OTHER.
11184	 * We also need to stuff the address of the original IO so we can
11185	 * find it easily. Something similar will need be done on the other
11186	 * side so when we are done we can find the copy.
11187	 */
11188	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11189		union ctl_ha_msg msg_info;
11190		int isc_retval;
11191
11192		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11193
11194		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11195		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11196#if 0
11197		printf("1. ctsio %p\n", ctsio);
11198#endif
11199		msg_info.hdr.serializing_sc = NULL;
11200		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11201		msg_info.scsi.tag_num = ctsio->tag_num;
11202		msg_info.scsi.tag_type = ctsio->tag_type;
11203		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11204
11205		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11206
11207		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11208		    (void *)&msg_info, sizeof(msg_info), 0)) >
11209		    CTL_HA_STATUS_SUCCESS) {
11210			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11211			       isc_retval);
11212			printf("CTL:opcode is %x\n",opcode);
11213		} else {
11214#if 0
11215			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11216#endif
11217		}
11218
11219		/*
11220		 * XXX KDM this I/O is off the incoming queue, but hasn't
11221		 * been inserted on any other queue.  We may need to come
11222		 * up with a holding queue while we wait for serialization
11223		 * so that we have an idea of what we're waiting for from
11224		 * the other side.
11225		 */
11226		goto bailout_unlock;
11227	}
11228
11229	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11230			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11231			      ctl_ooaq, ooa_links))) {
11232	case CTL_ACTION_BLOCK:
11233		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11234		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11235				  blocked_links);
11236		goto bailout_unlock;
11237		break; /* NOTREACHED */
11238	case CTL_ACTION_PASS:
11239	case CTL_ACTION_SKIP:
11240		goto queue_rtr;
11241		break; /* NOTREACHED */
11242	case CTL_ACTION_OVERLAP:
11243		ctl_set_overlapped_cmd(ctsio);
11244		mtx_unlock(&ctl_softc->ctl_lock);
11245		ctl_done((union ctl_io *)ctsio);
11246		goto bailout;
11247		break; /* NOTREACHED */
11248	case CTL_ACTION_OVERLAP_TAG:
11249		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11250		mtx_unlock(&ctl_softc->ctl_lock);
11251		ctl_done((union ctl_io *)ctsio);
11252		goto bailout;
11253		break; /* NOTREACHED */
11254	case CTL_ACTION_ERROR:
11255	default:
11256		ctl_set_internal_failure(ctsio,
11257					 /*sks_valid*/ 0,
11258					 /*retry_count*/ 0);
11259		mtx_unlock(&ctl_softc->ctl_lock);
11260		ctl_done((union ctl_io *)ctsio);
11261		goto bailout;
11262		break; /* NOTREACHED */
11263	}
11264
11265	goto bailout_unlock;
11266
11267queue_rtr:
11268	ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11269	STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue, &ctsio->io_hdr, links);
11270
11271bailout_unlock:
11272	mtx_unlock(&ctl_softc->ctl_lock);
11273
11274bailout:
11275	return (retval);
11276}
11277
11278static int
11279ctl_scsiio(struct ctl_scsiio *ctsio)
11280{
11281	int retval;
11282	struct ctl_cmd_entry *entry;
11283
11284	retval = CTL_RETVAL_COMPLETE;
11285
11286	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11287
11288	entry = &ctl_cmd_table[ctsio->cdb[0]];
11289
11290	/*
11291	 * If this I/O has been aborted, just send it straight to
11292	 * ctl_done() without executing it.
11293	 */
11294	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11295		ctl_done((union ctl_io *)ctsio);
11296		goto bailout;
11297	}
11298
11299	/*
11300	 * All the checks should have been handled by ctl_scsiio_precheck().
11301	 * We should be clear now to just execute the I/O.
11302	 */
11303	retval = entry->execute(ctsio);
11304
11305bailout:
11306	return (retval);
11307}
11308
11309/*
11310 * Since we only implement one target right now, a bus reset simply resets
11311 * our single target.
11312 */
11313static int
11314ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11315{
11316	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11317}
11318
11319static int
11320ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11321		 ctl_ua_type ua_type)
11322{
11323	struct ctl_lun *lun;
11324	int retval;
11325
11326	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11327		union ctl_ha_msg msg_info;
11328
11329		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11330		msg_info.hdr.nexus = io->io_hdr.nexus;
11331		if (ua_type==CTL_UA_TARG_RESET)
11332			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11333		else
11334			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11335		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11336		msg_info.hdr.original_sc = NULL;
11337		msg_info.hdr.serializing_sc = NULL;
11338		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11339		    (void *)&msg_info, sizeof(msg_info), 0)) {
11340		}
11341	}
11342	retval = 0;
11343
11344	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11345		retval += ctl_lun_reset(lun, io, ua_type);
11346
11347	return (retval);
11348}
11349
11350/*
11351 * The LUN should always be set.  The I/O is optional, and is used to
11352 * distinguish between I/Os sent by this initiator, and by other
11353 * initiators.  We set unit attention for initiators other than this one.
11354 * SAM-3 is vague on this point.  It does say that a unit attention should
11355 * be established for other initiators when a LUN is reset (see section
11356 * 5.7.3), but it doesn't specifically say that the unit attention should
11357 * be established for this particular initiator when a LUN is reset.  Here
11358 * is the relevant text, from SAM-3 rev 8:
11359 *
11360 * 5.7.2 When a SCSI initiator port aborts its own tasks
11361 *
11362 * When a SCSI initiator port causes its own task(s) to be aborted, no
11363 * notification that the task(s) have been aborted shall be returned to
11364 * the SCSI initiator port other than the completion response for the
11365 * command or task management function action that caused the task(s) to
11366 * be aborted and notification(s) associated with related effects of the
11367 * action (e.g., a reset unit attention condition).
11368 *
11369 * XXX KDM for now, we're setting unit attention for all initiators.
11370 */
11371static int
11372ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11373{
11374	union ctl_io *xio;
11375#if 0
11376	uint32_t initindex;
11377#endif
11378	int i;
11379
11380	/*
11381	 * Run through the OOA queue and abort each I/O.
11382	 */
11383#if 0
11384	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11385#endif
11386	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11387	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11388		xio->io_hdr.flags |= CTL_FLAG_ABORT;
11389	}
11390
11391	/*
11392	 * This version sets unit attention for every
11393	 */
11394#if 0
11395	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11396	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11397		if (initindex == i)
11398			continue;
11399		lun->pending_sense[i].ua_pending |= ua_type;
11400	}
11401#endif
11402
11403	/*
11404	 * A reset (any kind, really) clears reservations established with
11405	 * RESERVE/RELEASE.  It does not clear reservations established
11406	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11407	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11408	 * reservations made with the RESERVE/RELEASE commands, because
11409	 * those commands are obsolete in SPC-3.
11410	 */
11411	lun->flags &= ~CTL_LUN_RESERVED;
11412
11413	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11414		ctl_clear_mask(lun->have_ca, i);
11415		lun->pending_sense[i].ua_pending |= ua_type;
11416	}
11417
11418	return (0);
11419}
11420
11421static int
11422ctl_abort_task(union ctl_io *io)
11423{
11424	union ctl_io *xio;
11425	struct ctl_lun *lun;
11426	struct ctl_softc *ctl_softc;
11427#if 0
11428	struct sbuf sb;
11429	char printbuf[128];
11430#endif
11431	int found;
11432	uint32_t targ_lun;
11433
11434	ctl_softc = control_softc;
11435	found = 0;
11436
11437	/*
11438	 * Look up the LUN.
11439	 */
11440	targ_lun = io->io_hdr.nexus.targ_lun;
11441	if (io->io_hdr.nexus.lun_map_fn != NULL)
11442		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
11443	if ((targ_lun < CTL_MAX_LUNS)
11444	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11445		lun = ctl_softc->ctl_luns[targ_lun];
11446	else
11447		goto bailout;
11448
11449#if 0
11450	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11451	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11452#endif
11453
11454	/*
11455	 * Run through the OOA queue and attempt to find the given I/O.
11456	 * The target port, initiator ID, tag type and tag number have to
11457	 * match the values that we got from the initiator.  If we have an
11458	 * untagged command to abort, simply abort the first untagged command
11459	 * we come to.  We only allow one untagged command at a time of course.
11460	 */
11461#if 0
11462	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11463#endif
11464	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11465	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11466#if 0
11467		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11468
11469		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11470			    lun->lun, xio->scsiio.tag_num,
11471			    xio->scsiio.tag_type,
11472			    (xio->io_hdr.blocked_links.tqe_prev
11473			    == NULL) ? "" : " BLOCKED",
11474			    (xio->io_hdr.flags &
11475			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11476			    (xio->io_hdr.flags &
11477			    CTL_FLAG_ABORT) ? " ABORT" : "",
11478			    (xio->io_hdr.flags &
11479			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11480		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11481		sbuf_finish(&sb);
11482		printf("%s\n", sbuf_data(&sb));
11483#endif
11484
11485		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
11486		 && (xio->io_hdr.nexus.initid.id ==
11487		     io->io_hdr.nexus.initid.id)) {
11488			/*
11489			 * If the abort says that the task is untagged, the
11490			 * task in the queue must be untagged.  Otherwise,
11491			 * we just check to see whether the tag numbers
11492			 * match.  This is because the QLogic firmware
11493			 * doesn't pass back the tag type in an abort
11494			 * request.
11495			 */
11496#if 0
11497			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11498			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11499			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11500#endif
11501			/*
11502			 * XXX KDM we've got problems with FC, because it
11503			 * doesn't send down a tag type with aborts.  So we
11504			 * can only really go by the tag number...
11505			 * This may cause problems with parallel SCSI.
11506			 * Need to figure that out!!
11507			 */
11508			if (xio->scsiio.tag_num == io->taskio.tag_num) {
11509				xio->io_hdr.flags |= CTL_FLAG_ABORT;
11510				found = 1;
11511				if ((io->io_hdr.flags &
11512				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
11513				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11514					union ctl_ha_msg msg_info;
11515
11516					io->io_hdr.flags |=
11517					                CTL_FLAG_SENT_2OTHER_SC;
11518					msg_info.hdr.nexus = io->io_hdr.nexus;
11519					msg_info.task.task_action =
11520						CTL_TASK_ABORT_TASK;
11521					msg_info.task.tag_num =
11522						io->taskio.tag_num;
11523					msg_info.task.tag_type =
11524						io->taskio.tag_type;
11525					msg_info.hdr.msg_type =
11526						CTL_MSG_MANAGE_TASKS;
11527					msg_info.hdr.original_sc = NULL;
11528					msg_info.hdr.serializing_sc = NULL;
11529#if 0
11530					printf("Sent Abort to other side\n");
11531#endif
11532					if (CTL_HA_STATUS_SUCCESS !=
11533					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11534		    				(void *)&msg_info,
11535						sizeof(msg_info), 0)) {
11536					}
11537				}
11538#if 0
11539				printf("ctl_abort_task: found I/O to abort\n");
11540#endif
11541				break;
11542			}
11543		}
11544	}
11545
11546bailout:
11547
11548	if (found == 0) {
11549		/*
11550		 * This isn't really an error.  It's entirely possible for
11551		 * the abort and command completion to cross on the wire.
11552		 * This is more of an informative/diagnostic error.
11553		 */
11554#if 0
11555		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11556		       "%d:%d:%d:%d tag %d type %d\n",
11557		       io->io_hdr.nexus.initid.id,
11558		       io->io_hdr.nexus.targ_port,
11559		       io->io_hdr.nexus.targ_target.id,
11560		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11561		       io->taskio.tag_type);
11562#endif
11563		return (1);
11564	} else
11565		return (0);
11566}
11567
11568/*
11569 * This routine cannot block!  It must be callable from an interrupt
11570 * handler as well as from the work thread.
11571 */
11572static void
11573ctl_run_task_queue(struct ctl_softc *ctl_softc)
11574{
11575	union ctl_io *io, *next_io;
11576
11577	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11578
11579	CTL_DEBUG_PRINT(("ctl_run_task_queue\n"));
11580
11581	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->task_queue);
11582	     io != NULL; io = next_io) {
11583		int retval;
11584		const char *task_desc;
11585
11586		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11587
11588		retval = 0;
11589
11590		switch (io->io_hdr.io_type) {
11591		case CTL_IO_TASK: {
11592			task_desc = ctl_scsi_task_string(&io->taskio);
11593			if (task_desc != NULL) {
11594#ifdef NEEDTOPORT
11595				csevent_log(CSC_CTL | CSC_SHELF_SW |
11596					    CTL_TASK_REPORT,
11597					    csevent_LogType_Trace,
11598					    csevent_Severity_Information,
11599					    csevent_AlertLevel_Green,
11600					    csevent_FRU_Firmware,
11601					    csevent_FRU_Unknown,
11602					    "CTL: received task: %s",task_desc);
11603#endif
11604			} else {
11605#ifdef NEEDTOPORT
11606				csevent_log(CSC_CTL | CSC_SHELF_SW |
11607					    CTL_TASK_REPORT,
11608					    csevent_LogType_Trace,
11609					    csevent_Severity_Information,
11610					    csevent_AlertLevel_Green,
11611					    csevent_FRU_Firmware,
11612					    csevent_FRU_Unknown,
11613					    "CTL: received unknown task "
11614					    "type: %d (%#x)",
11615					    io->taskio.task_action,
11616					    io->taskio.task_action);
11617#endif
11618			}
11619			switch (io->taskio.task_action) {
11620			case CTL_TASK_ABORT_TASK:
11621				retval = ctl_abort_task(io);
11622				break;
11623			case CTL_TASK_ABORT_TASK_SET:
11624				break;
11625			case CTL_TASK_CLEAR_ACA:
11626				break;
11627			case CTL_TASK_CLEAR_TASK_SET:
11628				break;
11629			case CTL_TASK_LUN_RESET: {
11630				struct ctl_lun *lun;
11631				uint32_t targ_lun;
11632				int retval;
11633
11634				targ_lun = io->io_hdr.nexus.targ_lun;
11635				if (io->io_hdr.nexus.lun_map_fn != NULL)
11636					targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
11637
11638				if ((targ_lun < CTL_MAX_LUNS)
11639				 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11640					lun = ctl_softc->ctl_luns[targ_lun];
11641				else {
11642					retval = 1;
11643					break;
11644				}
11645
11646				if (!(io->io_hdr.flags &
11647				    CTL_FLAG_FROM_OTHER_SC)) {
11648					union ctl_ha_msg msg_info;
11649
11650					io->io_hdr.flags |=
11651						CTL_FLAG_SENT_2OTHER_SC;
11652					msg_info.hdr.msg_type =
11653						CTL_MSG_MANAGE_TASKS;
11654					msg_info.hdr.nexus = io->io_hdr.nexus;
11655					msg_info.task.task_action =
11656						CTL_TASK_LUN_RESET;
11657					msg_info.hdr.original_sc = NULL;
11658					msg_info.hdr.serializing_sc = NULL;
11659					if (CTL_HA_STATUS_SUCCESS !=
11660					    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11661					    (void *)&msg_info,
11662					    sizeof(msg_info), 0)) {
11663					}
11664				}
11665
11666				retval = ctl_lun_reset(lun, io,
11667						       CTL_UA_LUN_RESET);
11668				break;
11669			}
11670			case CTL_TASK_TARGET_RESET:
11671				retval = ctl_target_reset(ctl_softc, io,
11672							  CTL_UA_TARG_RESET);
11673				break;
11674			case CTL_TASK_BUS_RESET:
11675				retval = ctl_bus_reset(ctl_softc, io);
11676				break;
11677			case CTL_TASK_PORT_LOGIN:
11678				break;
11679			case CTL_TASK_PORT_LOGOUT:
11680				break;
11681			default:
11682				printf("ctl_run_task_queue: got unknown task "
11683				       "management event %d\n",
11684				       io->taskio.task_action);
11685				break;
11686			}
11687			if (retval == 0)
11688				io->io_hdr.status = CTL_SUCCESS;
11689			else
11690				io->io_hdr.status = CTL_ERROR;
11691
11692			STAILQ_REMOVE(&ctl_softc->task_queue, &io->io_hdr,
11693				      ctl_io_hdr, links);
11694			/*
11695			 * This will queue this I/O to the done queue, but the
11696			 * work thread won't be able to process it until we
11697			 * return and the lock is released.
11698			 */
11699			ctl_done_lock(io, /*have_lock*/ 1);
11700			break;
11701		}
11702		default: {
11703
11704			printf("%s: invalid I/O type %d msg %d cdb %x"
11705			       " iptl: %ju:%d:%ju:%d tag 0x%04x\n",
11706			       __func__, io->io_hdr.io_type,
11707			       io->io_hdr.msg_type, io->scsiio.cdb[0],
11708			       (uintmax_t)io->io_hdr.nexus.initid.id,
11709			       io->io_hdr.nexus.targ_port,
11710			       (uintmax_t)io->io_hdr.nexus.targ_target.id,
11711			       io->io_hdr.nexus.targ_lun /* XXX */,
11712			       (io->io_hdr.io_type == CTL_IO_TASK) ?
11713			       io->taskio.tag_num : io->scsiio.tag_num);
11714			STAILQ_REMOVE(&ctl_softc->task_queue, &io->io_hdr,
11715				      ctl_io_hdr, links);
11716			ctl_free_io(io);
11717			break;
11718		}
11719		}
11720	}
11721
11722	ctl_softc->flags &= ~CTL_FLAG_TASK_PENDING;
11723}
11724
11725/*
11726 * For HA operation.  Handle commands that come in from the other
11727 * controller.
11728 */
11729static void
11730ctl_handle_isc(union ctl_io *io)
11731{
11732	int free_io;
11733	struct ctl_lun *lun;
11734	struct ctl_softc *ctl_softc;
11735	uint32_t targ_lun;
11736
11737	ctl_softc = control_softc;
11738
11739	targ_lun = io->io_hdr.nexus.targ_lun;
11740	if (io->io_hdr.nexus.lun_map_fn != NULL)
11741		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
11742	lun = ctl_softc->ctl_luns[targ_lun];
11743
11744	switch (io->io_hdr.msg_type) {
11745	case CTL_MSG_SERIALIZE:
11746		free_io = ctl_serialize_other_sc_cmd(&io->scsiio,
11747						     /*have_lock*/ 0);
11748		break;
11749	case CTL_MSG_R2R: {
11750		uint8_t opcode;
11751		struct ctl_cmd_entry *entry;
11752
11753		/*
11754		 * This is only used in SER_ONLY mode.
11755		 */
11756		free_io = 0;
11757		opcode = io->scsiio.cdb[0];
11758		entry = &ctl_cmd_table[opcode];
11759		mtx_lock(&ctl_softc->ctl_lock);
11760		if (ctl_scsiio_lun_check(ctl_softc, lun,
11761		    entry, (struct ctl_scsiio *)io) != 0) {
11762			ctl_done_lock(io, /*have_lock*/ 1);
11763			mtx_unlock(&ctl_softc->ctl_lock);
11764			break;
11765		}
11766		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11767		STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
11768				   &io->io_hdr, links);
11769		mtx_unlock(&ctl_softc->ctl_lock);
11770		break;
11771	}
11772	case CTL_MSG_FINISH_IO:
11773		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
11774			free_io = 0;
11775			ctl_done_lock(io, /*have_lock*/ 0);
11776		} else {
11777			free_io = 1;
11778			mtx_lock(&ctl_softc->ctl_lock);
11779			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11780				     ooa_links);
11781			STAILQ_REMOVE(&ctl_softc->task_queue,
11782				      &io->io_hdr, ctl_io_hdr, links);
11783			ctl_check_blocked(lun);
11784			mtx_unlock(&ctl_softc->ctl_lock);
11785		}
11786		break;
11787	case CTL_MSG_PERS_ACTION:
11788		ctl_hndl_per_res_out_on_other_sc(
11789			(union ctl_ha_msg *)&io->presio.pr_msg);
11790		free_io = 1;
11791		break;
11792	case CTL_MSG_BAD_JUJU:
11793		free_io = 0;
11794		ctl_done_lock(io, /*have_lock*/ 0);
11795		break;
11796	case CTL_MSG_DATAMOVE:
11797		/* Only used in XFER mode */
11798		free_io = 0;
11799		ctl_datamove_remote(io);
11800		break;
11801	case CTL_MSG_DATAMOVE_DONE:
11802		/* Only used in XFER mode */
11803		free_io = 0;
11804		io->scsiio.be_move_done(io);
11805		break;
11806	default:
11807		free_io = 1;
11808		printf("%s: Invalid message type %d\n",
11809		       __func__, io->io_hdr.msg_type);
11810		break;
11811	}
11812	if (free_io)
11813		ctl_free_io(io);
11814
11815}
11816
11817
11818/*
11819 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11820 * there is no match.
11821 */
11822static ctl_lun_error_pattern
11823ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11824{
11825	struct ctl_cmd_entry *entry;
11826	ctl_lun_error_pattern filtered_pattern, pattern;
11827	uint8_t opcode;
11828
11829	pattern = desc->error_pattern;
11830
11831	/*
11832	 * XXX KDM we need more data passed into this function to match a
11833	 * custom pattern, and we actually need to implement custom pattern
11834	 * matching.
11835	 */
11836	if (pattern & CTL_LUN_PAT_CMD)
11837		return (CTL_LUN_PAT_CMD);
11838
11839	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11840		return (CTL_LUN_PAT_ANY);
11841
11842	opcode = ctsio->cdb[0];
11843	entry = &ctl_cmd_table[opcode];
11844
11845	filtered_pattern = entry->pattern & pattern;
11846
11847	/*
11848	 * If the user requested specific flags in the pattern (e.g.
11849	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11850	 * flags.
11851	 *
11852	 * If the user did not specify any flags, it doesn't matter whether
11853	 * or not the command supports the flags.
11854	 */
11855	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11856	     (pattern & ~CTL_LUN_PAT_MASK))
11857		return (CTL_LUN_PAT_NONE);
11858
11859	/*
11860	 * If the user asked for a range check, see if the requested LBA
11861	 * range overlaps with this command's LBA range.
11862	 */
11863	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
11864		uint64_t lba1;
11865		uint32_t len1;
11866		ctl_action action;
11867		int retval;
11868
11869		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
11870		if (retval != 0)
11871			return (CTL_LUN_PAT_NONE);
11872
11873		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
11874					      desc->lba_range.len);
11875		/*
11876		 * A "pass" means that the LBA ranges don't overlap, so
11877		 * this doesn't match the user's range criteria.
11878		 */
11879		if (action == CTL_ACTION_PASS)
11880			return (CTL_LUN_PAT_NONE);
11881	}
11882
11883	return (filtered_pattern);
11884}
11885
11886static void
11887ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
11888{
11889	struct ctl_error_desc *desc, *desc2;
11890
11891	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
11892
11893	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
11894		ctl_lun_error_pattern pattern;
11895		/*
11896		 * Check to see whether this particular command matches
11897		 * the pattern in the descriptor.
11898		 */
11899		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
11900		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
11901			continue;
11902
11903		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
11904		case CTL_LUN_INJ_ABORTED:
11905			ctl_set_aborted(&io->scsiio);
11906			break;
11907		case CTL_LUN_INJ_MEDIUM_ERR:
11908			ctl_set_medium_error(&io->scsiio);
11909			break;
11910		case CTL_LUN_INJ_UA:
11911			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
11912			 * OCCURRED */
11913			ctl_set_ua(&io->scsiio, 0x29, 0x00);
11914			break;
11915		case CTL_LUN_INJ_CUSTOM:
11916			/*
11917			 * We're assuming the user knows what he is doing.
11918			 * Just copy the sense information without doing
11919			 * checks.
11920			 */
11921			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
11922			      ctl_min(sizeof(desc->custom_sense),
11923				      sizeof(io->scsiio.sense_data)));
11924			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
11925			io->scsiio.sense_len = SSD_FULL_SIZE;
11926			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11927			break;
11928		case CTL_LUN_INJ_NONE:
11929		default:
11930			/*
11931			 * If this is an error injection type we don't know
11932			 * about, clear the continuous flag (if it is set)
11933			 * so it will get deleted below.
11934			 */
11935			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
11936			break;
11937		}
11938		/*
11939		 * By default, each error injection action is a one-shot
11940		 */
11941		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
11942			continue;
11943
11944		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
11945
11946		free(desc, M_CTL);
11947	}
11948}
11949
11950#ifdef CTL_IO_DELAY
11951static void
11952ctl_datamove_timer_wakeup(void *arg)
11953{
11954	union ctl_io *io;
11955
11956	io = (union ctl_io *)arg;
11957
11958	ctl_datamove(io);
11959}
11960#endif /* CTL_IO_DELAY */
11961
11962void
11963ctl_datamove(union ctl_io *io)
11964{
11965	void (*fe_datamove)(union ctl_io *io);
11966
11967	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
11968
11969	CTL_DEBUG_PRINT(("ctl_datamove\n"));
11970
11971#ifdef CTL_TIME_IO
11972	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
11973		char str[256];
11974		char path_str[64];
11975		struct sbuf sb;
11976
11977		ctl_scsi_path_string(io, path_str, sizeof(path_str));
11978		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
11979
11980		sbuf_cat(&sb, path_str);
11981		switch (io->io_hdr.io_type) {
11982		case CTL_IO_SCSI:
11983			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
11984			sbuf_printf(&sb, "\n");
11985			sbuf_cat(&sb, path_str);
11986			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
11987				    io->scsiio.tag_num, io->scsiio.tag_type);
11988			break;
11989		case CTL_IO_TASK:
11990			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
11991				    "Tag Type: %d\n", io->taskio.task_action,
11992				    io->taskio.tag_num, io->taskio.tag_type);
11993			break;
11994		default:
11995			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11996			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11997			break;
11998		}
11999		sbuf_cat(&sb, path_str);
12000		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12001			    (intmax_t)time_uptime - io->io_hdr.start_time);
12002		sbuf_finish(&sb);
12003		printf("%s", sbuf_data(&sb));
12004	}
12005#endif /* CTL_TIME_IO */
12006
12007	mtx_lock(&control_softc->ctl_lock);
12008#ifdef CTL_IO_DELAY
12009	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12010		struct ctl_lun *lun;
12011
12012		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12013
12014		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12015	} else {
12016		struct ctl_lun *lun;
12017
12018		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12019		if ((lun != NULL)
12020		 && (lun->delay_info.datamove_delay > 0)) {
12021			struct callout *callout;
12022
12023			callout = (struct callout *)&io->io_hdr.timer_bytes;
12024			callout_init(callout, /*mpsafe*/ 1);
12025			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12026			callout_reset(callout,
12027				      lun->delay_info.datamove_delay * hz,
12028				      ctl_datamove_timer_wakeup, io);
12029			if (lun->delay_info.datamove_type ==
12030			    CTL_DELAY_TYPE_ONESHOT)
12031				lun->delay_info.datamove_delay = 0;
12032			mtx_unlock(&control_softc->ctl_lock);
12033			return;
12034		}
12035	}
12036#endif
12037	/*
12038	 * If we have any pending task management commands, process them
12039	 * first.  This is necessary to eliminate a race condition with the
12040	 * FETD:
12041	 *
12042	 * - FETD submits a task management command, like an abort.
12043	 * - Back end calls fe_datamove() to move the data for the aborted
12044	 *   command.  The FETD can't really accept it, but if it did, it
12045	 *   would end up transmitting data for a command that the initiator
12046	 *   told us to abort.
12047	 *
12048	 * We close the race by processing all pending task management
12049	 * commands here (we can't block!), and then check this I/O to see
12050	 * if it has been aborted.  If so, return it to the back end with
12051	 * bad status, so the back end can say return an error to the back end
12052	 * and then when the back end returns an error, we can return the
12053	 * aborted command to the FETD, so it can clean up its resources.
12054	 */
12055	if (control_softc->flags & CTL_FLAG_TASK_PENDING)
12056		ctl_run_task_queue(control_softc);
12057
12058	/*
12059	 * This command has been aborted.  Set the port status, so we fail
12060	 * the data move.
12061	 */
12062	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12063		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12064		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12065		       io->io_hdr.nexus.targ_port,
12066		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12067		       io->io_hdr.nexus.targ_lun);
12068		io->io_hdr.status = CTL_CMD_ABORTED;
12069		io->io_hdr.port_status = 31337;
12070		mtx_unlock(&control_softc->ctl_lock);
12071		/*
12072		 * Note that the backend, in this case, will get the
12073		 * callback in its context.  In other cases it may get
12074		 * called in the frontend's interrupt thread context.
12075		 */
12076		io->scsiio.be_move_done(io);
12077		return;
12078	}
12079
12080	/*
12081	 * If we're in XFER mode and this I/O is from the other shelf
12082	 * controller, we need to send the DMA to the other side to
12083	 * actually transfer the data to/from the host.  In serialize only
12084	 * mode the transfer happens below CTL and ctl_datamove() is only
12085	 * called on the machine that originally received the I/O.
12086	 */
12087	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12088	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12089		union ctl_ha_msg msg;
12090		uint32_t sg_entries_sent;
12091		int do_sg_copy;
12092		int i;
12093
12094		memset(&msg, 0, sizeof(msg));
12095		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12096		msg.hdr.original_sc = io->io_hdr.original_sc;
12097		msg.hdr.serializing_sc = io;
12098		msg.hdr.nexus = io->io_hdr.nexus;
12099		msg.dt.flags = io->io_hdr.flags;
12100		/*
12101		 * We convert everything into a S/G list here.  We can't
12102		 * pass by reference, only by value between controllers.
12103		 * So we can't pass a pointer to the S/G list, only as many
12104		 * S/G entries as we can fit in here.  If it's possible for
12105		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12106		 * then we need to break this up into multiple transfers.
12107		 */
12108		if (io->scsiio.kern_sg_entries == 0) {
12109			msg.dt.kern_sg_entries = 1;
12110			/*
12111			 * If this is in cached memory, flush the cache
12112			 * before we send the DMA request to the other
12113			 * controller.  We want to do this in either the
12114			 * read or the write case.  The read case is
12115			 * straightforward.  In the write case, we want to
12116			 * make sure nothing is in the local cache that
12117			 * could overwrite the DMAed data.
12118			 */
12119			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12120				/*
12121				 * XXX KDM use bus_dmamap_sync() here.
12122				 */
12123			}
12124
12125			/*
12126			 * Convert to a physical address if this is a
12127			 * virtual address.
12128			 */
12129			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12130				msg.dt.sg_list[0].addr =
12131					io->scsiio.kern_data_ptr;
12132			} else {
12133				/*
12134				 * XXX KDM use busdma here!
12135				 */
12136#if 0
12137				msg.dt.sg_list[0].addr = (void *)
12138					vtophys(io->scsiio.kern_data_ptr);
12139#endif
12140			}
12141
12142			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12143			do_sg_copy = 0;
12144		} else {
12145			struct ctl_sg_entry *sgl;
12146
12147			do_sg_copy = 1;
12148			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12149			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12150			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12151				/*
12152				 * XXX KDM use bus_dmamap_sync() here.
12153				 */
12154			}
12155		}
12156
12157		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12158		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12159		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12160		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12161		msg.dt.sg_sequence = 0;
12162
12163		/*
12164		 * Loop until we've sent all of the S/G entries.  On the
12165		 * other end, we'll recompose these S/G entries into one
12166		 * contiguous list before passing it to the
12167		 */
12168		for (sg_entries_sent = 0; sg_entries_sent <
12169		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12170			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12171				sizeof(msg.dt.sg_list[0])),
12172				msg.dt.kern_sg_entries - sg_entries_sent);
12173
12174			if (do_sg_copy != 0) {
12175				struct ctl_sg_entry *sgl;
12176				int j;
12177
12178				sgl = (struct ctl_sg_entry *)
12179					io->scsiio.kern_data_ptr;
12180				/*
12181				 * If this is in cached memory, flush the cache
12182				 * before we send the DMA request to the other
12183				 * controller.  We want to do this in either
12184				 * the * read or the write case.  The read
12185				 * case is straightforward.  In the write
12186				 * case, we want to make sure nothing is
12187				 * in the local cache that could overwrite
12188				 * the DMAed data.
12189				 */
12190
12191				for (i = sg_entries_sent, j = 0;
12192				     i < msg.dt.cur_sg_entries; i++, j++) {
12193					if ((io->io_hdr.flags &
12194					     CTL_FLAG_NO_DATASYNC) == 0) {
12195						/*
12196						 * XXX KDM use bus_dmamap_sync()
12197						 */
12198					}
12199					if ((io->io_hdr.flags &
12200					     CTL_FLAG_BUS_ADDR) == 0) {
12201						/*
12202						 * XXX KDM use busdma.
12203						 */
12204#if 0
12205						msg.dt.sg_list[j].addr =(void *)
12206						       vtophys(sgl[i].addr);
12207#endif
12208					} else {
12209						msg.dt.sg_list[j].addr =
12210							sgl[i].addr;
12211					}
12212					msg.dt.sg_list[j].len = sgl[i].len;
12213				}
12214			}
12215
12216			sg_entries_sent += msg.dt.cur_sg_entries;
12217			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12218				msg.dt.sg_last = 1;
12219			else
12220				msg.dt.sg_last = 0;
12221
12222			/*
12223			 * XXX KDM drop and reacquire the lock here?
12224			 */
12225			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12226			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12227				/*
12228				 * XXX do something here.
12229				 */
12230			}
12231
12232			msg.dt.sent_sg_entries = sg_entries_sent;
12233		}
12234		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12235		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12236			ctl_failover_io(io, /*have_lock*/ 1);
12237
12238	} else {
12239
12240		/*
12241		 * Lookup the fe_datamove() function for this particular
12242		 * front end.
12243		 */
12244		fe_datamove =
12245		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12246		mtx_unlock(&control_softc->ctl_lock);
12247
12248		fe_datamove(io);
12249	}
12250}
12251
12252static void
12253ctl_send_datamove_done(union ctl_io *io, int have_lock)
12254{
12255	union ctl_ha_msg msg;
12256	int isc_status;
12257
12258	memset(&msg, 0, sizeof(msg));
12259
12260	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12261	msg.hdr.original_sc = io;
12262	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12263	msg.hdr.nexus = io->io_hdr.nexus;
12264	msg.hdr.status = io->io_hdr.status;
12265	msg.scsi.tag_num = io->scsiio.tag_num;
12266	msg.scsi.tag_type = io->scsiio.tag_type;
12267	msg.scsi.scsi_status = io->scsiio.scsi_status;
12268	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12269	       sizeof(io->scsiio.sense_data));
12270	msg.scsi.sense_len = io->scsiio.sense_len;
12271	msg.scsi.sense_residual = io->scsiio.sense_residual;
12272	msg.scsi.fetd_status = io->io_hdr.port_status;
12273	msg.scsi.residual = io->scsiio.residual;
12274	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12275
12276	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12277		ctl_failover_io(io, /*have_lock*/ have_lock);
12278		return;
12279	}
12280
12281	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12282	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12283		/* XXX do something if this fails */
12284	}
12285
12286}
12287
12288/*
12289 * The DMA to the remote side is done, now we need to tell the other side
12290 * we're done so it can continue with its data movement.
12291 */
12292static void
12293ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12294{
12295	union ctl_io *io;
12296
12297	io = rq->context;
12298
12299	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12300		printf("%s: ISC DMA write failed with error %d", __func__,
12301		       rq->ret);
12302		ctl_set_internal_failure(&io->scsiio,
12303					 /*sks_valid*/ 1,
12304					 /*retry_count*/ rq->ret);
12305	}
12306
12307	ctl_dt_req_free(rq);
12308
12309	/*
12310	 * In this case, we had to malloc the memory locally.  Free it.
12311	 */
12312	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12313		int i;
12314		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12315			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12316	}
12317	/*
12318	 * The data is in local and remote memory, so now we need to send
12319	 * status (good or back) back to the other side.
12320	 */
12321	ctl_send_datamove_done(io, /*have_lock*/ 0);
12322}
12323
12324/*
12325 * We've moved the data from the host/controller into local memory.  Now we
12326 * need to push it over to the remote controller's memory.
12327 */
12328static int
12329ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12330{
12331	int retval;
12332
12333	retval = 0;
12334
12335	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12336					  ctl_datamove_remote_write_cb);
12337
12338	return (retval);
12339}
12340
12341static void
12342ctl_datamove_remote_write(union ctl_io *io)
12343{
12344	int retval;
12345	void (*fe_datamove)(union ctl_io *io);
12346
12347	/*
12348	 * - Get the data from the host/HBA into local memory.
12349	 * - DMA memory from the local controller to the remote controller.
12350	 * - Send status back to the remote controller.
12351	 */
12352
12353	retval = ctl_datamove_remote_sgl_setup(io);
12354	if (retval != 0)
12355		return;
12356
12357	/* Switch the pointer over so the FETD knows what to do */
12358	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12359
12360	/*
12361	 * Use a custom move done callback, since we need to send completion
12362	 * back to the other controller, not to the backend on this side.
12363	 */
12364	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12365
12366	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12367
12368	fe_datamove(io);
12369
12370	return;
12371
12372}
12373
12374static int
12375ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12376{
12377#if 0
12378	char str[256];
12379	char path_str[64];
12380	struct sbuf sb;
12381#endif
12382
12383	/*
12384	 * In this case, we had to malloc the memory locally.  Free it.
12385	 */
12386	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12387		int i;
12388		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12389			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12390	}
12391
12392#if 0
12393	scsi_path_string(io, path_str, sizeof(path_str));
12394	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12395	sbuf_cat(&sb, path_str);
12396	scsi_command_string(&io->scsiio, NULL, &sb);
12397	sbuf_printf(&sb, "\n");
12398	sbuf_cat(&sb, path_str);
12399	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12400		    io->scsiio.tag_num, io->scsiio.tag_type);
12401	sbuf_cat(&sb, path_str);
12402	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12403		    io->io_hdr.flags, io->io_hdr.status);
12404	sbuf_finish(&sb);
12405	printk("%s", sbuf_data(&sb));
12406#endif
12407
12408
12409	/*
12410	 * The read is done, now we need to send status (good or bad) back
12411	 * to the other side.
12412	 */
12413	ctl_send_datamove_done(io, /*have_lock*/ 0);
12414
12415	return (0);
12416}
12417
12418static void
12419ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12420{
12421	union ctl_io *io;
12422	void (*fe_datamove)(union ctl_io *io);
12423
12424	io = rq->context;
12425
12426	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12427		printf("%s: ISC DMA read failed with error %d", __func__,
12428		       rq->ret);
12429		ctl_set_internal_failure(&io->scsiio,
12430					 /*sks_valid*/ 1,
12431					 /*retry_count*/ rq->ret);
12432	}
12433
12434	ctl_dt_req_free(rq);
12435
12436	/* Switch the pointer over so the FETD knows what to do */
12437	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12438
12439	/*
12440	 * Use a custom move done callback, since we need to send completion
12441	 * back to the other controller, not to the backend on this side.
12442	 */
12443	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12444
12445	/* XXX KDM add checks like the ones in ctl_datamove? */
12446
12447	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12448
12449	fe_datamove(io);
12450}
12451
12452static int
12453ctl_datamove_remote_sgl_setup(union ctl_io *io)
12454{
12455	struct ctl_sg_entry *local_sglist, *remote_sglist;
12456	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12457	struct ctl_softc *softc;
12458	int retval;
12459	int i;
12460
12461	retval = 0;
12462	softc = control_softc;
12463
12464	local_sglist = io->io_hdr.local_sglist;
12465	local_dma_sglist = io->io_hdr.local_dma_sglist;
12466	remote_sglist = io->io_hdr.remote_sglist;
12467	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12468
12469	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12470		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12471			local_sglist[i].len = remote_sglist[i].len;
12472
12473			/*
12474			 * XXX Detect the situation where the RS-level I/O
12475			 * redirector on the other side has already read the
12476			 * data off of the AOR RS on this side, and
12477			 * transferred it to remote (mirror) memory on the
12478			 * other side.  Since we already have the data in
12479			 * memory here, we just need to use it.
12480			 *
12481			 * XXX KDM this can probably be removed once we
12482			 * get the cache device code in and take the
12483			 * current AOR implementation out.
12484			 */
12485#ifdef NEEDTOPORT
12486			if ((remote_sglist[i].addr >=
12487			     (void *)vtophys(softc->mirr->addr))
12488			 && (remote_sglist[i].addr <
12489			     ((void *)vtophys(softc->mirr->addr) +
12490			     CacheMirrorOffset))) {
12491				local_sglist[i].addr = remote_sglist[i].addr -
12492					CacheMirrorOffset;
12493				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12494				     CTL_FLAG_DATA_IN)
12495					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12496			} else {
12497				local_sglist[i].addr = remote_sglist[i].addr +
12498					CacheMirrorOffset;
12499			}
12500#endif
12501#if 0
12502			printf("%s: local %p, remote %p, len %d\n",
12503			       __func__, local_sglist[i].addr,
12504			       remote_sglist[i].addr, local_sglist[i].len);
12505#endif
12506		}
12507	} else {
12508		uint32_t len_to_go;
12509
12510		/*
12511		 * In this case, we don't have automatically allocated
12512		 * memory for this I/O on this controller.  This typically
12513		 * happens with internal CTL I/O -- e.g. inquiry, mode
12514		 * sense, etc.  Anything coming from RAIDCore will have
12515		 * a mirror area available.
12516		 */
12517		len_to_go = io->scsiio.kern_data_len;
12518
12519		/*
12520		 * Clear the no datasync flag, we have to use malloced
12521		 * buffers.
12522		 */
12523		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12524
12525		/*
12526		 * The difficult thing here is that the size of the various
12527		 * S/G segments may be different than the size from the
12528		 * remote controller.  That'll make it harder when DMAing
12529		 * the data back to the other side.
12530		 */
12531		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12532		     sizeof(io->io_hdr.remote_sglist[0])) &&
12533		     (len_to_go > 0); i++) {
12534			local_sglist[i].len = ctl_min(len_to_go, 131072);
12535			CTL_SIZE_8B(local_dma_sglist[i].len,
12536				    local_sglist[i].len);
12537			local_sglist[i].addr =
12538				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12539
12540			local_dma_sglist[i].addr = local_sglist[i].addr;
12541
12542			if (local_sglist[i].addr == NULL) {
12543				int j;
12544
12545				printf("malloc failed for %zd bytes!",
12546				       local_dma_sglist[i].len);
12547				for (j = 0; j < i; j++) {
12548					free(local_sglist[j].addr, M_CTL);
12549				}
12550				ctl_set_internal_failure(&io->scsiio,
12551							 /*sks_valid*/ 1,
12552							 /*retry_count*/ 4857);
12553				retval = 1;
12554				goto bailout_error;
12555
12556			}
12557			/* XXX KDM do we need a sync here? */
12558
12559			len_to_go -= local_sglist[i].len;
12560		}
12561		/*
12562		 * Reset the number of S/G entries accordingly.  The
12563		 * original number of S/G entries is available in
12564		 * rem_sg_entries.
12565		 */
12566		io->scsiio.kern_sg_entries = i;
12567
12568#if 0
12569		printf("%s: kern_sg_entries = %d\n", __func__,
12570		       io->scsiio.kern_sg_entries);
12571		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12572			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12573			       local_sglist[i].addr, local_sglist[i].len,
12574			       local_dma_sglist[i].len);
12575#endif
12576	}
12577
12578
12579	return (retval);
12580
12581bailout_error:
12582
12583	ctl_send_datamove_done(io, /*have_lock*/ 0);
12584
12585	return (retval);
12586}
12587
12588static int
12589ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12590			 ctl_ha_dt_cb callback)
12591{
12592	struct ctl_ha_dt_req *rq;
12593	struct ctl_sg_entry *remote_sglist, *local_sglist;
12594	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12595	uint32_t local_used, remote_used, total_used;
12596	int retval;
12597	int i, j;
12598
12599	retval = 0;
12600
12601	rq = ctl_dt_req_alloc();
12602
12603	/*
12604	 * If we failed to allocate the request, and if the DMA didn't fail
12605	 * anyway, set busy status.  This is just a resource allocation
12606	 * failure.
12607	 */
12608	if ((rq == NULL)
12609	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12610		ctl_set_busy(&io->scsiio);
12611
12612	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12613
12614		if (rq != NULL)
12615			ctl_dt_req_free(rq);
12616
12617		/*
12618		 * The data move failed.  We need to return status back
12619		 * to the other controller.  No point in trying to DMA
12620		 * data to the remote controller.
12621		 */
12622
12623		ctl_send_datamove_done(io, /*have_lock*/ 0);
12624
12625		retval = 1;
12626
12627		goto bailout;
12628	}
12629
12630	local_sglist = io->io_hdr.local_sglist;
12631	local_dma_sglist = io->io_hdr.local_dma_sglist;
12632	remote_sglist = io->io_hdr.remote_sglist;
12633	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12634	local_used = 0;
12635	remote_used = 0;
12636	total_used = 0;
12637
12638	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12639		rq->ret = CTL_HA_STATUS_SUCCESS;
12640		rq->context = io;
12641		callback(rq);
12642		goto bailout;
12643	}
12644
12645	/*
12646	 * Pull/push the data over the wire from/to the other controller.
12647	 * This takes into account the possibility that the local and
12648	 * remote sglists may not be identical in terms of the size of
12649	 * the elements and the number of elements.
12650	 *
12651	 * One fundamental assumption here is that the length allocated for
12652	 * both the local and remote sglists is identical.  Otherwise, we've
12653	 * essentially got a coding error of some sort.
12654	 */
12655	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12656		int isc_ret;
12657		uint32_t cur_len, dma_length;
12658		uint8_t *tmp_ptr;
12659
12660		rq->id = CTL_HA_DATA_CTL;
12661		rq->command = command;
12662		rq->context = io;
12663
12664		/*
12665		 * Both pointers should be aligned.  But it is possible
12666		 * that the allocation length is not.  They should both
12667		 * also have enough slack left over at the end, though,
12668		 * to round up to the next 8 byte boundary.
12669		 */
12670		cur_len = ctl_min(local_sglist[i].len - local_used,
12671				  remote_sglist[j].len - remote_used);
12672
12673		/*
12674		 * In this case, we have a size issue and need to decrease
12675		 * the size, except in the case where we actually have less
12676		 * than 8 bytes left.  In that case, we need to increase
12677		 * the DMA length to get the last bit.
12678		 */
12679		if ((cur_len & 0x7) != 0) {
12680			if (cur_len > 0x7) {
12681				cur_len = cur_len - (cur_len & 0x7);
12682				dma_length = cur_len;
12683			} else {
12684				CTL_SIZE_8B(dma_length, cur_len);
12685			}
12686
12687		} else
12688			dma_length = cur_len;
12689
12690		/*
12691		 * If we had to allocate memory for this I/O, instead of using
12692		 * the non-cached mirror memory, we'll need to flush the cache
12693		 * before trying to DMA to the other controller.
12694		 *
12695		 * We could end up doing this multiple times for the same
12696		 * segment if we have a larger local segment than remote
12697		 * segment.  That shouldn't be an issue.
12698		 */
12699		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12700			/*
12701			 * XXX KDM use bus_dmamap_sync() here.
12702			 */
12703		}
12704
12705		rq->size = dma_length;
12706
12707		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12708		tmp_ptr += local_used;
12709
12710		/* Use physical addresses when talking to ISC hardware */
12711		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12712			/* XXX KDM use busdma */
12713#if 0
12714			rq->local = vtophys(tmp_ptr);
12715#endif
12716		} else
12717			rq->local = tmp_ptr;
12718
12719		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12720		tmp_ptr += remote_used;
12721		rq->remote = tmp_ptr;
12722
12723		rq->callback = NULL;
12724
12725		local_used += cur_len;
12726		if (local_used >= local_sglist[i].len) {
12727			i++;
12728			local_used = 0;
12729		}
12730
12731		remote_used += cur_len;
12732		if (remote_used >= remote_sglist[j].len) {
12733			j++;
12734			remote_used = 0;
12735		}
12736		total_used += cur_len;
12737
12738		if (total_used >= io->scsiio.kern_data_len)
12739			rq->callback = callback;
12740
12741		if ((rq->size & 0x7) != 0) {
12742			printf("%s: warning: size %d is not on 8b boundary\n",
12743			       __func__, rq->size);
12744		}
12745		if (((uintptr_t)rq->local & 0x7) != 0) {
12746			printf("%s: warning: local %p not on 8b boundary\n",
12747			       __func__, rq->local);
12748		}
12749		if (((uintptr_t)rq->remote & 0x7) != 0) {
12750			printf("%s: warning: remote %p not on 8b boundary\n",
12751			       __func__, rq->local);
12752		}
12753#if 0
12754		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12755		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12756		       rq->local, rq->remote, rq->size);
12757#endif
12758
12759		isc_ret = ctl_dt_single(rq);
12760		if (isc_ret == CTL_HA_STATUS_WAIT)
12761			continue;
12762
12763		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12764			rq->ret = CTL_HA_STATUS_SUCCESS;
12765		} else {
12766			rq->ret = isc_ret;
12767		}
12768		callback(rq);
12769		goto bailout;
12770	}
12771
12772bailout:
12773	return (retval);
12774
12775}
12776
12777static void
12778ctl_datamove_remote_read(union ctl_io *io)
12779{
12780	int retval;
12781	int i;
12782
12783	/*
12784	 * This will send an error to the other controller in the case of a
12785	 * failure.
12786	 */
12787	retval = ctl_datamove_remote_sgl_setup(io);
12788	if (retval != 0)
12789		return;
12790
12791	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12792					  ctl_datamove_remote_read_cb);
12793	if ((retval != 0)
12794	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12795		/*
12796		 * Make sure we free memory if there was an error..  The
12797		 * ctl_datamove_remote_xfer() function will send the
12798		 * datamove done message, or call the callback with an
12799		 * error if there is a problem.
12800		 */
12801		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12802			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12803	}
12804
12805	return;
12806}
12807
12808/*
12809 * Process a datamove request from the other controller.  This is used for
12810 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12811 * first.  Once that is complete, the data gets DMAed into the remote
12812 * controller's memory.  For reads, we DMA from the remote controller's
12813 * memory into our memory first, and then move it out to the FETD.
12814 */
12815static void
12816ctl_datamove_remote(union ctl_io *io)
12817{
12818	struct ctl_softc *softc;
12819
12820	softc = control_softc;
12821
12822	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
12823
12824	/*
12825	 * Note that we look for an aborted I/O here, but don't do some of
12826	 * the other checks that ctl_datamove() normally does.  We don't
12827	 * need to run the task queue, because this I/O is on the ISC
12828	 * queue, which is executed by the work thread after the task queue.
12829	 * We don't need to run the datamove delay code, since that should
12830	 * have been done if need be on the other controller.
12831	 */
12832	mtx_lock(&softc->ctl_lock);
12833
12834	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12835
12836		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
12837		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
12838		       io->io_hdr.nexus.targ_port,
12839		       io->io_hdr.nexus.targ_target.id,
12840		       io->io_hdr.nexus.targ_lun);
12841		io->io_hdr.status = CTL_CMD_ABORTED;
12842		io->io_hdr.port_status = 31338;
12843
12844		mtx_unlock(&softc->ctl_lock);
12845
12846		ctl_send_datamove_done(io, /*have_lock*/ 0);
12847
12848		return;
12849	}
12850
12851	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
12852		mtx_unlock(&softc->ctl_lock);
12853		ctl_datamove_remote_write(io);
12854	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
12855		mtx_unlock(&softc->ctl_lock);
12856		ctl_datamove_remote_read(io);
12857	} else {
12858		union ctl_ha_msg msg;
12859		struct scsi_sense_data *sense;
12860		uint8_t sks[3];
12861		int retry_count;
12862
12863		memset(&msg, 0, sizeof(msg));
12864
12865		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
12866		msg.hdr.status = CTL_SCSI_ERROR;
12867		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
12868
12869		retry_count = 4243;
12870
12871		sense = &msg.scsi.sense_data;
12872		sks[0] = SSD_SCS_VALID;
12873		sks[1] = (retry_count >> 8) & 0xff;
12874		sks[2] = retry_count & 0xff;
12875
12876		/* "Internal target failure" */
12877		scsi_set_sense_data(sense,
12878				    /*sense_format*/ SSD_TYPE_NONE,
12879				    /*current_error*/ 1,
12880				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
12881				    /*asc*/ 0x44,
12882				    /*ascq*/ 0x00,
12883				    /*type*/ SSD_ELEM_SKS,
12884				    /*size*/ sizeof(sks),
12885				    /*data*/ sks,
12886				    SSD_ELEM_NONE);
12887
12888		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12889		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12890			ctl_failover_io(io, /*have_lock*/ 1);
12891			mtx_unlock(&softc->ctl_lock);
12892			return;
12893		}
12894
12895		mtx_unlock(&softc->ctl_lock);
12896
12897		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
12898		    CTL_HA_STATUS_SUCCESS) {
12899			/* XXX KDM what to do if this fails? */
12900		}
12901		return;
12902	}
12903
12904}
12905
12906static int
12907ctl_process_done(union ctl_io *io, int have_lock)
12908{
12909	struct ctl_lun *lun;
12910	struct ctl_softc *ctl_softc;
12911	void (*fe_done)(union ctl_io *io);
12912	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
12913
12914	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12915
12916	fe_done =
12917	    control_softc->ctl_ports[targ_port]->fe_done;
12918
12919#ifdef CTL_TIME_IO
12920	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12921		char str[256];
12922		char path_str[64];
12923		struct sbuf sb;
12924
12925		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12926		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12927
12928		sbuf_cat(&sb, path_str);
12929		switch (io->io_hdr.io_type) {
12930		case CTL_IO_SCSI:
12931			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12932			sbuf_printf(&sb, "\n");
12933			sbuf_cat(&sb, path_str);
12934			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12935				    io->scsiio.tag_num, io->scsiio.tag_type);
12936			break;
12937		case CTL_IO_TASK:
12938			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12939				    "Tag Type: %d\n", io->taskio.task_action,
12940				    io->taskio.tag_num, io->taskio.tag_type);
12941			break;
12942		default:
12943			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12944			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12945			break;
12946		}
12947		sbuf_cat(&sb, path_str);
12948		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12949			    (intmax_t)time_uptime - io->io_hdr.start_time);
12950		sbuf_finish(&sb);
12951		printf("%s", sbuf_data(&sb));
12952	}
12953#endif /* CTL_TIME_IO */
12954
12955	switch (io->io_hdr.io_type) {
12956	case CTL_IO_SCSI:
12957		break;
12958	case CTL_IO_TASK:
12959		if (bootverbose || verbose > 0)
12960			ctl_io_error_print(io, NULL);
12961		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12962			ctl_free_io(io);
12963		else
12964			fe_done(io);
12965		return (CTL_RETVAL_COMPLETE);
12966		break;
12967	default:
12968		printf("ctl_process_done: invalid io type %d\n",
12969		       io->io_hdr.io_type);
12970		panic("ctl_process_done: invalid io type %d\n",
12971		      io->io_hdr.io_type);
12972		break; /* NOTREACHED */
12973	}
12974
12975	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12976	if (lun == NULL) {
12977		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12978				 io->io_hdr.nexus.targ_lun));
12979		fe_done(io);
12980		goto bailout;
12981	}
12982	ctl_softc = lun->ctl_softc;
12983
12984	/*
12985	 * Remove this from the OOA queue.
12986	 */
12987	if (have_lock == 0)
12988		mtx_lock(&ctl_softc->ctl_lock);
12989
12990	/*
12991	 * Check to see if we have any errors to inject here.  We only
12992	 * inject errors for commands that don't already have errors set.
12993	 */
12994	if ((STAILQ_FIRST(&lun->error_list) != NULL)
12995	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
12996		ctl_inject_error(lun, io);
12997
12998	/*
12999	 * XXX KDM how do we treat commands that aren't completed
13000	 * successfully?
13001	 *
13002	 * XXX KDM should we also track I/O latency?
13003	 */
13004	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) {
13005		uint32_t blocksize;
13006#ifdef CTL_TIME_IO
13007		struct bintime cur_bt;
13008#endif
13009
13010		if ((lun->be_lun != NULL)
13011		 && (lun->be_lun->blocksize != 0))
13012			blocksize = lun->be_lun->blocksize;
13013		else
13014			blocksize = 512;
13015
13016		switch (io->io_hdr.io_type) {
13017		case CTL_IO_SCSI: {
13018			int isread;
13019			struct ctl_lba_len_flags *lbalen;
13020
13021			isread = 0;
13022			switch (io->scsiio.cdb[0]) {
13023			case READ_6:
13024			case READ_10:
13025			case READ_12:
13026			case READ_16:
13027				isread = 1;
13028				/* FALLTHROUGH */
13029			case WRITE_6:
13030			case WRITE_10:
13031			case WRITE_12:
13032			case WRITE_16:
13033			case WRITE_VERIFY_10:
13034			case WRITE_VERIFY_12:
13035			case WRITE_VERIFY_16:
13036				lbalen = (struct ctl_lba_len_flags *)
13037				    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
13038
13039				if (isread) {
13040					lun->stats.ports[targ_port].bytes[CTL_STATS_READ] +=
13041					    lbalen->len * blocksize;
13042					lun->stats.ports[targ_port].operations[CTL_STATS_READ]++;
13043
13044#ifdef CTL_TIME_IO
13045					bintime_add(
13046					   &lun->stats.ports[targ_port].dma_time[CTL_STATS_READ],
13047					   &io->io_hdr.dma_bt);
13048					lun->stats.ports[targ_port].num_dmas[CTL_STATS_READ] +=
13049						io->io_hdr.num_dmas;
13050					getbintime(&cur_bt);
13051					bintime_sub(&cur_bt,
13052						    &io->io_hdr.start_bt);
13053
13054					bintime_add(
13055					    &lun->stats.ports[targ_port].time[CTL_STATS_READ],
13056					    &cur_bt);
13057
13058#if 0
13059					cs_prof_gettime(&cur_ticks);
13060					lun->stats.time[CTL_STATS_READ] +=
13061						cur_ticks -
13062						io->io_hdr.start_ticks;
13063#endif
13064#if 0
13065					lun->stats.time[CTL_STATS_READ] +=
13066						jiffies - io->io_hdr.start_time;
13067#endif
13068#endif /* CTL_TIME_IO */
13069				} else {
13070					lun->stats.ports[targ_port].bytes[CTL_STATS_WRITE] +=
13071					    lbalen->len * blocksize;
13072					lun->stats.ports[targ_port].operations[
13073						CTL_STATS_WRITE]++;
13074
13075#ifdef CTL_TIME_IO
13076					bintime_add(
13077					  &lun->stats.ports[targ_port].dma_time[CTL_STATS_WRITE],
13078					  &io->io_hdr.dma_bt);
13079					lun->stats.ports[targ_port].num_dmas[CTL_STATS_WRITE] +=
13080						io->io_hdr.num_dmas;
13081					getbintime(&cur_bt);
13082					bintime_sub(&cur_bt,
13083						    &io->io_hdr.start_bt);
13084
13085					bintime_add(
13086					    &lun->stats.ports[targ_port].time[CTL_STATS_WRITE],
13087					    &cur_bt);
13088#if 0
13089					cs_prof_gettime(&cur_ticks);
13090					lun->stats.ports[targ_port].time[CTL_STATS_WRITE] +=
13091						cur_ticks -
13092						io->io_hdr.start_ticks;
13093					lun->stats.ports[targ_port].time[CTL_STATS_WRITE] +=
13094						jiffies - io->io_hdr.start_time;
13095#endif
13096#endif /* CTL_TIME_IO */
13097				}
13098				break;
13099			default:
13100				lun->stats.ports[targ_port].operations[CTL_STATS_NO_IO]++;
13101
13102#ifdef CTL_TIME_IO
13103				bintime_add(
13104				  &lun->stats.ports[targ_port].dma_time[CTL_STATS_NO_IO],
13105				  &io->io_hdr.dma_bt);
13106				lun->stats.ports[targ_port].num_dmas[CTL_STATS_NO_IO] +=
13107					io->io_hdr.num_dmas;
13108				getbintime(&cur_bt);
13109				bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13110
13111				bintime_add(&lun->stats.ports[targ_port].time[CTL_STATS_NO_IO],
13112					    &cur_bt);
13113
13114#if 0
13115				cs_prof_gettime(&cur_ticks);
13116				lun->stats.ports[targ_port].time[CTL_STATS_NO_IO] +=
13117					cur_ticks -
13118					io->io_hdr.start_ticks;
13119				lun->stats.ports[targ_port].time[CTL_STATS_NO_IO] +=
13120					jiffies - io->io_hdr.start_time;
13121#endif
13122#endif /* CTL_TIME_IO */
13123				break;
13124			}
13125			break;
13126		}
13127		default:
13128			break;
13129		}
13130	}
13131
13132	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13133
13134	/*
13135	 * Run through the blocked queue on this LUN and see if anything
13136	 * has become unblocked, now that this transaction is done.
13137	 */
13138	ctl_check_blocked(lun);
13139
13140	/*
13141	 * If the LUN has been invalidated, free it if there is nothing
13142	 * left on its OOA queue.
13143	 */
13144	if ((lun->flags & CTL_LUN_INVALID)
13145	 && (TAILQ_FIRST(&lun->ooa_queue) == NULL))
13146		ctl_free_lun(lun);
13147
13148	/*
13149	 * If this command has been aborted, make sure we set the status
13150	 * properly.  The FETD is responsible for freeing the I/O and doing
13151	 * whatever it needs to do to clean up its state.
13152	 */
13153	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13154		io->io_hdr.status = CTL_CMD_ABORTED;
13155
13156	/*
13157	 * We print out status for every task management command.  For SCSI
13158	 * commands, we filter out any unit attention errors; they happen
13159	 * on every boot, and would clutter up the log.  Note:  task
13160	 * management commands aren't printed here, they are printed above,
13161	 * since they should never even make it down here.
13162	 */
13163	switch (io->io_hdr.io_type) {
13164	case CTL_IO_SCSI: {
13165		int error_code, sense_key, asc, ascq;
13166
13167		sense_key = 0;
13168
13169		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13170		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13171			/*
13172			 * Since this is just for printing, no need to
13173			 * show errors here.
13174			 */
13175			scsi_extract_sense_len(&io->scsiio.sense_data,
13176					       io->scsiio.sense_len,
13177					       &error_code,
13178					       &sense_key,
13179					       &asc,
13180					       &ascq,
13181					       /*show_errors*/ 0);
13182		}
13183
13184		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13185		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13186		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13187		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13188
13189			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13190				ctl_softc->skipped_prints++;
13191				if (have_lock == 0)
13192					mtx_unlock(&ctl_softc->ctl_lock);
13193			} else {
13194				uint32_t skipped_prints;
13195
13196				skipped_prints = ctl_softc->skipped_prints;
13197
13198				ctl_softc->skipped_prints = 0;
13199				ctl_softc->last_print_jiffies = time_uptime;
13200
13201				if (have_lock == 0)
13202					mtx_unlock(&ctl_softc->ctl_lock);
13203				if (skipped_prints > 0) {
13204#ifdef NEEDTOPORT
13205					csevent_log(CSC_CTL | CSC_SHELF_SW |
13206					    CTL_ERROR_REPORT,
13207					    csevent_LogType_Trace,
13208					    csevent_Severity_Information,
13209					    csevent_AlertLevel_Green,
13210					    csevent_FRU_Firmware,
13211					    csevent_FRU_Unknown,
13212					    "High CTL error volume, %d prints "
13213					    "skipped", skipped_prints);
13214#endif
13215				}
13216				if (bootverbose || verbose > 0)
13217					ctl_io_error_print(io, NULL);
13218			}
13219		} else {
13220			if (have_lock == 0)
13221				mtx_unlock(&ctl_softc->ctl_lock);
13222		}
13223		break;
13224	}
13225	case CTL_IO_TASK:
13226		if (have_lock == 0)
13227			mtx_unlock(&ctl_softc->ctl_lock);
13228		if (bootverbose || verbose > 0)
13229			ctl_io_error_print(io, NULL);
13230		break;
13231	default:
13232		if (have_lock == 0)
13233			mtx_unlock(&ctl_softc->ctl_lock);
13234		break;
13235	}
13236
13237	/*
13238	 * Tell the FETD or the other shelf controller we're done with this
13239	 * command.  Note that only SCSI commands get to this point.  Task
13240	 * management commands are completed above.
13241	 *
13242	 * We only send status to the other controller if we're in XFER
13243	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13244	 * received the I/O (from CTL's perspective), and so the status is
13245	 * generated there.
13246	 *
13247	 * XXX KDM if we hold the lock here, we could cause a deadlock
13248	 * if the frontend comes back in in this context to queue
13249	 * something.
13250	 */
13251	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13252	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13253		union ctl_ha_msg msg;
13254
13255		memset(&msg, 0, sizeof(msg));
13256		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13257		msg.hdr.original_sc = io->io_hdr.original_sc;
13258		msg.hdr.nexus = io->io_hdr.nexus;
13259		msg.hdr.status = io->io_hdr.status;
13260		msg.scsi.scsi_status = io->scsiio.scsi_status;
13261		msg.scsi.tag_num = io->scsiio.tag_num;
13262		msg.scsi.tag_type = io->scsiio.tag_type;
13263		msg.scsi.sense_len = io->scsiio.sense_len;
13264		msg.scsi.sense_residual = io->scsiio.sense_residual;
13265		msg.scsi.residual = io->scsiio.residual;
13266		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13267		       sizeof(io->scsiio.sense_data));
13268		/*
13269		 * We copy this whether or not this is an I/O-related
13270		 * command.  Otherwise, we'd have to go and check to see
13271		 * whether it's a read/write command, and it really isn't
13272		 * worth it.
13273		 */
13274		memcpy(&msg.scsi.lbalen,
13275		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13276		       sizeof(msg.scsi.lbalen));
13277
13278		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13279				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13280			/* XXX do something here */
13281		}
13282
13283		ctl_free_io(io);
13284	} else
13285		fe_done(io);
13286
13287bailout:
13288
13289	return (CTL_RETVAL_COMPLETE);
13290}
13291
13292/*
13293 * Front end should call this if it doesn't do autosense.  When the request
13294 * sense comes back in from the initiator, we'll dequeue this and send it.
13295 */
13296int
13297ctl_queue_sense(union ctl_io *io)
13298{
13299	struct ctl_lun *lun;
13300	struct ctl_softc *ctl_softc;
13301	uint32_t initidx, targ_lun;
13302
13303	ctl_softc = control_softc;
13304
13305	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13306
13307	/*
13308	 * LUN lookup will likely move to the ctl_work_thread() once we
13309	 * have our new queueing infrastructure (that doesn't put things on
13310	 * a per-LUN queue initially).  That is so that we can handle
13311	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13312	 * can't deal with that right now.
13313	 */
13314	mtx_lock(&ctl_softc->ctl_lock);
13315
13316	/*
13317	 * If we don't have a LUN for this, just toss the sense
13318	 * information.
13319	 */
13320	targ_lun = io->io_hdr.nexus.targ_lun;
13321	if (io->io_hdr.nexus.lun_map_fn != NULL)
13322		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
13323	if ((targ_lun < CTL_MAX_LUNS)
13324	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13325		lun = ctl_softc->ctl_luns[targ_lun];
13326	else
13327		goto bailout;
13328
13329	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13330
13331	/*
13332	 * Already have CA set for this LUN...toss the sense information.
13333	 */
13334	if (ctl_is_set(lun->have_ca, initidx))
13335		goto bailout;
13336
13337	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13338	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
13339	       sizeof(io->scsiio.sense_data)));
13340	ctl_set_mask(lun->have_ca, initidx);
13341
13342bailout:
13343	mtx_unlock(&ctl_softc->ctl_lock);
13344
13345	ctl_free_io(io);
13346
13347	return (CTL_RETVAL_COMPLETE);
13348}
13349
13350/*
13351 * Primary command inlet from frontend ports.  All SCSI and task I/O
13352 * requests must go through this function.
13353 */
13354int
13355ctl_queue(union ctl_io *io)
13356{
13357	struct ctl_softc *ctl_softc;
13358
13359	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13360
13361	ctl_softc = control_softc;
13362
13363#ifdef CTL_TIME_IO
13364	io->io_hdr.start_time = time_uptime;
13365	getbintime(&io->io_hdr.start_bt);
13366#endif /* CTL_TIME_IO */
13367
13368	mtx_lock(&ctl_softc->ctl_lock);
13369
13370	switch (io->io_hdr.io_type) {
13371	case CTL_IO_SCSI:
13372		STAILQ_INSERT_TAIL(&ctl_softc->incoming_queue, &io->io_hdr,
13373				   links);
13374		break;
13375	case CTL_IO_TASK:
13376		STAILQ_INSERT_TAIL(&ctl_softc->task_queue, &io->io_hdr, links);
13377		/*
13378		 * Set the task pending flag.  This is necessary to close a
13379		 * race condition with the FETD:
13380		 *
13381		 * - FETD submits a task management command, like an abort.
13382		 * - Back end calls fe_datamove() to move the data for the
13383		 *   aborted command.  The FETD can't really accept it, but
13384		 *   if it did, it would end up transmitting data for a
13385		 *   command that the initiator told us to abort.
13386		 *
13387		 * We close the race condition by setting the flag here,
13388		 * and checking it in ctl_datamove(), before calling the
13389		 * FETD's fe_datamove routine.  If we've got a task
13390		 * pending, we run the task queue and then check to see
13391		 * whether our particular I/O has been aborted.
13392		 */
13393		ctl_softc->flags |= CTL_FLAG_TASK_PENDING;
13394		break;
13395	default:
13396		mtx_unlock(&ctl_softc->ctl_lock);
13397		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13398		return (-EINVAL);
13399		break; /* NOTREACHED */
13400	}
13401	mtx_unlock(&ctl_softc->ctl_lock);
13402
13403	ctl_wakeup_thread();
13404
13405	return (CTL_RETVAL_COMPLETE);
13406}
13407
13408#ifdef CTL_IO_DELAY
13409static void
13410ctl_done_timer_wakeup(void *arg)
13411{
13412	union ctl_io *io;
13413
13414	io = (union ctl_io *)arg;
13415	ctl_done_lock(io, /*have_lock*/ 0);
13416}
13417#endif /* CTL_IO_DELAY */
13418
13419void
13420ctl_done_lock(union ctl_io *io, int have_lock)
13421{
13422	struct ctl_softc *ctl_softc;
13423#ifndef CTL_DONE_THREAD
13424	union ctl_io *xio;
13425#endif /* !CTL_DONE_THREAD */
13426
13427	ctl_softc = control_softc;
13428
13429	if (have_lock == 0)
13430		mtx_lock(&ctl_softc->ctl_lock);
13431
13432	/*
13433	 * Enable this to catch duplicate completion issues.
13434	 */
13435#if 0
13436	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13437		printf("%s: type %d msg %d cdb %x iptl: "
13438		       "%d:%d:%d:%d tag 0x%04x "
13439		       "flag %#x status %x\n",
13440			__func__,
13441			io->io_hdr.io_type,
13442			io->io_hdr.msg_type,
13443			io->scsiio.cdb[0],
13444			io->io_hdr.nexus.initid.id,
13445			io->io_hdr.nexus.targ_port,
13446			io->io_hdr.nexus.targ_target.id,
13447			io->io_hdr.nexus.targ_lun,
13448			(io->io_hdr.io_type ==
13449			CTL_IO_TASK) ?
13450			io->taskio.tag_num :
13451			io->scsiio.tag_num,
13452		        io->io_hdr.flags,
13453			io->io_hdr.status);
13454	} else
13455		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13456#endif
13457
13458	/*
13459	 * This is an internal copy of an I/O, and should not go through
13460	 * the normal done processing logic.
13461	 */
13462	if (io->io_hdr.flags & CTL_FLAG_INT_COPY) {
13463		if (have_lock == 0)
13464			mtx_unlock(&ctl_softc->ctl_lock);
13465		return;
13466	}
13467
13468	/*
13469	 * We need to send a msg to the serializing shelf to finish the IO
13470	 * as well.  We don't send a finish message to the other shelf if
13471	 * this is a task management command.  Task management commands
13472	 * aren't serialized in the OOA queue, but rather just executed on
13473	 * both shelf controllers for commands that originated on that
13474	 * controller.
13475	 */
13476	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13477	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13478		union ctl_ha_msg msg_io;
13479
13480		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13481		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13482		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13483		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13484		}
13485		/* continue on to finish IO */
13486	}
13487#ifdef CTL_IO_DELAY
13488	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13489		struct ctl_lun *lun;
13490
13491		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13492
13493		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13494	} else {
13495		struct ctl_lun *lun;
13496
13497		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13498
13499		if ((lun != NULL)
13500		 && (lun->delay_info.done_delay > 0)) {
13501			struct callout *callout;
13502
13503			callout = (struct callout *)&io->io_hdr.timer_bytes;
13504			callout_init(callout, /*mpsafe*/ 1);
13505			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13506			callout_reset(callout,
13507				      lun->delay_info.done_delay * hz,
13508				      ctl_done_timer_wakeup, io);
13509			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13510				lun->delay_info.done_delay = 0;
13511			if (have_lock == 0)
13512				mtx_unlock(&ctl_softc->ctl_lock);
13513			return;
13514		}
13515	}
13516#endif /* CTL_IO_DELAY */
13517
13518	STAILQ_INSERT_TAIL(&ctl_softc->done_queue, &io->io_hdr, links);
13519
13520#ifdef CTL_DONE_THREAD
13521	if (have_lock == 0)
13522		mtx_unlock(&ctl_softc->ctl_lock);
13523
13524	ctl_wakeup_thread();
13525#else /* CTL_DONE_THREAD */
13526	for (xio = (union ctl_io *)STAILQ_FIRST(&ctl_softc->done_queue);
13527	     xio != NULL;
13528	     xio =(union ctl_io *)STAILQ_FIRST(&ctl_softc->done_queue)) {
13529
13530		STAILQ_REMOVE_HEAD(&ctl_softc->done_queue, links);
13531
13532		ctl_process_done(xio, /*have_lock*/ 1);
13533	}
13534	if (have_lock == 0)
13535		mtx_unlock(&ctl_softc->ctl_lock);
13536#endif /* CTL_DONE_THREAD */
13537}
13538
13539void
13540ctl_done(union ctl_io *io)
13541{
13542	ctl_done_lock(io, /*have_lock*/ 0);
13543}
13544
13545int
13546ctl_isc(struct ctl_scsiio *ctsio)
13547{
13548	struct ctl_lun *lun;
13549	int retval;
13550
13551	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13552
13553	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13554
13555	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13556
13557	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13558
13559	return (retval);
13560}
13561
13562
13563static void
13564ctl_work_thread(void *arg)
13565{
13566	struct ctl_softc *softc;
13567	union ctl_io *io;
13568	struct ctl_be_lun *be_lun;
13569	int retval;
13570
13571	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13572
13573	softc = (struct ctl_softc *)arg;
13574	if (softc == NULL)
13575		return;
13576
13577	mtx_lock(&softc->ctl_lock);
13578	for (;;) {
13579		retval = 0;
13580
13581		/*
13582		 * We handle the queues in this order:
13583		 * - task management
13584		 * - ISC
13585		 * - done queue (to free up resources, unblock other commands)
13586		 * - RtR queue
13587		 * - incoming queue
13588		 *
13589		 * If those queues are empty, we break out of the loop and
13590		 * go to sleep.
13591		 */
13592		io = (union ctl_io *)STAILQ_FIRST(&softc->task_queue);
13593		if (io != NULL) {
13594			ctl_run_task_queue(softc);
13595			continue;
13596		}
13597		io = (union ctl_io *)STAILQ_FIRST(&softc->isc_queue);
13598		if (io != NULL) {
13599			STAILQ_REMOVE_HEAD(&softc->isc_queue, links);
13600			ctl_handle_isc(io);
13601			continue;
13602		}
13603		io = (union ctl_io *)STAILQ_FIRST(&softc->done_queue);
13604		if (io != NULL) {
13605			STAILQ_REMOVE_HEAD(&softc->done_queue, links);
13606			/* clear any blocked commands, call fe_done */
13607			mtx_unlock(&softc->ctl_lock);
13608			/*
13609			 * XXX KDM
13610			 * Call this without a lock for now.  This will
13611			 * depend on whether there is any way the FETD can
13612			 * sleep or deadlock if called with the CTL lock
13613			 * held.
13614			 */
13615			retval = ctl_process_done(io, /*have_lock*/ 0);
13616			mtx_lock(&softc->ctl_lock);
13617			continue;
13618		}
13619		if (!ctl_pause_rtr) {
13620			io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
13621			if (io != NULL) {
13622				STAILQ_REMOVE_HEAD(&softc->rtr_queue, links);
13623				mtx_unlock(&softc->ctl_lock);
13624				retval = ctl_scsiio(&io->scsiio);
13625				if (retval != CTL_RETVAL_COMPLETE)
13626					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13627				mtx_lock(&softc->ctl_lock);
13628				continue;
13629			}
13630		}
13631		io = (union ctl_io *)STAILQ_FIRST(&softc->incoming_queue);
13632		if (io != NULL) {
13633			STAILQ_REMOVE_HEAD(&softc->incoming_queue, links);
13634			mtx_unlock(&softc->ctl_lock);
13635			ctl_scsiio_precheck(softc, &io->scsiio);
13636			mtx_lock(&softc->ctl_lock);
13637			continue;
13638		}
13639		/*
13640		 * We might want to move this to a separate thread, so that
13641		 * configuration requests (in this case LUN creations)
13642		 * won't impact the I/O path.
13643		 */
13644		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13645		if (be_lun != NULL) {
13646			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13647			mtx_unlock(&softc->ctl_lock);
13648			ctl_create_lun(be_lun);
13649			mtx_lock(&softc->ctl_lock);
13650			continue;
13651		}
13652
13653		/* XXX KDM use the PDROP flag?? */
13654		/* Sleep until we have something to do. */
13655		mtx_sleep(softc, &softc->ctl_lock, PRIBIO, "-", 0);
13656
13657		/* Back to the top of the loop to see what woke us up. */
13658		continue;
13659	}
13660}
13661
13662void
13663ctl_wakeup_thread()
13664{
13665	struct ctl_softc *softc;
13666
13667	softc = control_softc;
13668
13669	wakeup_one(softc);
13670}
13671
13672/* Initialization and failover */
13673
13674void
13675ctl_init_isc_msg(void)
13676{
13677	printf("CTL: Still calling this thing\n");
13678}
13679
13680/*
13681 * Init component
13682 * 	Initializes component into configuration defined by bootMode
13683 *	(see hasc-sv.c)
13684 *  	returns hasc_Status:
13685 * 		OK
13686 *		ERROR - fatal error
13687 */
13688static ctl_ha_comp_status
13689ctl_isc_init(struct ctl_ha_component *c)
13690{
13691	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13692
13693	c->status = ret;
13694	return ret;
13695}
13696
13697/* Start component
13698 * 	Starts component in state requested. If component starts successfully,
13699 *	it must set its own state to the requestrd state
13700 *	When requested state is HASC_STATE_HA, the component may refine it
13701 * 	by adding _SLAVE or _MASTER flags.
13702 *	Currently allowed state transitions are:
13703 *	UNKNOWN->HA		- initial startup
13704 *	UNKNOWN->SINGLE - initial startup when no parter detected
13705 *	HA->SINGLE		- failover
13706 * returns ctl_ha_comp_status:
13707 * 		OK	- component successfully started in requested state
13708 *		FAILED  - could not start the requested state, failover may
13709 * 			  be possible
13710 *		ERROR	- fatal error detected, no future startup possible
13711 */
13712static ctl_ha_comp_status
13713ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13714{
13715	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13716
13717	printf("%s: go\n", __func__);
13718
13719	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13720	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13721		ctl_is_single = 0;
13722		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13723		    != CTL_HA_STATUS_SUCCESS) {
13724			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13725			ret = CTL_HA_COMP_STATUS_ERROR;
13726		}
13727	} else if (CTL_HA_STATE_IS_HA(c->state)
13728		&& CTL_HA_STATE_IS_SINGLE(state)){
13729		// HA->SINGLE transition
13730	        ctl_failover();
13731		ctl_is_single = 1;
13732	} else {
13733		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13734		       c->state, state);
13735		ret = CTL_HA_COMP_STATUS_ERROR;
13736	}
13737	if (CTL_HA_STATE_IS_SINGLE(state))
13738		ctl_is_single = 1;
13739
13740	c->state = state;
13741	c->status = ret;
13742	return ret;
13743}
13744
13745/*
13746 * Quiesce component
13747 * The component must clear any error conditions (set status to OK) and
13748 * prepare itself to another Start call
13749 * returns ctl_ha_comp_status:
13750 * 	OK
13751 *	ERROR
13752 */
13753static ctl_ha_comp_status
13754ctl_isc_quiesce(struct ctl_ha_component *c)
13755{
13756	int ret = CTL_HA_COMP_STATUS_OK;
13757
13758	ctl_pause_rtr = 1;
13759	c->status = ret;
13760	return ret;
13761}
13762
13763struct ctl_ha_component ctl_ha_component_ctlisc =
13764{
13765	.name = "CTL ISC",
13766	.state = CTL_HA_STATE_UNKNOWN,
13767	.init = ctl_isc_init,
13768	.start = ctl_isc_start,
13769	.quiesce = ctl_isc_quiesce
13770};
13771
13772/*
13773 *  vim: ts=8
13774 */
13775