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