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