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