ctl.c revision 272911
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 272911 2014-10-10 19:41:09Z 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*/ SCP_WCE | SCP_RCD,
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*/SCP_QUEUE_ALG_RESTRICTED,
284	/*eca_and_aen*/0,
285	/*flags4*/SCP_TAS,
286	/*aen_holdoff_period*/{0, 0},
287	/*busy_timeout_period*/{0, 0},
288	/*extended_selftest_completion_time*/{0, 0}
289};
290
291static struct scsi_control_page control_page_changeable = {
292	/*page_code*/SMS_CONTROL_MODE_PAGE,
293	/*page_length*/sizeof(struct scsi_control_page) - 2,
294	/*rlec*/SCP_DSENSE,
295	/*queue_flags*/SCP_QUEUE_ALG_MASK,
296	/*eca_and_aen*/SCP_SWP,
297	/*flags4*/0,
298	/*aen_holdoff_period*/{0, 0},
299	/*busy_timeout_period*/{0, 0},
300	/*extended_selftest_completion_time*/{0, 0}
301};
302
303
304/*
305 * XXX KDM move these into the softc.
306 */
307static int rcv_sync_msg;
308static int persis_offset;
309static uint8_t ctl_pause_rtr;
310static int     ctl_is_single = 1;
311static int     index_to_aps_page;
312
313SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314static int worker_threads = -1;
315SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316    &worker_threads, 1, "Number of worker threads");
317static int verbose = 0;
318SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319    &verbose, 0, "Show SCSI errors returned to initiator");
320
321/*
322 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
324 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
325 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
326 */
327#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
328
329static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
330				  int param);
331static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
332static int ctl_init(void);
333void ctl_shutdown(void);
334static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
335static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
336static void ctl_ioctl_online(void *arg);
337static void ctl_ioctl_offline(void *arg);
338static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
339static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
340static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
341static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
342static int ctl_ioctl_submit_wait(union ctl_io *io);
343static void ctl_ioctl_datamove(union ctl_io *io);
344static void ctl_ioctl_done(union ctl_io *io);
345static void ctl_ioctl_hard_startstop_callback(void *arg,
346					      struct cfi_metatask *metatask);
347static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
348static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
349			      struct ctl_ooa *ooa_hdr,
350			      struct ctl_ooa_entry *kern_entries);
351static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
352		     struct thread *td);
353static uint32_t ctl_map_lun(int port_num, uint32_t lun);
354static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
355#ifdef unused
356static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
357				   uint32_t targ_target, uint32_t targ_lun,
358				   int can_wait);
359static void ctl_kfree_io(union ctl_io *io);
360#endif /* unused */
361static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
362			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
363static int ctl_free_lun(struct ctl_lun *lun);
364static void ctl_create_lun(struct ctl_be_lun *be_lun);
365/**
366static void ctl_failover_change_pages(struct ctl_softc *softc,
367				      struct ctl_scsiio *ctsio, int master);
368**/
369
370static int ctl_do_mode_select(union ctl_io *io);
371static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
372			   uint64_t res_key, uint64_t sa_res_key,
373			   uint8_t type, uint32_t residx,
374			   struct ctl_scsiio *ctsio,
375			   struct scsi_per_res_out *cdb,
376			   struct scsi_per_res_out_parms* param);
377static void ctl_pro_preempt_other(struct ctl_lun *lun,
378				  union ctl_ha_msg *msg);
379static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
380static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
381static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
382static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
383static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
385static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
386					 int alloc_len);
387static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
388					 int alloc_len);
389static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
390static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
391static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
392static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
393static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
394static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
395static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
396    union ctl_io *pending_io, union ctl_io *ooa_io);
397static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
398				union ctl_io *starting_io);
399static int ctl_check_blocked(struct ctl_lun *lun);
400static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
401				struct ctl_lun *lun,
402				const struct ctl_cmd_entry *entry,
403				struct ctl_scsiio *ctsio);
404//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
405static void ctl_failover(void);
406static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
407			       struct ctl_scsiio *ctsio);
408static int ctl_scsiio(struct ctl_scsiio *ctsio);
409
410static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
411static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
412			    ctl_ua_type ua_type);
413static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
414			 ctl_ua_type ua_type);
415static int ctl_abort_task(union ctl_io *io);
416static int ctl_abort_task_set(union ctl_io *io);
417static int ctl_i_t_nexus_reset(union ctl_io *io);
418static void ctl_run_task(union ctl_io *io);
419#ifdef CTL_IO_DELAY
420static void ctl_datamove_timer_wakeup(void *arg);
421static void ctl_done_timer_wakeup(void *arg);
422#endif /* CTL_IO_DELAY */
423
424static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
425static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
426static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
427static void ctl_datamove_remote_write(union ctl_io *io);
428static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
429static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
430static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
431static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
432				    ctl_ha_dt_cb callback);
433static void ctl_datamove_remote_read(union ctl_io *io);
434static void ctl_datamove_remote(union ctl_io *io);
435static int ctl_process_done(union ctl_io *io);
436static void ctl_lun_thread(void *arg);
437static void ctl_work_thread(void *arg);
438static void ctl_enqueue_incoming(union ctl_io *io);
439static void ctl_enqueue_rtr(union ctl_io *io);
440static void ctl_enqueue_done(union ctl_io *io);
441static void ctl_enqueue_isc(union ctl_io *io);
442static const struct ctl_cmd_entry *
443    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
444static const struct ctl_cmd_entry *
445    ctl_validate_command(struct ctl_scsiio *ctsio);
446static int ctl_cmd_applicable(uint8_t lun_type,
447    const struct ctl_cmd_entry *entry);
448
449/*
450 * Load the serialization table.  This isn't very pretty, but is probably
451 * the easiest way to do it.
452 */
453#include "ctl_ser_table.c"
454
455/*
456 * We only need to define open, close and ioctl routines for this driver.
457 */
458static struct cdevsw ctl_cdevsw = {
459	.d_version =	D_VERSION,
460	.d_flags =	0,
461	.d_open =	ctl_open,
462	.d_close =	ctl_close,
463	.d_ioctl =	ctl_ioctl,
464	.d_name =	"ctl",
465};
466
467
468MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
469MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
470
471static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
472
473static moduledata_t ctl_moduledata = {
474	"ctl",
475	ctl_module_event_handler,
476	NULL
477};
478
479DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
480MODULE_VERSION(ctl, 1);
481
482static struct ctl_frontend ioctl_frontend =
483{
484	.name = "ioctl",
485};
486
487static void
488ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
489			    union ctl_ha_msg *msg_info)
490{
491	struct ctl_scsiio *ctsio;
492
493	if (msg_info->hdr.original_sc == NULL) {
494		printf("%s: original_sc == NULL!\n", __func__);
495		/* XXX KDM now what? */
496		return;
497	}
498
499	ctsio = &msg_info->hdr.original_sc->scsiio;
500	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
501	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
502	ctsio->io_hdr.status = msg_info->hdr.status;
503	ctsio->scsi_status = msg_info->scsi.scsi_status;
504	ctsio->sense_len = msg_info->scsi.sense_len;
505	ctsio->sense_residual = msg_info->scsi.sense_residual;
506	ctsio->residual = msg_info->scsi.residual;
507	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
508	       sizeof(ctsio->sense_data));
509	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
510	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
511	ctl_enqueue_isc((union ctl_io *)ctsio);
512}
513
514static void
515ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
516				union ctl_ha_msg *msg_info)
517{
518	struct ctl_scsiio *ctsio;
519
520	if (msg_info->hdr.serializing_sc == NULL) {
521		printf("%s: serializing_sc == NULL!\n", __func__);
522		/* XXX KDM now what? */
523		return;
524	}
525
526	ctsio = &msg_info->hdr.serializing_sc->scsiio;
527#if 0
528	/*
529	 * Attempt to catch the situation where an I/O has
530	 * been freed, and we're using it again.
531	 */
532	if (ctsio->io_hdr.io_type == 0xff) {
533		union ctl_io *tmp_io;
534		tmp_io = (union ctl_io *)ctsio;
535		printf("%s: %p use after free!\n", __func__,
536		       ctsio);
537		printf("%s: type %d msg %d cdb %x iptl: "
538		       "%d:%d:%d:%d tag 0x%04x "
539		       "flag %#x status %x\n",
540			__func__,
541			tmp_io->io_hdr.io_type,
542			tmp_io->io_hdr.msg_type,
543			tmp_io->scsiio.cdb[0],
544			tmp_io->io_hdr.nexus.initid.id,
545			tmp_io->io_hdr.nexus.targ_port,
546			tmp_io->io_hdr.nexus.targ_target.id,
547			tmp_io->io_hdr.nexus.targ_lun,
548			(tmp_io->io_hdr.io_type ==
549			CTL_IO_TASK) ?
550			tmp_io->taskio.tag_num :
551			tmp_io->scsiio.tag_num,
552		        tmp_io->io_hdr.flags,
553			tmp_io->io_hdr.status);
554	}
555#endif
556	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
557	ctl_enqueue_isc((union ctl_io *)ctsio);
558}
559
560/*
561 * ISC (Inter Shelf Communication) event handler.  Events from the HA
562 * subsystem come in here.
563 */
564static void
565ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
566{
567	struct ctl_softc *ctl_softc;
568	union ctl_io *io;
569	struct ctl_prio *presio;
570	ctl_ha_status isc_status;
571
572	ctl_softc = control_softc;
573	io = NULL;
574
575
576#if 0
577	printf("CTL: Isc Msg event %d\n", event);
578#endif
579	if (event == CTL_HA_EVT_MSG_RECV) {
580		union ctl_ha_msg msg_info;
581
582		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
583					     sizeof(msg_info), /*wait*/ 0);
584#if 0
585		printf("CTL: msg_type %d\n", msg_info.msg_type);
586#endif
587		if (isc_status != 0) {
588			printf("Error receiving message, status = %d\n",
589			       isc_status);
590			return;
591		}
592
593		switch (msg_info.hdr.msg_type) {
594		case CTL_MSG_SERIALIZE:
595#if 0
596			printf("Serialize\n");
597#endif
598			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
599			if (io == NULL) {
600				printf("ctl_isc_event_handler: can't allocate "
601				       "ctl_io!\n");
602				/* Bad Juju */
603				/* Need to set busy and send msg back */
604				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
605				msg_info.hdr.status = CTL_SCSI_ERROR;
606				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
607				msg_info.scsi.sense_len = 0;
608			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
609				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
610				}
611				goto bailout;
612			}
613			ctl_zero_io(io);
614			// populate ctsio from msg_info
615			io->io_hdr.io_type = CTL_IO_SCSI;
616			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
617			io->io_hdr.original_sc = msg_info.hdr.original_sc;
618#if 0
619			printf("pOrig %x\n", (int)msg_info.original_sc);
620#endif
621			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
622					    CTL_FLAG_IO_ACTIVE;
623			/*
624			 * If we're in serialization-only mode, we don't
625			 * want to go through full done processing.  Thus
626			 * the COPY flag.
627			 *
628			 * XXX KDM add another flag that is more specific.
629			 */
630			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
631				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
632			io->io_hdr.nexus = msg_info.hdr.nexus;
633#if 0
634			printf("targ %d, port %d, iid %d, lun %d\n",
635			       io->io_hdr.nexus.targ_target.id,
636			       io->io_hdr.nexus.targ_port,
637			       io->io_hdr.nexus.initid.id,
638			       io->io_hdr.nexus.targ_lun);
639#endif
640			io->scsiio.tag_num = msg_info.scsi.tag_num;
641			io->scsiio.tag_type = msg_info.scsi.tag_type;
642			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
643			       CTL_MAX_CDBLEN);
644			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
645				const struct ctl_cmd_entry *entry;
646
647				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
648				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
649				io->io_hdr.flags |=
650					entry->flags & CTL_FLAG_DATA_MASK;
651			}
652			ctl_enqueue_isc(io);
653			break;
654
655		/* Performed on the Originating SC, XFER mode only */
656		case CTL_MSG_DATAMOVE: {
657			struct ctl_sg_entry *sgl;
658			int i, j;
659
660			io = msg_info.hdr.original_sc;
661			if (io == NULL) {
662				printf("%s: original_sc == NULL!\n", __func__);
663				/* XXX KDM do something here */
664				break;
665			}
666			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
667			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
668			/*
669			 * Keep track of this, we need to send it back over
670			 * when the datamove is complete.
671			 */
672			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
673
674			if (msg_info.dt.sg_sequence == 0) {
675				/*
676				 * XXX KDM we use the preallocated S/G list
677				 * here, but we'll need to change this to
678				 * dynamic allocation if we need larger S/G
679				 * lists.
680				 */
681				if (msg_info.dt.kern_sg_entries >
682				    sizeof(io->io_hdr.remote_sglist) /
683				    sizeof(io->io_hdr.remote_sglist[0])) {
684					printf("%s: number of S/G entries "
685					    "needed %u > allocated num %zd\n",
686					    __func__,
687					    msg_info.dt.kern_sg_entries,
688					    sizeof(io->io_hdr.remote_sglist)/
689					    sizeof(io->io_hdr.remote_sglist[0]));
690
691					/*
692					 * XXX KDM send a message back to
693					 * the other side to shut down the
694					 * DMA.  The error will come back
695					 * through via the normal channel.
696					 */
697					break;
698				}
699				sgl = io->io_hdr.remote_sglist;
700				memset(sgl, 0,
701				       sizeof(io->io_hdr.remote_sglist));
702
703				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
704
705				io->scsiio.kern_sg_entries =
706					msg_info.dt.kern_sg_entries;
707				io->scsiio.rem_sg_entries =
708					msg_info.dt.kern_sg_entries;
709				io->scsiio.kern_data_len =
710					msg_info.dt.kern_data_len;
711				io->scsiio.kern_total_len =
712					msg_info.dt.kern_total_len;
713				io->scsiio.kern_data_resid =
714					msg_info.dt.kern_data_resid;
715				io->scsiio.kern_rel_offset =
716					msg_info.dt.kern_rel_offset;
717				/*
718				 * Clear out per-DMA flags.
719				 */
720				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
721				/*
722				 * Add per-DMA flags that are set for this
723				 * particular DMA request.
724				 */
725				io->io_hdr.flags |= msg_info.dt.flags &
726						    CTL_FLAG_RDMA_MASK;
727			} else
728				sgl = (struct ctl_sg_entry *)
729					io->scsiio.kern_data_ptr;
730
731			for (i = msg_info.dt.sent_sg_entries, j = 0;
732			     i < (msg_info.dt.sent_sg_entries +
733			     msg_info.dt.cur_sg_entries); i++, j++) {
734				sgl[i].addr = msg_info.dt.sg_list[j].addr;
735				sgl[i].len = msg_info.dt.sg_list[j].len;
736
737#if 0
738				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
739				       __func__,
740				       msg_info.dt.sg_list[j].addr,
741				       msg_info.dt.sg_list[j].len,
742				       sgl[i].addr, sgl[i].len, j, i);
743#endif
744			}
745#if 0
746			memcpy(&sgl[msg_info.dt.sent_sg_entries],
747			       msg_info.dt.sg_list,
748			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
749#endif
750
751			/*
752			 * If this is the last piece of the I/O, we've got
753			 * the full S/G list.  Queue processing in the thread.
754			 * Otherwise wait for the next piece.
755			 */
756			if (msg_info.dt.sg_last != 0)
757				ctl_enqueue_isc(io);
758			break;
759		}
760		/* Performed on the Serializing (primary) SC, XFER mode only */
761		case CTL_MSG_DATAMOVE_DONE: {
762			if (msg_info.hdr.serializing_sc == NULL) {
763				printf("%s: serializing_sc == NULL!\n",
764				       __func__);
765				/* XXX KDM now what? */
766				break;
767			}
768			/*
769			 * We grab the sense information here in case
770			 * there was a failure, so we can return status
771			 * back to the initiator.
772			 */
773			io = msg_info.hdr.serializing_sc;
774			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
775			io->io_hdr.status = msg_info.hdr.status;
776			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
777			io->scsiio.sense_len = msg_info.scsi.sense_len;
778			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
779			io->io_hdr.port_status = msg_info.scsi.fetd_status;
780			io->scsiio.residual = msg_info.scsi.residual;
781			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
782			       sizeof(io->scsiio.sense_data));
783			ctl_enqueue_isc(io);
784			break;
785		}
786
787		/* Preformed on Originating SC, SER_ONLY mode */
788		case CTL_MSG_R2R:
789			io = msg_info.hdr.original_sc;
790			if (io == NULL) {
791				printf("%s: Major Bummer\n", __func__);
792				return;
793			} else {
794#if 0
795				printf("pOrig %x\n",(int) ctsio);
796#endif
797			}
798			io->io_hdr.msg_type = CTL_MSG_R2R;
799			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
800			ctl_enqueue_isc(io);
801			break;
802
803		/*
804		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
805		 * mode.
806		 * Performed on the Originating (i.e. secondary) SC in XFER
807		 * mode
808		 */
809		case CTL_MSG_FINISH_IO:
810			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
811				ctl_isc_handler_finish_xfer(ctl_softc,
812							    &msg_info);
813			else
814				ctl_isc_handler_finish_ser_only(ctl_softc,
815								&msg_info);
816			break;
817
818		/* Preformed on Originating SC */
819		case CTL_MSG_BAD_JUJU:
820			io = msg_info.hdr.original_sc;
821			if (io == NULL) {
822				printf("%s: Bad JUJU!, original_sc is NULL!\n",
823				       __func__);
824				break;
825			}
826			ctl_copy_sense_data(&msg_info, io);
827			/*
828			 * IO should have already been cleaned up on other
829			 * SC so clear this flag so we won't send a message
830			 * back to finish the IO there.
831			 */
832			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
833			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
834
835			/* io = msg_info.hdr.serializing_sc; */
836			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
837			ctl_enqueue_isc(io);
838			break;
839
840		/* Handle resets sent from the other side */
841		case CTL_MSG_MANAGE_TASKS: {
842			struct ctl_taskio *taskio;
843			taskio = (struct ctl_taskio *)ctl_alloc_io(
844				(void *)ctl_softc->othersc_pool);
845			if (taskio == NULL) {
846				printf("ctl_isc_event_handler: can't allocate "
847				       "ctl_io!\n");
848				/* Bad Juju */
849				/* should I just call the proper reset func
850				   here??? */
851				goto bailout;
852			}
853			ctl_zero_io((union ctl_io *)taskio);
854			taskio->io_hdr.io_type = CTL_IO_TASK;
855			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
856			taskio->io_hdr.nexus = msg_info.hdr.nexus;
857			taskio->task_action = msg_info.task.task_action;
858			taskio->tag_num = msg_info.task.tag_num;
859			taskio->tag_type = msg_info.task.tag_type;
860#ifdef CTL_TIME_IO
861			taskio->io_hdr.start_time = time_uptime;
862			getbintime(&taskio->io_hdr.start_bt);
863#if 0
864			cs_prof_gettime(&taskio->io_hdr.start_ticks);
865#endif
866#endif /* CTL_TIME_IO */
867			ctl_run_task((union ctl_io *)taskio);
868			break;
869		}
870		/* Persistent Reserve action which needs attention */
871		case CTL_MSG_PERS_ACTION:
872			presio = (struct ctl_prio *)ctl_alloc_io(
873				(void *)ctl_softc->othersc_pool);
874			if (presio == NULL) {
875				printf("ctl_isc_event_handler: can't allocate "
876				       "ctl_io!\n");
877				/* Bad Juju */
878				/* Need to set busy and send msg back */
879				goto bailout;
880			}
881			ctl_zero_io((union ctl_io *)presio);
882			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883			presio->pr_msg = msg_info.pr;
884			ctl_enqueue_isc((union ctl_io *)presio);
885			break;
886		case CTL_MSG_SYNC_FE:
887			rcv_sync_msg = 1;
888			break;
889		case CTL_MSG_APS_LOCK: {
890			// It's quicker to execute this then to
891			// queue it.
892			struct ctl_lun *lun;
893			struct ctl_page_index *page_index;
894			struct copan_aps_subpage *current_sp;
895			uint32_t targ_lun;
896
897			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
898			lun = ctl_softc->ctl_luns[targ_lun];
899			mtx_lock(&lun->lun_lock);
900			page_index = &lun->mode_pages.index[index_to_aps_page];
901			current_sp = (struct copan_aps_subpage *)
902				     (page_index->page_data +
903				     (page_index->page_len * CTL_PAGE_CURRENT));
904
905			current_sp->lock_active = msg_info.aps.lock_flag;
906			mtx_unlock(&lun->lun_lock);
907		        break;
908		}
909		default:
910		        printf("How did I get here?\n");
911		}
912	} else if (event == CTL_HA_EVT_MSG_SENT) {
913		if (param != CTL_HA_STATUS_SUCCESS) {
914			printf("Bad status from ctl_ha_msg_send status %d\n",
915			       param);
916		}
917		return;
918	} else if (event == CTL_HA_EVT_DISCONNECT) {
919		printf("CTL: Got a disconnect from Isc\n");
920		return;
921	} else {
922		printf("ctl_isc_event_handler: Unknown event %d\n", event);
923		return;
924	}
925
926bailout:
927	return;
928}
929
930static void
931ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
932{
933	struct scsi_sense_data *sense;
934
935	sense = &dest->scsiio.sense_data;
936	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
937	dest->scsiio.scsi_status = src->scsi.scsi_status;
938	dest->scsiio.sense_len = src->scsi.sense_len;
939	dest->io_hdr.status = src->hdr.status;
940}
941
942static int
943ctl_init(void)
944{
945	struct ctl_softc *softc;
946	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
947	struct ctl_port *port;
948        uint8_t sc_id =0;
949	int i, error, retval;
950	//int isc_retval;
951
952	retval = 0;
953	ctl_pause_rtr = 0;
954        rcv_sync_msg = 0;
955
956	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
957			       M_WAITOK | M_ZERO);
958	softc = control_softc;
959
960	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
961			      "cam/ctl");
962
963	softc->dev->si_drv1 = softc;
964
965	/*
966	 * By default, return a "bad LUN" peripheral qualifier for unknown
967	 * LUNs.  The user can override this default using the tunable or
968	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
969	 */
970	softc->inquiry_pq_no_lun = 1;
971	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
972			  &softc->inquiry_pq_no_lun);
973	sysctl_ctx_init(&softc->sysctl_ctx);
974	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
975		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
976		CTLFLAG_RD, 0, "CAM Target Layer");
977
978	if (softc->sysctl_tree == NULL) {
979		printf("%s: unable to allocate sysctl tree\n", __func__);
980		destroy_dev(softc->dev);
981		free(control_softc, M_DEVBUF);
982		control_softc = NULL;
983		return (ENOMEM);
984	}
985
986	SYSCTL_ADD_INT(&softc->sysctl_ctx,
987		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
988		       "inquiry_pq_no_lun", CTLFLAG_RW,
989		       &softc->inquiry_pq_no_lun, 0,
990		       "Report no lun possible for invalid LUNs");
991
992	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
993	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
994	softc->open_count = 0;
995
996	/*
997	 * Default to actually sending a SYNCHRONIZE CACHE command down to
998	 * the drive.
999	 */
1000	softc->flags = CTL_FLAG_REAL_SYNC;
1001
1002	/*
1003	 * In Copan's HA scheme, the "master" and "slave" roles are
1004	 * figured out through the slot the controller is in.  Although it
1005	 * is an active/active system, someone has to be in charge.
1006 	 */
1007#ifdef NEEDTOPORT
1008        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1009#endif
1010
1011        if (sc_id == 0) {
1012		softc->flags |= CTL_FLAG_MASTER_SHELF;
1013		persis_offset = 0;
1014	} else
1015		persis_offset = CTL_MAX_INITIATORS;
1016
1017	/*
1018	 * XXX KDM need to figure out where we want to get our target ID
1019	 * and WWID.  Is it different on each port?
1020	 */
1021	softc->target.id = 0;
1022	softc->target.wwid[0] = 0x12345678;
1023	softc->target.wwid[1] = 0x87654321;
1024	STAILQ_INIT(&softc->lun_list);
1025	STAILQ_INIT(&softc->pending_lun_queue);
1026	STAILQ_INIT(&softc->fe_list);
1027	STAILQ_INIT(&softc->port_list);
1028	STAILQ_INIT(&softc->be_list);
1029	STAILQ_INIT(&softc->io_pools);
1030	ctl_tpc_init(softc);
1031
1032	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1033			    &internal_pool)!= 0){
1034		printf("ctl: can't allocate %d entry internal pool, "
1035		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1036		return (ENOMEM);
1037	}
1038
1039	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1040			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1041		printf("ctl: can't allocate %d entry emergency pool, "
1042		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1043		ctl_pool_free(internal_pool);
1044		return (ENOMEM);
1045	}
1046
1047	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1048	                    &other_pool) != 0)
1049	{
1050		printf("ctl: can't allocate %d entry other SC pool, "
1051		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1052		ctl_pool_free(internal_pool);
1053		ctl_pool_free(emergency_pool);
1054		return (ENOMEM);
1055	}
1056
1057	softc->internal_pool = internal_pool;
1058	softc->emergency_pool = emergency_pool;
1059	softc->othersc_pool = other_pool;
1060
1061	if (worker_threads <= 0)
1062		worker_threads = max(1, mp_ncpus / 4);
1063	if (worker_threads > CTL_MAX_THREADS)
1064		worker_threads = CTL_MAX_THREADS;
1065
1066	for (i = 0; i < worker_threads; i++) {
1067		struct ctl_thread *thr = &softc->threads[i];
1068
1069		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1070		thr->ctl_softc = softc;
1071		STAILQ_INIT(&thr->incoming_queue);
1072		STAILQ_INIT(&thr->rtr_queue);
1073		STAILQ_INIT(&thr->done_queue);
1074		STAILQ_INIT(&thr->isc_queue);
1075
1076		error = kproc_kthread_add(ctl_work_thread, thr,
1077		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1078		if (error != 0) {
1079			printf("error creating CTL work thread!\n");
1080			ctl_pool_free(internal_pool);
1081			ctl_pool_free(emergency_pool);
1082			ctl_pool_free(other_pool);
1083			return (error);
1084		}
1085	}
1086	error = kproc_kthread_add(ctl_lun_thread, softc,
1087	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1088	if (error != 0) {
1089		printf("error creating CTL lun thread!\n");
1090		ctl_pool_free(internal_pool);
1091		ctl_pool_free(emergency_pool);
1092		ctl_pool_free(other_pool);
1093		return (error);
1094	}
1095	if (bootverbose)
1096		printf("ctl: CAM Target Layer loaded\n");
1097
1098	/*
1099	 * Initialize the ioctl front end.
1100	 */
1101	ctl_frontend_register(&ioctl_frontend);
1102	port = &softc->ioctl_info.port;
1103	port->frontend = &ioctl_frontend;
1104	sprintf(softc->ioctl_info.port_name, "ioctl");
1105	port->port_type = CTL_PORT_IOCTL;
1106	port->num_requested_ctl_io = 100;
1107	port->port_name = softc->ioctl_info.port_name;
1108	port->port_online = ctl_ioctl_online;
1109	port->port_offline = ctl_ioctl_offline;
1110	port->onoff_arg = &softc->ioctl_info;
1111	port->lun_enable = ctl_ioctl_lun_enable;
1112	port->lun_disable = ctl_ioctl_lun_disable;
1113	port->targ_lun_arg = &softc->ioctl_info;
1114	port->fe_datamove = ctl_ioctl_datamove;
1115	port->fe_done = ctl_ioctl_done;
1116	port->max_targets = 15;
1117	port->max_target_id = 15;
1118
1119	if (ctl_port_register(&softc->ioctl_info.port,
1120	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1121		printf("ctl: ioctl front end registration failed, will "
1122		       "continue anyway\n");
1123	}
1124
1125#ifdef CTL_IO_DELAY
1126	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1127		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1128		       sizeof(struct callout), CTL_TIMER_BYTES);
1129		return (EINVAL);
1130	}
1131#endif /* CTL_IO_DELAY */
1132
1133	return (0);
1134}
1135
1136void
1137ctl_shutdown(void)
1138{
1139	struct ctl_softc *softc;
1140	struct ctl_lun *lun, *next_lun;
1141	struct ctl_io_pool *pool;
1142
1143	softc = (struct ctl_softc *)control_softc;
1144
1145	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1146		printf("ctl: ioctl front end deregistration failed\n");
1147
1148	mtx_lock(&softc->ctl_lock);
1149
1150	/*
1151	 * Free up each LUN.
1152	 */
1153	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1154		next_lun = STAILQ_NEXT(lun, links);
1155		ctl_free_lun(lun);
1156	}
1157
1158	mtx_unlock(&softc->ctl_lock);
1159
1160	ctl_frontend_deregister(&ioctl_frontend);
1161
1162	/*
1163	 * This will rip the rug out from under any FETDs or anyone else
1164	 * that has a pool allocated.  Since we increment our module
1165	 * refcount any time someone outside the main CTL module allocates
1166	 * a pool, we shouldn't have any problems here.  The user won't be
1167	 * able to unload the CTL module until client modules have
1168	 * successfully unloaded.
1169	 */
1170	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1171		ctl_pool_free(pool);
1172
1173#if 0
1174	ctl_shutdown_thread(softc->work_thread);
1175	mtx_destroy(&softc->queue_lock);
1176#endif
1177
1178	ctl_tpc_shutdown(softc);
1179	mtx_destroy(&softc->pool_lock);
1180	mtx_destroy(&softc->ctl_lock);
1181
1182	destroy_dev(softc->dev);
1183
1184	sysctl_ctx_free(&softc->sysctl_ctx);
1185
1186	free(control_softc, M_DEVBUF);
1187	control_softc = NULL;
1188
1189	if (bootverbose)
1190		printf("ctl: CAM Target Layer unloaded\n");
1191}
1192
1193static int
1194ctl_module_event_handler(module_t mod, int what, void *arg)
1195{
1196
1197	switch (what) {
1198	case MOD_LOAD:
1199		return (ctl_init());
1200	case MOD_UNLOAD:
1201		return (EBUSY);
1202	default:
1203		return (EOPNOTSUPP);
1204	}
1205}
1206
1207/*
1208 * XXX KDM should we do some access checks here?  Bump a reference count to
1209 * prevent a CTL module from being unloaded while someone has it open?
1210 */
1211static int
1212ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1213{
1214	return (0);
1215}
1216
1217static int
1218ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1219{
1220	return (0);
1221}
1222
1223int
1224ctl_port_enable(ctl_port_type port_type)
1225{
1226	struct ctl_softc *softc;
1227	struct ctl_port *port;
1228
1229	if (ctl_is_single == 0) {
1230		union ctl_ha_msg msg_info;
1231		int isc_retval;
1232
1233#if 0
1234		printf("%s: HA mode, synchronizing frontend enable\n",
1235		        __func__);
1236#endif
1237		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1238	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1239		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1240			printf("Sync msg send error retval %d\n", isc_retval);
1241		}
1242		if (!rcv_sync_msg) {
1243			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1244			        sizeof(msg_info), 1);
1245		}
1246#if 0
1247        	printf("CTL:Frontend Enable\n");
1248	} else {
1249		printf("%s: single mode, skipping frontend synchronization\n",
1250		        __func__);
1251#endif
1252	}
1253
1254	softc = control_softc;
1255
1256	STAILQ_FOREACH(port, &softc->port_list, links) {
1257		if (port_type & port->port_type)
1258		{
1259#if 0
1260			printf("port %d\n", port->targ_port);
1261#endif
1262			ctl_port_online(port);
1263		}
1264	}
1265
1266	return (0);
1267}
1268
1269int
1270ctl_port_disable(ctl_port_type port_type)
1271{
1272	struct ctl_softc *softc;
1273	struct ctl_port *port;
1274
1275	softc = control_softc;
1276
1277	STAILQ_FOREACH(port, &softc->port_list, links) {
1278		if (port_type & port->port_type)
1279			ctl_port_offline(port);
1280	}
1281
1282	return (0);
1283}
1284
1285/*
1286 * Returns 0 for success, 1 for failure.
1287 * Currently the only failure mode is if there aren't enough entries
1288 * allocated.  So, in case of a failure, look at num_entries_dropped,
1289 * reallocate and try again.
1290 */
1291int
1292ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1293	      int *num_entries_filled, int *num_entries_dropped,
1294	      ctl_port_type port_type, int no_virtual)
1295{
1296	struct ctl_softc *softc;
1297	struct ctl_port *port;
1298	int entries_dropped, entries_filled;
1299	int retval;
1300	int i;
1301
1302	softc = control_softc;
1303
1304	retval = 0;
1305	entries_filled = 0;
1306	entries_dropped = 0;
1307
1308	i = 0;
1309	mtx_lock(&softc->ctl_lock);
1310	STAILQ_FOREACH(port, &softc->port_list, links) {
1311		struct ctl_port_entry *entry;
1312
1313		if ((port->port_type & port_type) == 0)
1314			continue;
1315
1316		if ((no_virtual != 0)
1317		 && (port->virtual_port != 0))
1318			continue;
1319
1320		if (entries_filled >= num_entries_alloced) {
1321			entries_dropped++;
1322			continue;
1323		}
1324		entry = &entries[i];
1325
1326		entry->port_type = port->port_type;
1327		strlcpy(entry->port_name, port->port_name,
1328			sizeof(entry->port_name));
1329		entry->physical_port = port->physical_port;
1330		entry->virtual_port = port->virtual_port;
1331		entry->wwnn = port->wwnn;
1332		entry->wwpn = port->wwpn;
1333
1334		i++;
1335		entries_filled++;
1336	}
1337
1338	mtx_unlock(&softc->ctl_lock);
1339
1340	if (entries_dropped > 0)
1341		retval = 1;
1342
1343	*num_entries_dropped = entries_dropped;
1344	*num_entries_filled = entries_filled;
1345
1346	return (retval);
1347}
1348
1349static void
1350ctl_ioctl_online(void *arg)
1351{
1352	struct ctl_ioctl_info *ioctl_info;
1353
1354	ioctl_info = (struct ctl_ioctl_info *)arg;
1355
1356	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1357}
1358
1359static void
1360ctl_ioctl_offline(void *arg)
1361{
1362	struct ctl_ioctl_info *ioctl_info;
1363
1364	ioctl_info = (struct ctl_ioctl_info *)arg;
1365
1366	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1367}
1368
1369/*
1370 * Remove an initiator by port number and initiator ID.
1371 * Returns 0 for success, -1 for failure.
1372 */
1373int
1374ctl_remove_initiator(struct ctl_port *port, int iid)
1375{
1376	struct ctl_softc *softc = control_softc;
1377
1378	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1379
1380	if (iid > CTL_MAX_INIT_PER_PORT) {
1381		printf("%s: initiator ID %u > maximun %u!\n",
1382		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1383		return (-1);
1384	}
1385
1386	mtx_lock(&softc->ctl_lock);
1387	port->wwpn_iid[iid].in_use--;
1388	port->wwpn_iid[iid].last_use = time_uptime;
1389	mtx_unlock(&softc->ctl_lock);
1390
1391	return (0);
1392}
1393
1394/*
1395 * Add an initiator to the initiator map.
1396 * Returns iid for success, < 0 for failure.
1397 */
1398int
1399ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1400{
1401	struct ctl_softc *softc = control_softc;
1402	time_t best_time;
1403	int i, best;
1404
1405	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1406
1407	if (iid >= CTL_MAX_INIT_PER_PORT) {
1408		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1409		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1410		free(name, M_CTL);
1411		return (-1);
1412	}
1413
1414	mtx_lock(&softc->ctl_lock);
1415
1416	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1417		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1418			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1419				iid = i;
1420				break;
1421			}
1422			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1423			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1424				iid = i;
1425				break;
1426			}
1427		}
1428	}
1429
1430	if (iid < 0) {
1431		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1432			if (port->wwpn_iid[i].in_use == 0 &&
1433			    port->wwpn_iid[i].wwpn == 0 &&
1434			    port->wwpn_iid[i].name == NULL) {
1435				iid = i;
1436				break;
1437			}
1438		}
1439	}
1440
1441	if (iid < 0) {
1442		best = -1;
1443		best_time = INT32_MAX;
1444		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1445			if (port->wwpn_iid[i].in_use == 0) {
1446				if (port->wwpn_iid[i].last_use < best_time) {
1447					best = i;
1448					best_time = port->wwpn_iid[i].last_use;
1449				}
1450			}
1451		}
1452		iid = best;
1453	}
1454
1455	if (iid < 0) {
1456		mtx_unlock(&softc->ctl_lock);
1457		free(name, M_CTL);
1458		return (-2);
1459	}
1460
1461	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1462		/*
1463		 * This is not an error yet.
1464		 */
1465		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1466#if 0
1467			printf("%s: port %d iid %u WWPN %#jx arrived"
1468			    " again\n", __func__, port->targ_port,
1469			    iid, (uintmax_t)wwpn);
1470#endif
1471			goto take;
1472		}
1473		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1474		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1475#if 0
1476			printf("%s: port %d iid %u name '%s' arrived"
1477			    " again\n", __func__, port->targ_port,
1478			    iid, name);
1479#endif
1480			goto take;
1481		}
1482
1483		/*
1484		 * This is an error, but what do we do about it?  The
1485		 * driver is telling us we have a new WWPN for this
1486		 * initiator ID, so we pretty much need to use it.
1487		 */
1488		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1489		    " but WWPN %#jx '%s' is still at that address\n",
1490		    __func__, port->targ_port, iid, wwpn, name,
1491		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1492		    port->wwpn_iid[iid].name);
1493
1494		/*
1495		 * XXX KDM clear have_ca and ua_pending on each LUN for
1496		 * this initiator.
1497		 */
1498	}
1499take:
1500	free(port->wwpn_iid[iid].name, M_CTL);
1501	port->wwpn_iid[iid].name = name;
1502	port->wwpn_iid[iid].wwpn = wwpn;
1503	port->wwpn_iid[iid].in_use++;
1504	mtx_unlock(&softc->ctl_lock);
1505
1506	return (iid);
1507}
1508
1509static int
1510ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1511{
1512	int len;
1513
1514	switch (port->port_type) {
1515	case CTL_PORT_FC:
1516	{
1517		struct scsi_transportid_fcp *id =
1518		    (struct scsi_transportid_fcp *)buf;
1519		if (port->wwpn_iid[iid].wwpn == 0)
1520			return (0);
1521		memset(id, 0, sizeof(*id));
1522		id->format_protocol = SCSI_PROTO_FC;
1523		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1524		return (sizeof(*id));
1525	}
1526	case CTL_PORT_ISCSI:
1527	{
1528		struct scsi_transportid_iscsi_port *id =
1529		    (struct scsi_transportid_iscsi_port *)buf;
1530		if (port->wwpn_iid[iid].name == NULL)
1531			return (0);
1532		memset(id, 0, 256);
1533		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1534		    SCSI_PROTO_ISCSI;
1535		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1536		len = roundup2(min(len, 252), 4);
1537		scsi_ulto2b(len, id->additional_length);
1538		return (sizeof(*id) + len);
1539	}
1540	case CTL_PORT_SAS:
1541	{
1542		struct scsi_transportid_sas *id =
1543		    (struct scsi_transportid_sas *)buf;
1544		if (port->wwpn_iid[iid].wwpn == 0)
1545			return (0);
1546		memset(id, 0, sizeof(*id));
1547		id->format_protocol = SCSI_PROTO_SAS;
1548		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1549		return (sizeof(*id));
1550	}
1551	default:
1552	{
1553		struct scsi_transportid_spi *id =
1554		    (struct scsi_transportid_spi *)buf;
1555		memset(id, 0, sizeof(*id));
1556		id->format_protocol = SCSI_PROTO_SPI;
1557		scsi_ulto2b(iid, id->scsi_addr);
1558		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1559		return (sizeof(*id));
1560	}
1561	}
1562}
1563
1564static int
1565ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1566{
1567	return (0);
1568}
1569
1570static int
1571ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1572{
1573	return (0);
1574}
1575
1576/*
1577 * Data movement routine for the CTL ioctl frontend port.
1578 */
1579static int
1580ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1581{
1582	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1583	struct ctl_sg_entry ext_entry, kern_entry;
1584	int ext_sglen, ext_sg_entries, kern_sg_entries;
1585	int ext_sg_start, ext_offset;
1586	int len_to_copy, len_copied;
1587	int kern_watermark, ext_watermark;
1588	int ext_sglist_malloced;
1589	int i, j;
1590
1591	ext_sglist_malloced = 0;
1592	ext_sg_start = 0;
1593	ext_offset = 0;
1594
1595	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1596
1597	/*
1598	 * If this flag is set, fake the data transfer.
1599	 */
1600	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1601		ctsio->ext_data_filled = ctsio->ext_data_len;
1602		goto bailout;
1603	}
1604
1605	/*
1606	 * To simplify things here, if we have a single buffer, stick it in
1607	 * a S/G entry and just make it a single entry S/G list.
1608	 */
1609	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1610		int len_seen;
1611
1612		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1613
1614		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1615							   M_WAITOK);
1616		ext_sglist_malloced = 1;
1617		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1618				   ext_sglen) != 0) {
1619			ctl_set_internal_failure(ctsio,
1620						 /*sks_valid*/ 0,
1621						 /*retry_count*/ 0);
1622			goto bailout;
1623		}
1624		ext_sg_entries = ctsio->ext_sg_entries;
1625		len_seen = 0;
1626		for (i = 0; i < ext_sg_entries; i++) {
1627			if ((len_seen + ext_sglist[i].len) >=
1628			     ctsio->ext_data_filled) {
1629				ext_sg_start = i;
1630				ext_offset = ctsio->ext_data_filled - len_seen;
1631				break;
1632			}
1633			len_seen += ext_sglist[i].len;
1634		}
1635	} else {
1636		ext_sglist = &ext_entry;
1637		ext_sglist->addr = ctsio->ext_data_ptr;
1638		ext_sglist->len = ctsio->ext_data_len;
1639		ext_sg_entries = 1;
1640		ext_sg_start = 0;
1641		ext_offset = ctsio->ext_data_filled;
1642	}
1643
1644	if (ctsio->kern_sg_entries > 0) {
1645		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1646		kern_sg_entries = ctsio->kern_sg_entries;
1647	} else {
1648		kern_sglist = &kern_entry;
1649		kern_sglist->addr = ctsio->kern_data_ptr;
1650		kern_sglist->len = ctsio->kern_data_len;
1651		kern_sg_entries = 1;
1652	}
1653
1654
1655	kern_watermark = 0;
1656	ext_watermark = ext_offset;
1657	len_copied = 0;
1658	for (i = ext_sg_start, j = 0;
1659	     i < ext_sg_entries && j < kern_sg_entries;) {
1660		uint8_t *ext_ptr, *kern_ptr;
1661
1662		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1663				      kern_sglist[j].len - kern_watermark);
1664
1665		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1666		ext_ptr = ext_ptr + ext_watermark;
1667		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1668			/*
1669			 * XXX KDM fix this!
1670			 */
1671			panic("need to implement bus address support");
1672#if 0
1673			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1674#endif
1675		} else
1676			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1677		kern_ptr = kern_ptr + kern_watermark;
1678
1679		kern_watermark += len_to_copy;
1680		ext_watermark += len_to_copy;
1681
1682		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1683		     CTL_FLAG_DATA_IN) {
1684			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1685					 "bytes to user\n", len_to_copy));
1686			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1687					 "to %p\n", kern_ptr, ext_ptr));
1688			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1689				ctl_set_internal_failure(ctsio,
1690							 /*sks_valid*/ 0,
1691							 /*retry_count*/ 0);
1692				goto bailout;
1693			}
1694		} else {
1695			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1696					 "bytes from user\n", len_to_copy));
1697			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1698					 "to %p\n", ext_ptr, kern_ptr));
1699			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1700				ctl_set_internal_failure(ctsio,
1701							 /*sks_valid*/ 0,
1702							 /*retry_count*/0);
1703				goto bailout;
1704			}
1705		}
1706
1707		len_copied += len_to_copy;
1708
1709		if (ext_sglist[i].len == ext_watermark) {
1710			i++;
1711			ext_watermark = 0;
1712		}
1713
1714		if (kern_sglist[j].len == kern_watermark) {
1715			j++;
1716			kern_watermark = 0;
1717		}
1718	}
1719
1720	ctsio->ext_data_filled += len_copied;
1721
1722	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1723			 "kern_sg_entries: %d\n", ext_sg_entries,
1724			 kern_sg_entries));
1725	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1726			 "kern_data_len = %d\n", ctsio->ext_data_len,
1727			 ctsio->kern_data_len));
1728
1729
1730	/* XXX KDM set residual?? */
1731bailout:
1732
1733	if (ext_sglist_malloced != 0)
1734		free(ext_sglist, M_CTL);
1735
1736	return (CTL_RETVAL_COMPLETE);
1737}
1738
1739/*
1740 * Serialize a command that went down the "wrong" side, and so was sent to
1741 * this controller for execution.  The logic is a little different than the
1742 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1743 * sent back to the other side, but in the success case, we execute the
1744 * command on this side (XFER mode) or tell the other side to execute it
1745 * (SER_ONLY mode).
1746 */
1747static int
1748ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1749{
1750	struct ctl_softc *ctl_softc;
1751	union ctl_ha_msg msg_info;
1752	struct ctl_lun *lun;
1753	int retval = 0;
1754	uint32_t targ_lun;
1755
1756	ctl_softc = control_softc;
1757
1758	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1759	lun = ctl_softc->ctl_luns[targ_lun];
1760	if (lun==NULL)
1761	{
1762		/*
1763		 * Why isn't LUN defined? The other side wouldn't
1764		 * send a cmd if the LUN is undefined.
1765		 */
1766		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1767
1768		/* "Logical unit not supported" */
1769		ctl_set_sense_data(&msg_info.scsi.sense_data,
1770				   lun,
1771				   /*sense_format*/SSD_TYPE_NONE,
1772				   /*current_error*/ 1,
1773				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1774				   /*asc*/ 0x25,
1775				   /*ascq*/ 0x00,
1776				   SSD_ELEM_NONE);
1777
1778		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1779		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1780		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1781		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1782		msg_info.hdr.serializing_sc = NULL;
1783		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1784	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1785				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1786		}
1787		return(1);
1788
1789	}
1790
1791	mtx_lock(&lun->lun_lock);
1792    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1793
1794	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1795		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1796		 ooa_links))) {
1797	case CTL_ACTION_BLOCK:
1798		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1799		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1800				  blocked_links);
1801		break;
1802	case CTL_ACTION_PASS:
1803	case CTL_ACTION_SKIP:
1804		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1805			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1806			ctl_enqueue_rtr((union ctl_io *)ctsio);
1807		} else {
1808
1809			/* send msg back to other side */
1810			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1811			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1812			msg_info.hdr.msg_type = CTL_MSG_R2R;
1813#if 0
1814			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1815#endif
1816		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1817			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1818			}
1819		}
1820		break;
1821	case CTL_ACTION_OVERLAP:
1822		/* OVERLAPPED COMMANDS ATTEMPTED */
1823		ctl_set_sense_data(&msg_info.scsi.sense_data,
1824				   lun,
1825				   /*sense_format*/SSD_TYPE_NONE,
1826				   /*current_error*/ 1,
1827				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1828				   /*asc*/ 0x4E,
1829				   /*ascq*/ 0x00,
1830				   SSD_ELEM_NONE);
1831
1832		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1833		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1834		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1835		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1836		msg_info.hdr.serializing_sc = NULL;
1837		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1838#if 0
1839		printf("BAD JUJU:Major Bummer Overlap\n");
1840#endif
1841		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1842		retval = 1;
1843		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1844		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1845		}
1846		break;
1847	case CTL_ACTION_OVERLAP_TAG:
1848		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1849		ctl_set_sense_data(&msg_info.scsi.sense_data,
1850				   lun,
1851				   /*sense_format*/SSD_TYPE_NONE,
1852				   /*current_error*/ 1,
1853				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854				   /*asc*/ 0x4D,
1855				   /*ascq*/ ctsio->tag_num & 0xff,
1856				   SSD_ELEM_NONE);
1857
1858		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862		msg_info.hdr.serializing_sc = NULL;
1863		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864#if 0
1865		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1866#endif
1867		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868		retval = 1;
1869		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871		}
1872		break;
1873	case CTL_ACTION_ERROR:
1874	default:
1875		/* "Internal target failure" */
1876		ctl_set_sense_data(&msg_info.scsi.sense_data,
1877				   lun,
1878				   /*sense_format*/SSD_TYPE_NONE,
1879				   /*current_error*/ 1,
1880				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1881				   /*asc*/ 0x44,
1882				   /*ascq*/ 0x00,
1883				   SSD_ELEM_NONE);
1884
1885		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1886		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1887		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1888		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1889		msg_info.hdr.serializing_sc = NULL;
1890		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1891#if 0
1892		printf("BAD JUJU:Major Bummer HW Error\n");
1893#endif
1894		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1895		retval = 1;
1896		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1897		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1898		}
1899		break;
1900	}
1901	mtx_unlock(&lun->lun_lock);
1902	return (retval);
1903}
1904
1905static int
1906ctl_ioctl_submit_wait(union ctl_io *io)
1907{
1908	struct ctl_fe_ioctl_params params;
1909	ctl_fe_ioctl_state last_state;
1910	int done, retval;
1911
1912	retval = 0;
1913
1914	bzero(&params, sizeof(params));
1915
1916	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1917	cv_init(&params.sem, "ctlioccv");
1918	params.state = CTL_IOCTL_INPROG;
1919	last_state = params.state;
1920
1921	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1922
1923	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1924
1925	/* This shouldn't happen */
1926	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1927		return (retval);
1928
1929	done = 0;
1930
1931	do {
1932		mtx_lock(&params.ioctl_mtx);
1933		/*
1934		 * Check the state here, and don't sleep if the state has
1935		 * already changed (i.e. wakeup has already occured, but we
1936		 * weren't waiting yet).
1937		 */
1938		if (params.state == last_state) {
1939			/* XXX KDM cv_wait_sig instead? */
1940			cv_wait(&params.sem, &params.ioctl_mtx);
1941		}
1942		last_state = params.state;
1943
1944		switch (params.state) {
1945		case CTL_IOCTL_INPROG:
1946			/* Why did we wake up? */
1947			/* XXX KDM error here? */
1948			mtx_unlock(&params.ioctl_mtx);
1949			break;
1950		case CTL_IOCTL_DATAMOVE:
1951			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1952
1953			/*
1954			 * change last_state back to INPROG to avoid
1955			 * deadlock on subsequent data moves.
1956			 */
1957			params.state = last_state = CTL_IOCTL_INPROG;
1958
1959			mtx_unlock(&params.ioctl_mtx);
1960			ctl_ioctl_do_datamove(&io->scsiio);
1961			/*
1962			 * Note that in some cases, most notably writes,
1963			 * this will queue the I/O and call us back later.
1964			 * In other cases, generally reads, this routine
1965			 * will immediately call back and wake us up,
1966			 * probably using our own context.
1967			 */
1968			io->scsiio.be_move_done(io);
1969			break;
1970		case CTL_IOCTL_DONE:
1971			mtx_unlock(&params.ioctl_mtx);
1972			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1973			done = 1;
1974			break;
1975		default:
1976			mtx_unlock(&params.ioctl_mtx);
1977			/* XXX KDM error here? */
1978			break;
1979		}
1980	} while (done == 0);
1981
1982	mtx_destroy(&params.ioctl_mtx);
1983	cv_destroy(&params.sem);
1984
1985	return (CTL_RETVAL_COMPLETE);
1986}
1987
1988static void
1989ctl_ioctl_datamove(union ctl_io *io)
1990{
1991	struct ctl_fe_ioctl_params *params;
1992
1993	params = (struct ctl_fe_ioctl_params *)
1994		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1995
1996	mtx_lock(&params->ioctl_mtx);
1997	params->state = CTL_IOCTL_DATAMOVE;
1998	cv_broadcast(&params->sem);
1999	mtx_unlock(&params->ioctl_mtx);
2000}
2001
2002static void
2003ctl_ioctl_done(union ctl_io *io)
2004{
2005	struct ctl_fe_ioctl_params *params;
2006
2007	params = (struct ctl_fe_ioctl_params *)
2008		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2009
2010	mtx_lock(&params->ioctl_mtx);
2011	params->state = CTL_IOCTL_DONE;
2012	cv_broadcast(&params->sem);
2013	mtx_unlock(&params->ioctl_mtx);
2014}
2015
2016static void
2017ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2018{
2019	struct ctl_fe_ioctl_startstop_info *sd_info;
2020
2021	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2022
2023	sd_info->hs_info.status = metatask->status;
2024	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2025	sd_info->hs_info.luns_complete =
2026		metatask->taskinfo.startstop.luns_complete;
2027	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2028
2029	cv_broadcast(&sd_info->sem);
2030}
2031
2032static void
2033ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2034{
2035	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2036
2037	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2038
2039	mtx_lock(fe_bbr_info->lock);
2040	fe_bbr_info->bbr_info->status = metatask->status;
2041	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2042	fe_bbr_info->wakeup_done = 1;
2043	mtx_unlock(fe_bbr_info->lock);
2044
2045	cv_broadcast(&fe_bbr_info->sem);
2046}
2047
2048/*
2049 * Returns 0 for success, errno for failure.
2050 */
2051static int
2052ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2053		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2054{
2055	union ctl_io *io;
2056	int retval;
2057
2058	retval = 0;
2059
2060	mtx_lock(&lun->lun_lock);
2061	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2062	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2063	     ooa_links)) {
2064		struct ctl_ooa_entry *entry;
2065
2066		/*
2067		 * If we've got more than we can fit, just count the
2068		 * remaining entries.
2069		 */
2070		if (*cur_fill_num >= ooa_hdr->alloc_num)
2071			continue;
2072
2073		entry = &kern_entries[*cur_fill_num];
2074
2075		entry->tag_num = io->scsiio.tag_num;
2076		entry->lun_num = lun->lun;
2077#ifdef CTL_TIME_IO
2078		entry->start_bt = io->io_hdr.start_bt;
2079#endif
2080		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2081		entry->cdb_len = io->scsiio.cdb_len;
2082		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2083			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2084
2085		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2086			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2087
2088		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2089			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2090
2091		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2092			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2093
2094		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2095			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2096	}
2097	mtx_unlock(&lun->lun_lock);
2098
2099	return (retval);
2100}
2101
2102static void *
2103ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2104		 size_t error_str_len)
2105{
2106	void *kptr;
2107
2108	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2109
2110	if (copyin(user_addr, kptr, len) != 0) {
2111		snprintf(error_str, error_str_len, "Error copying %d bytes "
2112			 "from user address %p to kernel address %p", len,
2113			 user_addr, kptr);
2114		free(kptr, M_CTL);
2115		return (NULL);
2116	}
2117
2118	return (kptr);
2119}
2120
2121static void
2122ctl_free_args(int num_args, struct ctl_be_arg *args)
2123{
2124	int i;
2125
2126	if (args == NULL)
2127		return;
2128
2129	for (i = 0; i < num_args; i++) {
2130		free(args[i].kname, M_CTL);
2131		free(args[i].kvalue, M_CTL);
2132	}
2133
2134	free(args, M_CTL);
2135}
2136
2137static struct ctl_be_arg *
2138ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2139		char *error_str, size_t error_str_len)
2140{
2141	struct ctl_be_arg *args;
2142	int i;
2143
2144	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2145				error_str, error_str_len);
2146
2147	if (args == NULL)
2148		goto bailout;
2149
2150	for (i = 0; i < num_args; i++) {
2151		args[i].kname = NULL;
2152		args[i].kvalue = NULL;
2153	}
2154
2155	for (i = 0; i < num_args; i++) {
2156		uint8_t *tmpptr;
2157
2158		args[i].kname = ctl_copyin_alloc(args[i].name,
2159			args[i].namelen, error_str, error_str_len);
2160		if (args[i].kname == NULL)
2161			goto bailout;
2162
2163		if (args[i].kname[args[i].namelen - 1] != '\0') {
2164			snprintf(error_str, error_str_len, "Argument %d "
2165				 "name is not NUL-terminated", i);
2166			goto bailout;
2167		}
2168
2169		if (args[i].flags & CTL_BEARG_RD) {
2170			tmpptr = ctl_copyin_alloc(args[i].value,
2171				args[i].vallen, error_str, error_str_len);
2172			if (tmpptr == NULL)
2173				goto bailout;
2174			if ((args[i].flags & CTL_BEARG_ASCII)
2175			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2176				snprintf(error_str, error_str_len, "Argument "
2177				    "%d value is not NUL-terminated", i);
2178				goto bailout;
2179			}
2180			args[i].kvalue = tmpptr;
2181		} else {
2182			args[i].kvalue = malloc(args[i].vallen,
2183			    M_CTL, M_WAITOK | M_ZERO);
2184		}
2185	}
2186
2187	return (args);
2188bailout:
2189
2190	ctl_free_args(num_args, args);
2191
2192	return (NULL);
2193}
2194
2195static void
2196ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2197{
2198	int i;
2199
2200	for (i = 0; i < num_args; i++) {
2201		if (args[i].flags & CTL_BEARG_WR)
2202			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2203	}
2204}
2205
2206/*
2207 * Escape characters that are illegal or not recommended in XML.
2208 */
2209int
2210ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2211{
2212	int retval;
2213
2214	retval = 0;
2215
2216	for (; *str; str++) {
2217		switch (*str) {
2218		case '&':
2219			retval = sbuf_printf(sb, "&amp;");
2220			break;
2221		case '>':
2222			retval = sbuf_printf(sb, "&gt;");
2223			break;
2224		case '<':
2225			retval = sbuf_printf(sb, "&lt;");
2226			break;
2227		default:
2228			retval = sbuf_putc(sb, *str);
2229			break;
2230		}
2231
2232		if (retval != 0)
2233			break;
2234
2235	}
2236
2237	return (retval);
2238}
2239
2240static int
2241ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2242	  struct thread *td)
2243{
2244	struct ctl_softc *softc;
2245	int retval;
2246
2247	softc = control_softc;
2248
2249	retval = 0;
2250
2251	switch (cmd) {
2252	case CTL_IO: {
2253		union ctl_io *io;
2254		void *pool_tmp;
2255
2256		/*
2257		 * If we haven't been "enabled", don't allow any SCSI I/O
2258		 * to this FETD.
2259		 */
2260		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2261			retval = EPERM;
2262			break;
2263		}
2264
2265		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2266		if (io == NULL) {
2267			printf("ctl_ioctl: can't allocate ctl_io!\n");
2268			retval = ENOSPC;
2269			break;
2270		}
2271
2272		/*
2273		 * Need to save the pool reference so it doesn't get
2274		 * spammed by the user's ctl_io.
2275		 */
2276		pool_tmp = io->io_hdr.pool;
2277
2278		memcpy(io, (void *)addr, sizeof(*io));
2279
2280		io->io_hdr.pool = pool_tmp;
2281		/*
2282		 * No status yet, so make sure the status is set properly.
2283		 */
2284		io->io_hdr.status = CTL_STATUS_NONE;
2285
2286		/*
2287		 * The user sets the initiator ID, target and LUN IDs.
2288		 */
2289		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2290		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2291		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2292		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2293			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2294
2295		retval = ctl_ioctl_submit_wait(io);
2296
2297		if (retval != 0) {
2298			ctl_free_io(io);
2299			break;
2300		}
2301
2302		memcpy((void *)addr, io, sizeof(*io));
2303
2304		/* return this to our pool */
2305		ctl_free_io(io);
2306
2307		break;
2308	}
2309	case CTL_ENABLE_PORT:
2310	case CTL_DISABLE_PORT:
2311	case CTL_SET_PORT_WWNS: {
2312		struct ctl_port *port;
2313		struct ctl_port_entry *entry;
2314
2315		entry = (struct ctl_port_entry *)addr;
2316
2317		mtx_lock(&softc->ctl_lock);
2318		STAILQ_FOREACH(port, &softc->port_list, links) {
2319			int action, done;
2320
2321			action = 0;
2322			done = 0;
2323
2324			if ((entry->port_type == CTL_PORT_NONE)
2325			 && (entry->targ_port == port->targ_port)) {
2326				/*
2327				 * If the user only wants to enable or
2328				 * disable or set WWNs on a specific port,
2329				 * do the operation and we're done.
2330				 */
2331				action = 1;
2332				done = 1;
2333			} else if (entry->port_type & port->port_type) {
2334				/*
2335				 * Compare the user's type mask with the
2336				 * particular frontend type to see if we
2337				 * have a match.
2338				 */
2339				action = 1;
2340				done = 0;
2341
2342				/*
2343				 * Make sure the user isn't trying to set
2344				 * WWNs on multiple ports at the same time.
2345				 */
2346				if (cmd == CTL_SET_PORT_WWNS) {
2347					printf("%s: Can't set WWNs on "
2348					       "multiple ports\n", __func__);
2349					retval = EINVAL;
2350					break;
2351				}
2352			}
2353			if (action != 0) {
2354				/*
2355				 * XXX KDM we have to drop the lock here,
2356				 * because the online/offline operations
2357				 * can potentially block.  We need to
2358				 * reference count the frontends so they
2359				 * can't go away,
2360				 */
2361				mtx_unlock(&softc->ctl_lock);
2362
2363				if (cmd == CTL_ENABLE_PORT) {
2364					struct ctl_lun *lun;
2365
2366					STAILQ_FOREACH(lun, &softc->lun_list,
2367						       links) {
2368						port->lun_enable(port->targ_lun_arg,
2369						    lun->target,
2370						    lun->lun);
2371					}
2372
2373					ctl_port_online(port);
2374				} else if (cmd == CTL_DISABLE_PORT) {
2375					struct ctl_lun *lun;
2376
2377					ctl_port_offline(port);
2378
2379					STAILQ_FOREACH(lun, &softc->lun_list,
2380						       links) {
2381						port->lun_disable(
2382						    port->targ_lun_arg,
2383						    lun->target,
2384						    lun->lun);
2385					}
2386				}
2387
2388				mtx_lock(&softc->ctl_lock);
2389
2390				if (cmd == CTL_SET_PORT_WWNS)
2391					ctl_port_set_wwns(port,
2392					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2393					    1 : 0, entry->wwnn,
2394					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2395					    1 : 0, entry->wwpn);
2396			}
2397			if (done != 0)
2398				break;
2399		}
2400		mtx_unlock(&softc->ctl_lock);
2401		break;
2402	}
2403	case CTL_GET_PORT_LIST: {
2404		struct ctl_port *port;
2405		struct ctl_port_list *list;
2406		int i;
2407
2408		list = (struct ctl_port_list *)addr;
2409
2410		if (list->alloc_len != (list->alloc_num *
2411		    sizeof(struct ctl_port_entry))) {
2412			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2413			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2414			       "%zu\n", __func__, list->alloc_len,
2415			       list->alloc_num, sizeof(struct ctl_port_entry));
2416			retval = EINVAL;
2417			break;
2418		}
2419		list->fill_len = 0;
2420		list->fill_num = 0;
2421		list->dropped_num = 0;
2422		i = 0;
2423		mtx_lock(&softc->ctl_lock);
2424		STAILQ_FOREACH(port, &softc->port_list, links) {
2425			struct ctl_port_entry entry, *list_entry;
2426
2427			if (list->fill_num >= list->alloc_num) {
2428				list->dropped_num++;
2429				continue;
2430			}
2431
2432			entry.port_type = port->port_type;
2433			strlcpy(entry.port_name, port->port_name,
2434				sizeof(entry.port_name));
2435			entry.targ_port = port->targ_port;
2436			entry.physical_port = port->physical_port;
2437			entry.virtual_port = port->virtual_port;
2438			entry.wwnn = port->wwnn;
2439			entry.wwpn = port->wwpn;
2440			if (port->status & CTL_PORT_STATUS_ONLINE)
2441				entry.online = 1;
2442			else
2443				entry.online = 0;
2444
2445			list_entry = &list->entries[i];
2446
2447			retval = copyout(&entry, list_entry, sizeof(entry));
2448			if (retval != 0) {
2449				printf("%s: CTL_GET_PORT_LIST: copyout "
2450				       "returned %d\n", __func__, retval);
2451				break;
2452			}
2453			i++;
2454			list->fill_num++;
2455			list->fill_len += sizeof(entry);
2456		}
2457		mtx_unlock(&softc->ctl_lock);
2458
2459		/*
2460		 * If this is non-zero, we had a copyout fault, so there's
2461		 * probably no point in attempting to set the status inside
2462		 * the structure.
2463		 */
2464		if (retval != 0)
2465			break;
2466
2467		if (list->dropped_num > 0)
2468			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2469		else
2470			list->status = CTL_PORT_LIST_OK;
2471		break;
2472	}
2473	case CTL_DUMP_OOA: {
2474		struct ctl_lun *lun;
2475		union ctl_io *io;
2476		char printbuf[128];
2477		struct sbuf sb;
2478
2479		mtx_lock(&softc->ctl_lock);
2480		printf("Dumping OOA queues:\n");
2481		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2482			mtx_lock(&lun->lun_lock);
2483			for (io = (union ctl_io *)TAILQ_FIRST(
2484			     &lun->ooa_queue); io != NULL;
2485			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2486			     ooa_links)) {
2487				sbuf_new(&sb, printbuf, sizeof(printbuf),
2488					 SBUF_FIXEDLEN);
2489				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2490					    (intmax_t)lun->lun,
2491					    io->scsiio.tag_num,
2492					    (io->io_hdr.flags &
2493					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2494					    (io->io_hdr.flags &
2495					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2496					    (io->io_hdr.flags &
2497					    CTL_FLAG_ABORT) ? " ABORT" : "",
2498			                    (io->io_hdr.flags &
2499		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2500				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2501				sbuf_finish(&sb);
2502				printf("%s\n", sbuf_data(&sb));
2503			}
2504			mtx_unlock(&lun->lun_lock);
2505		}
2506		printf("OOA queues dump done\n");
2507		mtx_unlock(&softc->ctl_lock);
2508		break;
2509	}
2510	case CTL_GET_OOA: {
2511		struct ctl_lun *lun;
2512		struct ctl_ooa *ooa_hdr;
2513		struct ctl_ooa_entry *entries;
2514		uint32_t cur_fill_num;
2515
2516		ooa_hdr = (struct ctl_ooa *)addr;
2517
2518		if ((ooa_hdr->alloc_len == 0)
2519		 || (ooa_hdr->alloc_num == 0)) {
2520			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2521			       "must be non-zero\n", __func__,
2522			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2523			retval = EINVAL;
2524			break;
2525		}
2526
2527		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2528		    sizeof(struct ctl_ooa_entry))) {
2529			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2530			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2531			       __func__, ooa_hdr->alloc_len,
2532			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2533			retval = EINVAL;
2534			break;
2535		}
2536
2537		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2538		if (entries == NULL) {
2539			printf("%s: could not allocate %d bytes for OOA "
2540			       "dump\n", __func__, ooa_hdr->alloc_len);
2541			retval = ENOMEM;
2542			break;
2543		}
2544
2545		mtx_lock(&softc->ctl_lock);
2546		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2547		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2548		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2549			mtx_unlock(&softc->ctl_lock);
2550			free(entries, M_CTL);
2551			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2552			       __func__, (uintmax_t)ooa_hdr->lun_num);
2553			retval = EINVAL;
2554			break;
2555		}
2556
2557		cur_fill_num = 0;
2558
2559		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2560			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2561				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2562					ooa_hdr, entries);
2563				if (retval != 0)
2564					break;
2565			}
2566			if (retval != 0) {
2567				mtx_unlock(&softc->ctl_lock);
2568				free(entries, M_CTL);
2569				break;
2570			}
2571		} else {
2572			lun = softc->ctl_luns[ooa_hdr->lun_num];
2573
2574			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2575						    entries);
2576		}
2577		mtx_unlock(&softc->ctl_lock);
2578
2579		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2580		ooa_hdr->fill_len = ooa_hdr->fill_num *
2581			sizeof(struct ctl_ooa_entry);
2582		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2583		if (retval != 0) {
2584			printf("%s: error copying out %d bytes for OOA dump\n",
2585			       __func__, ooa_hdr->fill_len);
2586		}
2587
2588		getbintime(&ooa_hdr->cur_bt);
2589
2590		if (cur_fill_num > ooa_hdr->alloc_num) {
2591			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2592			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2593		} else {
2594			ooa_hdr->dropped_num = 0;
2595			ooa_hdr->status = CTL_OOA_OK;
2596		}
2597
2598		free(entries, M_CTL);
2599		break;
2600	}
2601	case CTL_CHECK_OOA: {
2602		union ctl_io *io;
2603		struct ctl_lun *lun;
2604		struct ctl_ooa_info *ooa_info;
2605
2606
2607		ooa_info = (struct ctl_ooa_info *)addr;
2608
2609		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2610			ooa_info->status = CTL_OOA_INVALID_LUN;
2611			break;
2612		}
2613		mtx_lock(&softc->ctl_lock);
2614		lun = softc->ctl_luns[ooa_info->lun_id];
2615		if (lun == NULL) {
2616			mtx_unlock(&softc->ctl_lock);
2617			ooa_info->status = CTL_OOA_INVALID_LUN;
2618			break;
2619		}
2620		mtx_lock(&lun->lun_lock);
2621		mtx_unlock(&softc->ctl_lock);
2622		ooa_info->num_entries = 0;
2623		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2624		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2625		     &io->io_hdr, ooa_links)) {
2626			ooa_info->num_entries++;
2627		}
2628		mtx_unlock(&lun->lun_lock);
2629
2630		ooa_info->status = CTL_OOA_SUCCESS;
2631
2632		break;
2633	}
2634	case CTL_HARD_START:
2635	case CTL_HARD_STOP: {
2636		struct ctl_fe_ioctl_startstop_info ss_info;
2637		struct cfi_metatask *metatask;
2638		struct mtx hs_mtx;
2639
2640		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2641
2642		cv_init(&ss_info.sem, "hard start/stop cv" );
2643
2644		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2645		if (metatask == NULL) {
2646			retval = ENOMEM;
2647			mtx_destroy(&hs_mtx);
2648			break;
2649		}
2650
2651		if (cmd == CTL_HARD_START)
2652			metatask->tasktype = CFI_TASK_STARTUP;
2653		else
2654			metatask->tasktype = CFI_TASK_SHUTDOWN;
2655
2656		metatask->callback = ctl_ioctl_hard_startstop_callback;
2657		metatask->callback_arg = &ss_info;
2658
2659		cfi_action(metatask);
2660
2661		/* Wait for the callback */
2662		mtx_lock(&hs_mtx);
2663		cv_wait_sig(&ss_info.sem, &hs_mtx);
2664		mtx_unlock(&hs_mtx);
2665
2666		/*
2667		 * All information has been copied from the metatask by the
2668		 * time cv_broadcast() is called, so we free the metatask here.
2669		 */
2670		cfi_free_metatask(metatask);
2671
2672		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2673
2674		mtx_destroy(&hs_mtx);
2675		break;
2676	}
2677	case CTL_BBRREAD: {
2678		struct ctl_bbrread_info *bbr_info;
2679		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2680		struct mtx bbr_mtx;
2681		struct cfi_metatask *metatask;
2682
2683		bbr_info = (struct ctl_bbrread_info *)addr;
2684
2685		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2686
2687		bzero(&bbr_mtx, sizeof(bbr_mtx));
2688		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2689
2690		fe_bbr_info.bbr_info = bbr_info;
2691		fe_bbr_info.lock = &bbr_mtx;
2692
2693		cv_init(&fe_bbr_info.sem, "BBR read cv");
2694		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2695
2696		if (metatask == NULL) {
2697			mtx_destroy(&bbr_mtx);
2698			cv_destroy(&fe_bbr_info.sem);
2699			retval = ENOMEM;
2700			break;
2701		}
2702		metatask->tasktype = CFI_TASK_BBRREAD;
2703		metatask->callback = ctl_ioctl_bbrread_callback;
2704		metatask->callback_arg = &fe_bbr_info;
2705		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2706		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2707		metatask->taskinfo.bbrread.len = bbr_info->len;
2708
2709		cfi_action(metatask);
2710
2711		mtx_lock(&bbr_mtx);
2712		while (fe_bbr_info.wakeup_done == 0)
2713			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2714		mtx_unlock(&bbr_mtx);
2715
2716		bbr_info->status = metatask->status;
2717		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2718		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2719		memcpy(&bbr_info->sense_data,
2720		       &metatask->taskinfo.bbrread.sense_data,
2721		       ctl_min(sizeof(bbr_info->sense_data),
2722			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2723
2724		cfi_free_metatask(metatask);
2725
2726		mtx_destroy(&bbr_mtx);
2727		cv_destroy(&fe_bbr_info.sem);
2728
2729		break;
2730	}
2731	case CTL_DELAY_IO: {
2732		struct ctl_io_delay_info *delay_info;
2733#ifdef CTL_IO_DELAY
2734		struct ctl_lun *lun;
2735#endif /* CTL_IO_DELAY */
2736
2737		delay_info = (struct ctl_io_delay_info *)addr;
2738
2739#ifdef CTL_IO_DELAY
2740		mtx_lock(&softc->ctl_lock);
2741
2742		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2743		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2744			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2745		} else {
2746			lun = softc->ctl_luns[delay_info->lun_id];
2747			mtx_lock(&lun->lun_lock);
2748
2749			delay_info->status = CTL_DELAY_STATUS_OK;
2750
2751			switch (delay_info->delay_type) {
2752			case CTL_DELAY_TYPE_CONT:
2753				break;
2754			case CTL_DELAY_TYPE_ONESHOT:
2755				break;
2756			default:
2757				delay_info->status =
2758					CTL_DELAY_STATUS_INVALID_TYPE;
2759				break;
2760			}
2761
2762			switch (delay_info->delay_loc) {
2763			case CTL_DELAY_LOC_DATAMOVE:
2764				lun->delay_info.datamove_type =
2765					delay_info->delay_type;
2766				lun->delay_info.datamove_delay =
2767					delay_info->delay_secs;
2768				break;
2769			case CTL_DELAY_LOC_DONE:
2770				lun->delay_info.done_type =
2771					delay_info->delay_type;
2772				lun->delay_info.done_delay =
2773					delay_info->delay_secs;
2774				break;
2775			default:
2776				delay_info->status =
2777					CTL_DELAY_STATUS_INVALID_LOC;
2778				break;
2779			}
2780			mtx_unlock(&lun->lun_lock);
2781		}
2782
2783		mtx_unlock(&softc->ctl_lock);
2784#else
2785		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2786#endif /* CTL_IO_DELAY */
2787		break;
2788	}
2789	case CTL_REALSYNC_SET: {
2790		int *syncstate;
2791
2792		syncstate = (int *)addr;
2793
2794		mtx_lock(&softc->ctl_lock);
2795		switch (*syncstate) {
2796		case 0:
2797			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2798			break;
2799		case 1:
2800			softc->flags |= CTL_FLAG_REAL_SYNC;
2801			break;
2802		default:
2803			retval = EINVAL;
2804			break;
2805		}
2806		mtx_unlock(&softc->ctl_lock);
2807		break;
2808	}
2809	case CTL_REALSYNC_GET: {
2810		int *syncstate;
2811
2812		syncstate = (int*)addr;
2813
2814		mtx_lock(&softc->ctl_lock);
2815		if (softc->flags & CTL_FLAG_REAL_SYNC)
2816			*syncstate = 1;
2817		else
2818			*syncstate = 0;
2819		mtx_unlock(&softc->ctl_lock);
2820
2821		break;
2822	}
2823	case CTL_SETSYNC:
2824	case CTL_GETSYNC: {
2825		struct ctl_sync_info *sync_info;
2826		struct ctl_lun *lun;
2827
2828		sync_info = (struct ctl_sync_info *)addr;
2829
2830		mtx_lock(&softc->ctl_lock);
2831		lun = softc->ctl_luns[sync_info->lun_id];
2832		if (lun == NULL) {
2833			mtx_unlock(&softc->ctl_lock);
2834			sync_info->status = CTL_GS_SYNC_NO_LUN;
2835		}
2836		/*
2837		 * Get or set the sync interval.  We're not bounds checking
2838		 * in the set case, hopefully the user won't do something
2839		 * silly.
2840		 */
2841		mtx_lock(&lun->lun_lock);
2842		mtx_unlock(&softc->ctl_lock);
2843		if (cmd == CTL_GETSYNC)
2844			sync_info->sync_interval = lun->sync_interval;
2845		else
2846			lun->sync_interval = sync_info->sync_interval;
2847		mtx_unlock(&lun->lun_lock);
2848
2849		sync_info->status = CTL_GS_SYNC_OK;
2850
2851		break;
2852	}
2853	case CTL_GETSTATS: {
2854		struct ctl_stats *stats;
2855		struct ctl_lun *lun;
2856		int i;
2857
2858		stats = (struct ctl_stats *)addr;
2859
2860		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2861		     stats->alloc_len) {
2862			stats->status = CTL_SS_NEED_MORE_SPACE;
2863			stats->num_luns = softc->num_luns;
2864			break;
2865		}
2866		/*
2867		 * XXX KDM no locking here.  If the LUN list changes,
2868		 * things can blow up.
2869		 */
2870		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2871		     i++, lun = STAILQ_NEXT(lun, links)) {
2872			retval = copyout(&lun->stats, &stats->lun_stats[i],
2873					 sizeof(lun->stats));
2874			if (retval != 0)
2875				break;
2876		}
2877		stats->num_luns = softc->num_luns;
2878		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2879				 softc->num_luns;
2880		stats->status = CTL_SS_OK;
2881#ifdef CTL_TIME_IO
2882		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2883#else
2884		stats->flags = CTL_STATS_FLAG_NONE;
2885#endif
2886		getnanouptime(&stats->timestamp);
2887		break;
2888	}
2889	case CTL_ERROR_INJECT: {
2890		struct ctl_error_desc *err_desc, *new_err_desc;
2891		struct ctl_lun *lun;
2892
2893		err_desc = (struct ctl_error_desc *)addr;
2894
2895		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2896				      M_WAITOK | M_ZERO);
2897		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2898
2899		mtx_lock(&softc->ctl_lock);
2900		lun = softc->ctl_luns[err_desc->lun_id];
2901		if (lun == NULL) {
2902			mtx_unlock(&softc->ctl_lock);
2903			free(new_err_desc, M_CTL);
2904			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2905			       __func__, (uintmax_t)err_desc->lun_id);
2906			retval = EINVAL;
2907			break;
2908		}
2909		mtx_lock(&lun->lun_lock);
2910		mtx_unlock(&softc->ctl_lock);
2911
2912		/*
2913		 * We could do some checking here to verify the validity
2914		 * of the request, but given the complexity of error
2915		 * injection requests, the checking logic would be fairly
2916		 * complex.
2917		 *
2918		 * For now, if the request is invalid, it just won't get
2919		 * executed and might get deleted.
2920		 */
2921		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2922
2923		/*
2924		 * XXX KDM check to make sure the serial number is unique,
2925		 * in case we somehow manage to wrap.  That shouldn't
2926		 * happen for a very long time, but it's the right thing to
2927		 * do.
2928		 */
2929		new_err_desc->serial = lun->error_serial;
2930		err_desc->serial = lun->error_serial;
2931		lun->error_serial++;
2932
2933		mtx_unlock(&lun->lun_lock);
2934		break;
2935	}
2936	case CTL_ERROR_INJECT_DELETE: {
2937		struct ctl_error_desc *delete_desc, *desc, *desc2;
2938		struct ctl_lun *lun;
2939		int delete_done;
2940
2941		delete_desc = (struct ctl_error_desc *)addr;
2942		delete_done = 0;
2943
2944		mtx_lock(&softc->ctl_lock);
2945		lun = softc->ctl_luns[delete_desc->lun_id];
2946		if (lun == NULL) {
2947			mtx_unlock(&softc->ctl_lock);
2948			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2949			       __func__, (uintmax_t)delete_desc->lun_id);
2950			retval = EINVAL;
2951			break;
2952		}
2953		mtx_lock(&lun->lun_lock);
2954		mtx_unlock(&softc->ctl_lock);
2955		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2956			if (desc->serial != delete_desc->serial)
2957				continue;
2958
2959			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2960				      links);
2961			free(desc, M_CTL);
2962			delete_done = 1;
2963		}
2964		mtx_unlock(&lun->lun_lock);
2965		if (delete_done == 0) {
2966			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2967			       "error serial %ju on LUN %u\n", __func__,
2968			       delete_desc->serial, delete_desc->lun_id);
2969			retval = EINVAL;
2970			break;
2971		}
2972		break;
2973	}
2974	case CTL_DUMP_STRUCTS: {
2975		int i, j, k, idx;
2976		struct ctl_port *port;
2977		struct ctl_frontend *fe;
2978
2979		mtx_lock(&softc->ctl_lock);
2980		printf("CTL Persistent Reservation information start:\n");
2981		for (i = 0; i < CTL_MAX_LUNS; i++) {
2982			struct ctl_lun *lun;
2983
2984			lun = softc->ctl_luns[i];
2985
2986			if ((lun == NULL)
2987			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2988				continue;
2989
2990			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2991				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2992					idx = j * CTL_MAX_INIT_PER_PORT + k;
2993					if (lun->pr_keys[idx] == 0)
2994						continue;
2995					printf("  LUN %d port %d iid %d key "
2996					       "%#jx\n", i, j, k,
2997					       (uintmax_t)lun->pr_keys[idx]);
2998				}
2999			}
3000		}
3001		printf("CTL Persistent Reservation information end\n");
3002		printf("CTL Ports:\n");
3003		STAILQ_FOREACH(port, &softc->port_list, links) {
3004			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3005			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3006			       port->frontend->name, port->port_type,
3007			       port->physical_port, port->virtual_port,
3008			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3009			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3010				if (port->wwpn_iid[j].in_use == 0 &&
3011				    port->wwpn_iid[j].wwpn == 0 &&
3012				    port->wwpn_iid[j].name == NULL)
3013					continue;
3014
3015				printf("    iid %u use %d WWPN %#jx '%s'\n",
3016				    j, port->wwpn_iid[j].in_use,
3017				    (uintmax_t)port->wwpn_iid[j].wwpn,
3018				    port->wwpn_iid[j].name);
3019			}
3020		}
3021		printf("CTL Port information end\n");
3022		mtx_unlock(&softc->ctl_lock);
3023		/*
3024		 * XXX KDM calling this without a lock.  We'd likely want
3025		 * to drop the lock before calling the frontend's dump
3026		 * routine anyway.
3027		 */
3028		printf("CTL Frontends:\n");
3029		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3030			printf("  Frontend '%s'\n", fe->name);
3031			if (fe->fe_dump != NULL)
3032				fe->fe_dump();
3033		}
3034		printf("CTL Frontend information end\n");
3035		break;
3036	}
3037	case CTL_LUN_REQ: {
3038		struct ctl_lun_req *lun_req;
3039		struct ctl_backend_driver *backend;
3040
3041		lun_req = (struct ctl_lun_req *)addr;
3042
3043		backend = ctl_backend_find(lun_req->backend);
3044		if (backend == NULL) {
3045			lun_req->status = CTL_LUN_ERROR;
3046			snprintf(lun_req->error_str,
3047				 sizeof(lun_req->error_str),
3048				 "Backend \"%s\" not found.",
3049				 lun_req->backend);
3050			break;
3051		}
3052		if (lun_req->num_be_args > 0) {
3053			lun_req->kern_be_args = ctl_copyin_args(
3054				lun_req->num_be_args,
3055				lun_req->be_args,
3056				lun_req->error_str,
3057				sizeof(lun_req->error_str));
3058			if (lun_req->kern_be_args == NULL) {
3059				lun_req->status = CTL_LUN_ERROR;
3060				break;
3061			}
3062		}
3063
3064		retval = backend->ioctl(dev, cmd, addr, flag, td);
3065
3066		if (lun_req->num_be_args > 0) {
3067			ctl_copyout_args(lun_req->num_be_args,
3068				      lun_req->kern_be_args);
3069			ctl_free_args(lun_req->num_be_args,
3070				      lun_req->kern_be_args);
3071		}
3072		break;
3073	}
3074	case CTL_LUN_LIST: {
3075		struct sbuf *sb;
3076		struct ctl_lun *lun;
3077		struct ctl_lun_list *list;
3078		struct ctl_option *opt;
3079
3080		list = (struct ctl_lun_list *)addr;
3081
3082		/*
3083		 * Allocate a fixed length sbuf here, based on the length
3084		 * of the user's buffer.  We could allocate an auto-extending
3085		 * buffer, and then tell the user how much larger our
3086		 * amount of data is than his buffer, but that presents
3087		 * some problems:
3088		 *
3089		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3090		 *     we can't hold a lock while calling them with an
3091		 *     auto-extending buffer.
3092 		 *
3093		 * 2.  There is not currently a LUN reference counting
3094		 *     mechanism, outside of outstanding transactions on
3095		 *     the LUN's OOA queue.  So a LUN could go away on us
3096		 *     while we're getting the LUN number, backend-specific
3097		 *     information, etc.  Thus, given the way things
3098		 *     currently work, we need to hold the CTL lock while
3099		 *     grabbing LUN information.
3100		 *
3101		 * So, from the user's standpoint, the best thing to do is
3102		 * allocate what he thinks is a reasonable buffer length,
3103		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3104		 * double the buffer length and try again.  (And repeat
3105		 * that until he succeeds.)
3106		 */
3107		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3108		if (sb == NULL) {
3109			list->status = CTL_LUN_LIST_ERROR;
3110			snprintf(list->error_str, sizeof(list->error_str),
3111				 "Unable to allocate %d bytes for LUN list",
3112				 list->alloc_len);
3113			break;
3114		}
3115
3116		sbuf_printf(sb, "<ctllunlist>\n");
3117
3118		mtx_lock(&softc->ctl_lock);
3119		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3120			mtx_lock(&lun->lun_lock);
3121			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3122					     (uintmax_t)lun->lun);
3123
3124			/*
3125			 * Bail out as soon as we see that we've overfilled
3126			 * the buffer.
3127			 */
3128			if (retval != 0)
3129				break;
3130
3131			retval = sbuf_printf(sb, "\t<backend_type>%s"
3132					     "</backend_type>\n",
3133					     (lun->backend == NULL) ?  "none" :
3134					     lun->backend->name);
3135
3136			if (retval != 0)
3137				break;
3138
3139			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3140					     lun->be_lun->lun_type);
3141
3142			if (retval != 0)
3143				break;
3144
3145			if (lun->backend == NULL) {
3146				retval = sbuf_printf(sb, "</lun>\n");
3147				if (retval != 0)
3148					break;
3149				continue;
3150			}
3151
3152			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3153					     (lun->be_lun->maxlba > 0) ?
3154					     lun->be_lun->maxlba + 1 : 0);
3155
3156			if (retval != 0)
3157				break;
3158
3159			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3160					     lun->be_lun->blocksize);
3161
3162			if (retval != 0)
3163				break;
3164
3165			retval = sbuf_printf(sb, "\t<serial_number>");
3166
3167			if (retval != 0)
3168				break;
3169
3170			retval = ctl_sbuf_printf_esc(sb,
3171						     lun->be_lun->serial_num);
3172
3173			if (retval != 0)
3174				break;
3175
3176			retval = sbuf_printf(sb, "</serial_number>\n");
3177
3178			if (retval != 0)
3179				break;
3180
3181			retval = sbuf_printf(sb, "\t<device_id>");
3182
3183			if (retval != 0)
3184				break;
3185
3186			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3187
3188			if (retval != 0)
3189				break;
3190
3191			retval = sbuf_printf(sb, "</device_id>\n");
3192
3193			if (retval != 0)
3194				break;
3195
3196			if (lun->backend->lun_info != NULL) {
3197				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3198				if (retval != 0)
3199					break;
3200			}
3201			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3202				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3203				    opt->name, opt->value, opt->name);
3204				if (retval != 0)
3205					break;
3206			}
3207
3208			retval = sbuf_printf(sb, "</lun>\n");
3209
3210			if (retval != 0)
3211				break;
3212			mtx_unlock(&lun->lun_lock);
3213		}
3214		if (lun != NULL)
3215			mtx_unlock(&lun->lun_lock);
3216		mtx_unlock(&softc->ctl_lock);
3217
3218		if ((retval != 0)
3219		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3220			retval = 0;
3221			sbuf_delete(sb);
3222			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3223			snprintf(list->error_str, sizeof(list->error_str),
3224				 "Out of space, %d bytes is too small",
3225				 list->alloc_len);
3226			break;
3227		}
3228
3229		sbuf_finish(sb);
3230
3231		retval = copyout(sbuf_data(sb), list->lun_xml,
3232				 sbuf_len(sb) + 1);
3233
3234		list->fill_len = sbuf_len(sb) + 1;
3235		list->status = CTL_LUN_LIST_OK;
3236		sbuf_delete(sb);
3237		break;
3238	}
3239	case CTL_ISCSI: {
3240		struct ctl_iscsi *ci;
3241		struct ctl_frontend *fe;
3242
3243		ci = (struct ctl_iscsi *)addr;
3244
3245		fe = ctl_frontend_find("iscsi");
3246		if (fe == NULL) {
3247			ci->status = CTL_ISCSI_ERROR;
3248			snprintf(ci->error_str, sizeof(ci->error_str),
3249			    "Frontend \"iscsi\" not found.");
3250			break;
3251		}
3252
3253		retval = fe->ioctl(dev, cmd, addr, flag, td);
3254		break;
3255	}
3256	case CTL_PORT_REQ: {
3257		struct ctl_req *req;
3258		struct ctl_frontend *fe;
3259
3260		req = (struct ctl_req *)addr;
3261
3262		fe = ctl_frontend_find(req->driver);
3263		if (fe == NULL) {
3264			req->status = CTL_LUN_ERROR;
3265			snprintf(req->error_str, sizeof(req->error_str),
3266			    "Frontend \"%s\" not found.", req->driver);
3267			break;
3268		}
3269		if (req->num_args > 0) {
3270			req->kern_args = ctl_copyin_args(req->num_args,
3271			    req->args, req->error_str, sizeof(req->error_str));
3272			if (req->kern_args == NULL) {
3273				req->status = CTL_LUN_ERROR;
3274				break;
3275			}
3276		}
3277
3278		retval = fe->ioctl(dev, cmd, addr, flag, td);
3279
3280		if (req->num_args > 0) {
3281			ctl_copyout_args(req->num_args, req->kern_args);
3282			ctl_free_args(req->num_args, req->kern_args);
3283		}
3284		break;
3285	}
3286	case CTL_PORT_LIST: {
3287		struct sbuf *sb;
3288		struct ctl_port *port;
3289		struct ctl_lun_list *list;
3290		struct ctl_option *opt;
3291
3292		list = (struct ctl_lun_list *)addr;
3293
3294		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3295		if (sb == NULL) {
3296			list->status = CTL_LUN_LIST_ERROR;
3297			snprintf(list->error_str, sizeof(list->error_str),
3298				 "Unable to allocate %d bytes for LUN list",
3299				 list->alloc_len);
3300			break;
3301		}
3302
3303		sbuf_printf(sb, "<ctlportlist>\n");
3304
3305		mtx_lock(&softc->ctl_lock);
3306		STAILQ_FOREACH(port, &softc->port_list, links) {
3307			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3308					     (uintmax_t)port->targ_port);
3309
3310			/*
3311			 * Bail out as soon as we see that we've overfilled
3312			 * the buffer.
3313			 */
3314			if (retval != 0)
3315				break;
3316
3317			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3318			    "</frontend_type>\n", port->frontend->name);
3319			if (retval != 0)
3320				break;
3321
3322			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3323					     port->port_type);
3324			if (retval != 0)
3325				break;
3326
3327			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3328			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3329			if (retval != 0)
3330				break;
3331
3332			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3333			    port->port_name);
3334			if (retval != 0)
3335				break;
3336
3337			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3338			    port->physical_port);
3339			if (retval != 0)
3340				break;
3341
3342			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3343			    port->virtual_port);
3344			if (retval != 0)
3345				break;
3346
3347			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3348			    (uintmax_t)port->wwnn);
3349			if (retval != 0)
3350				break;
3351
3352			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3353			    (uintmax_t)port->wwpn);
3354			if (retval != 0)
3355				break;
3356
3357			if (port->port_info != NULL) {
3358				retval = port->port_info(port->onoff_arg, sb);
3359				if (retval != 0)
3360					break;
3361			}
3362			STAILQ_FOREACH(opt, &port->options, links) {
3363				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3364				    opt->name, opt->value, opt->name);
3365				if (retval != 0)
3366					break;
3367			}
3368
3369			retval = sbuf_printf(sb, "</targ_port>\n");
3370			if (retval != 0)
3371				break;
3372		}
3373		mtx_unlock(&softc->ctl_lock);
3374
3375		if ((retval != 0)
3376		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3377			retval = 0;
3378			sbuf_delete(sb);
3379			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3380			snprintf(list->error_str, sizeof(list->error_str),
3381				 "Out of space, %d bytes is too small",
3382				 list->alloc_len);
3383			break;
3384		}
3385
3386		sbuf_finish(sb);
3387
3388		retval = copyout(sbuf_data(sb), list->lun_xml,
3389				 sbuf_len(sb) + 1);
3390
3391		list->fill_len = sbuf_len(sb) + 1;
3392		list->status = CTL_LUN_LIST_OK;
3393		sbuf_delete(sb);
3394		break;
3395	}
3396	default: {
3397		/* XXX KDM should we fix this? */
3398#if 0
3399		struct ctl_backend_driver *backend;
3400		unsigned int type;
3401		int found;
3402
3403		found = 0;
3404
3405		/*
3406		 * We encode the backend type as the ioctl type for backend
3407		 * ioctls.  So parse it out here, and then search for a
3408		 * backend of this type.
3409		 */
3410		type = _IOC_TYPE(cmd);
3411
3412		STAILQ_FOREACH(backend, &softc->be_list, links) {
3413			if (backend->type == type) {
3414				found = 1;
3415				break;
3416			}
3417		}
3418		if (found == 0) {
3419			printf("ctl: unknown ioctl command %#lx or backend "
3420			       "%d\n", cmd, type);
3421			retval = EINVAL;
3422			break;
3423		}
3424		retval = backend->ioctl(dev, cmd, addr, flag, td);
3425#endif
3426		retval = ENOTTY;
3427		break;
3428	}
3429	}
3430	return (retval);
3431}
3432
3433uint32_t
3434ctl_get_initindex(struct ctl_nexus *nexus)
3435{
3436	if (nexus->targ_port < CTL_MAX_PORTS)
3437		return (nexus->initid.id +
3438			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3439	else
3440		return (nexus->initid.id +
3441		       ((nexus->targ_port - CTL_MAX_PORTS) *
3442			CTL_MAX_INIT_PER_PORT));
3443}
3444
3445uint32_t
3446ctl_get_resindex(struct ctl_nexus *nexus)
3447{
3448	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3449}
3450
3451uint32_t
3452ctl_port_idx(int port_num)
3453{
3454	if (port_num < CTL_MAX_PORTS)
3455		return(port_num);
3456	else
3457		return(port_num - CTL_MAX_PORTS);
3458}
3459
3460static uint32_t
3461ctl_map_lun(int port_num, uint32_t lun_id)
3462{
3463	struct ctl_port *port;
3464
3465	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3466	if (port == NULL)
3467		return (UINT32_MAX);
3468	if (port->lun_map == NULL)
3469		return (lun_id);
3470	return (port->lun_map(port->targ_lun_arg, lun_id));
3471}
3472
3473static uint32_t
3474ctl_map_lun_back(int port_num, uint32_t lun_id)
3475{
3476	struct ctl_port *port;
3477	uint32_t i;
3478
3479	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3480	if (port->lun_map == NULL)
3481		return (lun_id);
3482	for (i = 0; i < CTL_MAX_LUNS; i++) {
3483		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3484			return (i);
3485	}
3486	return (UINT32_MAX);
3487}
3488
3489/*
3490 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3491 * that are a power of 2.
3492 */
3493int
3494ctl_ffz(uint32_t *mask, uint32_t size)
3495{
3496	uint32_t num_chunks, num_pieces;
3497	int i, j;
3498
3499	num_chunks = (size >> 5);
3500	if (num_chunks == 0)
3501		num_chunks++;
3502	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3503
3504	for (i = 0; i < num_chunks; i++) {
3505		for (j = 0; j < num_pieces; j++) {
3506			if ((mask[i] & (1 << j)) == 0)
3507				return ((i << 5) + j);
3508		}
3509	}
3510
3511	return (-1);
3512}
3513
3514int
3515ctl_set_mask(uint32_t *mask, uint32_t bit)
3516{
3517	uint32_t chunk, piece;
3518
3519	chunk = bit >> 5;
3520	piece = bit % (sizeof(uint32_t) * 8);
3521
3522	if ((mask[chunk] & (1 << piece)) != 0)
3523		return (-1);
3524	else
3525		mask[chunk] |= (1 << piece);
3526
3527	return (0);
3528}
3529
3530int
3531ctl_clear_mask(uint32_t *mask, uint32_t bit)
3532{
3533	uint32_t chunk, piece;
3534
3535	chunk = bit >> 5;
3536	piece = bit % (sizeof(uint32_t) * 8);
3537
3538	if ((mask[chunk] & (1 << piece)) == 0)
3539		return (-1);
3540	else
3541		mask[chunk] &= ~(1 << piece);
3542
3543	return (0);
3544}
3545
3546int
3547ctl_is_set(uint32_t *mask, uint32_t bit)
3548{
3549	uint32_t chunk, piece;
3550
3551	chunk = bit >> 5;
3552	piece = bit % (sizeof(uint32_t) * 8);
3553
3554	if ((mask[chunk] & (1 << piece)) == 0)
3555		return (0);
3556	else
3557		return (1);
3558}
3559
3560#ifdef unused
3561/*
3562 * The bus, target and lun are optional, they can be filled in later.
3563 * can_wait is used to determine whether we can wait on the malloc or not.
3564 */
3565union ctl_io*
3566ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3567	      uint32_t targ_lun, int can_wait)
3568{
3569	union ctl_io *io;
3570
3571	if (can_wait)
3572		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3573	else
3574		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3575
3576	if (io != NULL) {
3577		io->io_hdr.io_type = io_type;
3578		io->io_hdr.targ_port = targ_port;
3579		/*
3580		 * XXX KDM this needs to change/go away.  We need to move
3581		 * to a preallocated pool of ctl_scsiio structures.
3582		 */
3583		io->io_hdr.nexus.targ_target.id = targ_target;
3584		io->io_hdr.nexus.targ_lun = targ_lun;
3585	}
3586
3587	return (io);
3588}
3589
3590void
3591ctl_kfree_io(union ctl_io *io)
3592{
3593	free(io, M_CTL);
3594}
3595#endif /* unused */
3596
3597/*
3598 * ctl_softc, pool_type, total_ctl_io are passed in.
3599 * npool is passed out.
3600 */
3601int
3602ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3603		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3604{
3605	uint32_t i;
3606	union ctl_io *cur_io, *next_io;
3607	struct ctl_io_pool *pool;
3608	int retval;
3609
3610	retval = 0;
3611
3612	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3613					    M_NOWAIT | M_ZERO);
3614	if (pool == NULL) {
3615		retval = ENOMEM;
3616		goto bailout;
3617	}
3618
3619	pool->type = pool_type;
3620	pool->ctl_softc = ctl_softc;
3621
3622	mtx_lock(&ctl_softc->pool_lock);
3623	pool->id = ctl_softc->cur_pool_id++;
3624	mtx_unlock(&ctl_softc->pool_lock);
3625
3626	pool->flags = CTL_POOL_FLAG_NONE;
3627	pool->refcount = 1;		/* Reference for validity. */
3628	STAILQ_INIT(&pool->free_queue);
3629
3630	/*
3631	 * XXX KDM other options here:
3632	 * - allocate a page at a time
3633	 * - allocate one big chunk of memory.
3634	 * Page allocation might work well, but would take a little more
3635	 * tracking.
3636	 */
3637	for (i = 0; i < total_ctl_io; i++) {
3638		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3639						M_NOWAIT);
3640		if (cur_io == NULL) {
3641			retval = ENOMEM;
3642			break;
3643		}
3644		cur_io->io_hdr.pool = pool;
3645		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3646		pool->total_ctl_io++;
3647		pool->free_ctl_io++;
3648	}
3649
3650	if (retval != 0) {
3651		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3652		     cur_io != NULL; cur_io = next_io) {
3653			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3654							      links);
3655			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3656				      ctl_io_hdr, links);
3657			free(cur_io, M_CTLIO);
3658		}
3659
3660		free(pool, M_CTL);
3661		goto bailout;
3662	}
3663	mtx_lock(&ctl_softc->pool_lock);
3664	ctl_softc->num_pools++;
3665	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3666	/*
3667	 * Increment our usage count if this is an external consumer, so we
3668	 * can't get unloaded until the external consumer (most likely a
3669	 * FETD) unloads and frees his pool.
3670	 *
3671	 * XXX KDM will this increment the caller's module use count, or
3672	 * mine?
3673	 */
3674#if 0
3675	if ((pool_type != CTL_POOL_EMERGENCY)
3676	 && (pool_type != CTL_POOL_INTERNAL)
3677	 && (pool_type != CTL_POOL_4OTHERSC))
3678		MOD_INC_USE_COUNT;
3679#endif
3680
3681	mtx_unlock(&ctl_softc->pool_lock);
3682
3683	*npool = pool;
3684
3685bailout:
3686
3687	return (retval);
3688}
3689
3690static int
3691ctl_pool_acquire(struct ctl_io_pool *pool)
3692{
3693
3694	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3695
3696	if (pool->flags & CTL_POOL_FLAG_INVALID)
3697		return (EINVAL);
3698
3699	pool->refcount++;
3700
3701	return (0);
3702}
3703
3704static void
3705ctl_pool_release(struct ctl_io_pool *pool)
3706{
3707	struct ctl_softc *ctl_softc = pool->ctl_softc;
3708	union ctl_io *io;
3709
3710	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3711
3712	if (--pool->refcount != 0)
3713		return;
3714
3715	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3716		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3717			      links);
3718		free(io, M_CTLIO);
3719	}
3720
3721	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3722	ctl_softc->num_pools--;
3723
3724	/*
3725	 * XXX KDM will this decrement the caller's usage count or mine?
3726	 */
3727#if 0
3728	if ((pool->type != CTL_POOL_EMERGENCY)
3729	 && (pool->type != CTL_POOL_INTERNAL)
3730	 && (pool->type != CTL_POOL_4OTHERSC))
3731		MOD_DEC_USE_COUNT;
3732#endif
3733
3734	free(pool, M_CTL);
3735}
3736
3737void
3738ctl_pool_free(struct ctl_io_pool *pool)
3739{
3740	struct ctl_softc *ctl_softc;
3741
3742	if (pool == NULL)
3743		return;
3744
3745	ctl_softc = pool->ctl_softc;
3746	mtx_lock(&ctl_softc->pool_lock);
3747	pool->flags |= CTL_POOL_FLAG_INVALID;
3748	ctl_pool_release(pool);
3749	mtx_unlock(&ctl_softc->pool_lock);
3750}
3751
3752/*
3753 * This routine does not block (except for spinlocks of course).
3754 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3755 * possible.
3756 */
3757union ctl_io *
3758ctl_alloc_io(void *pool_ref)
3759{
3760	union ctl_io *io;
3761	struct ctl_softc *ctl_softc;
3762	struct ctl_io_pool *pool, *npool;
3763	struct ctl_io_pool *emergency_pool;
3764
3765	pool = (struct ctl_io_pool *)pool_ref;
3766
3767	if (pool == NULL) {
3768		printf("%s: pool is NULL\n", __func__);
3769		return (NULL);
3770	}
3771
3772	emergency_pool = NULL;
3773
3774	ctl_softc = pool->ctl_softc;
3775
3776	mtx_lock(&ctl_softc->pool_lock);
3777	/*
3778	 * First, try to get the io structure from the user's pool.
3779	 */
3780	if (ctl_pool_acquire(pool) == 0) {
3781		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3782		if (io != NULL) {
3783			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3784			pool->total_allocated++;
3785			pool->free_ctl_io--;
3786			mtx_unlock(&ctl_softc->pool_lock);
3787			return (io);
3788		} else
3789			ctl_pool_release(pool);
3790	}
3791	/*
3792	 * If he doesn't have any io structures left, search for an
3793	 * emergency pool and grab one from there.
3794	 */
3795	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3796		if (npool->type != CTL_POOL_EMERGENCY)
3797			continue;
3798
3799		if (ctl_pool_acquire(npool) != 0)
3800			continue;
3801
3802		emergency_pool = npool;
3803
3804		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3805		if (io != NULL) {
3806			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3807			npool->total_allocated++;
3808			npool->free_ctl_io--;
3809			mtx_unlock(&ctl_softc->pool_lock);
3810			return (io);
3811		} else
3812			ctl_pool_release(npool);
3813	}
3814
3815	/* Drop the spinlock before we malloc */
3816	mtx_unlock(&ctl_softc->pool_lock);
3817
3818	/*
3819	 * The emergency pool (if it exists) didn't have one, so try an
3820	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3821	 */
3822	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3823	if (io != NULL) {
3824		/*
3825		 * If the emergency pool exists but is empty, add this
3826		 * ctl_io to its list when it gets freed.
3827		 */
3828		if (emergency_pool != NULL) {
3829			mtx_lock(&ctl_softc->pool_lock);
3830			if (ctl_pool_acquire(emergency_pool) == 0) {
3831				io->io_hdr.pool = emergency_pool;
3832				emergency_pool->total_ctl_io++;
3833				/*
3834				 * Need to bump this, otherwise
3835				 * total_allocated and total_freed won't
3836				 * match when we no longer have anything
3837				 * outstanding.
3838				 */
3839				emergency_pool->total_allocated++;
3840			}
3841			mtx_unlock(&ctl_softc->pool_lock);
3842		} else
3843			io->io_hdr.pool = NULL;
3844	}
3845
3846	return (io);
3847}
3848
3849void
3850ctl_free_io(union ctl_io *io)
3851{
3852	if (io == NULL)
3853		return;
3854
3855	/*
3856	 * If this ctl_io has a pool, return it to that pool.
3857	 */
3858	if (io->io_hdr.pool != NULL) {
3859		struct ctl_io_pool *pool;
3860
3861		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3862		mtx_lock(&pool->ctl_softc->pool_lock);
3863		io->io_hdr.io_type = 0xff;
3864		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3865		pool->total_freed++;
3866		pool->free_ctl_io++;
3867		ctl_pool_release(pool);
3868		mtx_unlock(&pool->ctl_softc->pool_lock);
3869	} else {
3870		/*
3871		 * Otherwise, just free it.  We probably malloced it and
3872		 * the emergency pool wasn't available.
3873		 */
3874		free(io, M_CTLIO);
3875	}
3876
3877}
3878
3879void
3880ctl_zero_io(union ctl_io *io)
3881{
3882	void *pool_ref;
3883
3884	if (io == NULL)
3885		return;
3886
3887	/*
3888	 * May need to preserve linked list pointers at some point too.
3889	 */
3890	pool_ref = io->io_hdr.pool;
3891
3892	memset(io, 0, sizeof(*io));
3893
3894	io->io_hdr.pool = pool_ref;
3895}
3896
3897/*
3898 * This routine is currently used for internal copies of ctl_ios that need
3899 * to persist for some reason after we've already returned status to the
3900 * FETD.  (Thus the flag set.)
3901 *
3902 * XXX XXX
3903 * Note that this makes a blind copy of all fields in the ctl_io, except
3904 * for the pool reference.  This includes any memory that has been
3905 * allocated!  That memory will no longer be valid after done has been
3906 * called, so this would be VERY DANGEROUS for command that actually does
3907 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3908 * start and stop commands, which don't transfer any data, so this is not a
3909 * problem.  If it is used for anything else, the caller would also need to
3910 * allocate data buffer space and this routine would need to be modified to
3911 * copy the data buffer(s) as well.
3912 */
3913void
3914ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3915{
3916	void *pool_ref;
3917
3918	if ((src == NULL)
3919	 || (dest == NULL))
3920		return;
3921
3922	/*
3923	 * May need to preserve linked list pointers at some point too.
3924	 */
3925	pool_ref = dest->io_hdr.pool;
3926
3927	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3928
3929	dest->io_hdr.pool = pool_ref;
3930	/*
3931	 * We need to know that this is an internal copy, and doesn't need
3932	 * to get passed back to the FETD that allocated it.
3933	 */
3934	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3935}
3936
3937#ifdef NEEDTOPORT
3938static void
3939ctl_update_power_subpage(struct copan_power_subpage *page)
3940{
3941	int num_luns, num_partitions, config_type;
3942	struct ctl_softc *softc;
3943	cs_BOOL_t aor_present, shelf_50pct_power;
3944	cs_raidset_personality_t rs_type;
3945	int max_active_luns;
3946
3947	softc = control_softc;
3948
3949	/* subtract out the processor LUN */
3950	num_luns = softc->num_luns - 1;
3951	/*
3952	 * Default to 7 LUNs active, which was the only number we allowed
3953	 * in the past.
3954	 */
3955	max_active_luns = 7;
3956
3957	num_partitions = config_GetRsPartitionInfo();
3958	config_type = config_GetConfigType();
3959	shelf_50pct_power = config_GetShelfPowerMode();
3960	aor_present = config_IsAorRsPresent();
3961
3962	rs_type = ddb_GetRsRaidType(1);
3963	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3964	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3965		EPRINT(0, "Unsupported RS type %d!", rs_type);
3966	}
3967
3968
3969	page->total_luns = num_luns;
3970
3971	switch (config_type) {
3972	case 40:
3973		/*
3974		 * In a 40 drive configuration, it doesn't matter what DC
3975		 * cards we have, whether we have AOR enabled or not,
3976		 * partitioning or not, or what type of RAIDset we have.
3977		 * In that scenario, we can power up every LUN we present
3978		 * to the user.
3979		 */
3980		max_active_luns = num_luns;
3981
3982		break;
3983	case 64:
3984		if (shelf_50pct_power == CS_FALSE) {
3985			/* 25% power */
3986			if (aor_present == CS_TRUE) {
3987				if (rs_type ==
3988				     CS_RAIDSET_PERSONALITY_RAID5) {
3989					max_active_luns = 7;
3990				} else if (rs_type ==
3991					 CS_RAIDSET_PERSONALITY_RAID1){
3992					max_active_luns = 14;
3993				} else {
3994					/* XXX KDM now what?? */
3995				}
3996			} else {
3997				if (rs_type ==
3998				     CS_RAIDSET_PERSONALITY_RAID5) {
3999					max_active_luns = 8;
4000				} else if (rs_type ==
4001					 CS_RAIDSET_PERSONALITY_RAID1){
4002					max_active_luns = 16;
4003				} else {
4004					/* XXX KDM now what?? */
4005				}
4006			}
4007		} else {
4008			/* 50% power */
4009			/*
4010			 * With 50% power in a 64 drive configuration, we
4011			 * can power all LUNs we present.
4012			 */
4013			max_active_luns = num_luns;
4014		}
4015		break;
4016	case 112:
4017		if (shelf_50pct_power == CS_FALSE) {
4018			/* 25% power */
4019			if (aor_present == CS_TRUE) {
4020				if (rs_type ==
4021				     CS_RAIDSET_PERSONALITY_RAID5) {
4022					max_active_luns = 7;
4023				} else if (rs_type ==
4024					 CS_RAIDSET_PERSONALITY_RAID1){
4025					max_active_luns = 14;
4026				} else {
4027					/* XXX KDM now what?? */
4028				}
4029			} else {
4030				if (rs_type ==
4031				     CS_RAIDSET_PERSONALITY_RAID5) {
4032					max_active_luns = 8;
4033				} else if (rs_type ==
4034					 CS_RAIDSET_PERSONALITY_RAID1){
4035					max_active_luns = 16;
4036				} else {
4037					/* XXX KDM now what?? */
4038				}
4039			}
4040		} else {
4041			/* 50% power */
4042			if (aor_present == CS_TRUE) {
4043				if (rs_type ==
4044				     CS_RAIDSET_PERSONALITY_RAID5) {
4045					max_active_luns = 14;
4046				} else if (rs_type ==
4047					 CS_RAIDSET_PERSONALITY_RAID1){
4048					/*
4049					 * We're assuming here that disk
4050					 * caching is enabled, and so we're
4051					 * able to power up half of each
4052					 * LUN, and cache all writes.
4053					 */
4054					max_active_luns = num_luns;
4055				} else {
4056					/* XXX KDM now what?? */
4057				}
4058			} else {
4059				if (rs_type ==
4060				     CS_RAIDSET_PERSONALITY_RAID5) {
4061					max_active_luns = 15;
4062				} else if (rs_type ==
4063					 CS_RAIDSET_PERSONALITY_RAID1){
4064					max_active_luns = 30;
4065				} else {
4066					/* XXX KDM now what?? */
4067				}
4068			}
4069		}
4070		break;
4071	default:
4072		/*
4073		 * In this case, we have an unknown configuration, so we
4074		 * just use the default from above.
4075		 */
4076		break;
4077	}
4078
4079	page->max_active_luns = max_active_luns;
4080#if 0
4081	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4082	       page->total_luns, page->max_active_luns);
4083#endif
4084}
4085#endif /* NEEDTOPORT */
4086
4087/*
4088 * This routine could be used in the future to load default and/or saved
4089 * mode page parameters for a particuar lun.
4090 */
4091static int
4092ctl_init_page_index(struct ctl_lun *lun)
4093{
4094	int i;
4095	struct ctl_page_index *page_index;
4096	struct ctl_softc *softc;
4097	const char *value;
4098
4099	memcpy(&lun->mode_pages.index, page_index_template,
4100	       sizeof(page_index_template));
4101
4102	softc = lun->ctl_softc;
4103
4104	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4105
4106		page_index = &lun->mode_pages.index[i];
4107		/*
4108		 * If this is a disk-only mode page, there's no point in
4109		 * setting it up.  For some pages, we have to have some
4110		 * basic information about the disk in order to calculate the
4111		 * mode page data.
4112		 */
4113		if ((lun->be_lun->lun_type != T_DIRECT)
4114		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4115			continue;
4116
4117		switch (page_index->page_code & SMPH_PC_MASK) {
4118		case SMS_FORMAT_DEVICE_PAGE: {
4119			struct scsi_format_page *format_page;
4120
4121			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4122				panic("subpage is incorrect!");
4123
4124			/*
4125			 * Sectors per track are set above.  Bytes per
4126			 * sector need to be set here on a per-LUN basis.
4127			 */
4128			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4129			       &format_page_default,
4130			       sizeof(format_page_default));
4131			memcpy(&lun->mode_pages.format_page[
4132			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4133			       sizeof(format_page_changeable));
4134			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4135			       &format_page_default,
4136			       sizeof(format_page_default));
4137			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4138			       &format_page_default,
4139			       sizeof(format_page_default));
4140
4141			format_page = &lun->mode_pages.format_page[
4142				CTL_PAGE_CURRENT];
4143			scsi_ulto2b(lun->be_lun->blocksize,
4144				    format_page->bytes_per_sector);
4145
4146			format_page = &lun->mode_pages.format_page[
4147				CTL_PAGE_DEFAULT];
4148			scsi_ulto2b(lun->be_lun->blocksize,
4149				    format_page->bytes_per_sector);
4150
4151			format_page = &lun->mode_pages.format_page[
4152				CTL_PAGE_SAVED];
4153			scsi_ulto2b(lun->be_lun->blocksize,
4154				    format_page->bytes_per_sector);
4155
4156			page_index->page_data =
4157				(uint8_t *)lun->mode_pages.format_page;
4158			break;
4159		}
4160		case SMS_RIGID_DISK_PAGE: {
4161			struct scsi_rigid_disk_page *rigid_disk_page;
4162			uint32_t sectors_per_cylinder;
4163			uint64_t cylinders;
4164#ifndef	__XSCALE__
4165			int shift;
4166#endif /* !__XSCALE__ */
4167
4168			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4169				panic("invalid subpage value %d",
4170				      page_index->subpage);
4171
4172			/*
4173			 * Rotation rate and sectors per track are set
4174			 * above.  We calculate the cylinders here based on
4175			 * capacity.  Due to the number of heads and
4176			 * sectors per track we're using, smaller arrays
4177			 * may turn out to have 0 cylinders.  Linux and
4178			 * FreeBSD don't pay attention to these mode pages
4179			 * to figure out capacity, but Solaris does.  It
4180			 * seems to deal with 0 cylinders just fine, and
4181			 * works out a fake geometry based on the capacity.
4182			 */
4183			memcpy(&lun->mode_pages.rigid_disk_page[
4184			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4185			       sizeof(rigid_disk_page_default));
4186			memcpy(&lun->mode_pages.rigid_disk_page[
4187			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4188			       sizeof(rigid_disk_page_changeable));
4189			memcpy(&lun->mode_pages.rigid_disk_page[
4190			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4191			       sizeof(rigid_disk_page_default));
4192			memcpy(&lun->mode_pages.rigid_disk_page[
4193			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4194			       sizeof(rigid_disk_page_default));
4195
4196			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4197				CTL_DEFAULT_HEADS;
4198
4199			/*
4200			 * The divide method here will be more accurate,
4201			 * probably, but results in floating point being
4202			 * used in the kernel on i386 (__udivdi3()).  On the
4203			 * XScale, though, __udivdi3() is implemented in
4204			 * software.
4205			 *
4206			 * The shift method for cylinder calculation is
4207			 * accurate if sectors_per_cylinder is a power of
4208			 * 2.  Otherwise it might be slightly off -- you
4209			 * might have a bit of a truncation problem.
4210			 */
4211#ifdef	__XSCALE__
4212			cylinders = (lun->be_lun->maxlba + 1) /
4213				sectors_per_cylinder;
4214#else
4215			for (shift = 31; shift > 0; shift--) {
4216				if (sectors_per_cylinder & (1 << shift))
4217					break;
4218			}
4219			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4220#endif
4221
4222			/*
4223			 * We've basically got 3 bytes, or 24 bits for the
4224			 * cylinder size in the mode page.  If we're over,
4225			 * just round down to 2^24.
4226			 */
4227			if (cylinders > 0xffffff)
4228				cylinders = 0xffffff;
4229
4230			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4231				CTL_PAGE_CURRENT];
4232			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4233
4234			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4235				CTL_PAGE_DEFAULT];
4236			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4237
4238			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4239				CTL_PAGE_SAVED];
4240			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4241
4242			page_index->page_data =
4243				(uint8_t *)lun->mode_pages.rigid_disk_page;
4244			break;
4245		}
4246		case SMS_CACHING_PAGE: {
4247			struct scsi_caching_page *caching_page;
4248
4249			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4250				panic("invalid subpage value %d",
4251				      page_index->subpage);
4252			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4253			       &caching_page_default,
4254			       sizeof(caching_page_default));
4255			memcpy(&lun->mode_pages.caching_page[
4256			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4257			       sizeof(caching_page_changeable));
4258			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4259			       &caching_page_default,
4260			       sizeof(caching_page_default));
4261			caching_page = &lun->mode_pages.caching_page[
4262			    CTL_PAGE_SAVED];
4263			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4264			if (value != NULL && strcmp(value, "off") == 0)
4265				caching_page->flags1 &= ~SCP_WCE;
4266			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4267			if (value != NULL && strcmp(value, "off") == 0)
4268				caching_page->flags1 |= SCP_RCD;
4269			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4270			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4271			       sizeof(caching_page_default));
4272			page_index->page_data =
4273				(uint8_t *)lun->mode_pages.caching_page;
4274			break;
4275		}
4276		case SMS_CONTROL_MODE_PAGE: {
4277			struct scsi_control_page *control_page;
4278
4279			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4280				panic("invalid subpage value %d",
4281				      page_index->subpage);
4282
4283			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4284			       &control_page_default,
4285			       sizeof(control_page_default));
4286			memcpy(&lun->mode_pages.control_page[
4287			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4288			       sizeof(control_page_changeable));
4289			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4290			       &control_page_default,
4291			       sizeof(control_page_default));
4292			control_page = &lun->mode_pages.control_page[
4293			    CTL_PAGE_SAVED];
4294			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4295			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4296				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4297				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4298			}
4299			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4300			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4301			       sizeof(control_page_default));
4302			page_index->page_data =
4303				(uint8_t *)lun->mode_pages.control_page;
4304			break;
4305
4306		}
4307		case SMS_VENDOR_SPECIFIC_PAGE:{
4308			switch (page_index->subpage) {
4309			case PWR_SUBPAGE_CODE: {
4310				struct copan_power_subpage *current_page,
4311							   *saved_page;
4312
4313				memcpy(&lun->mode_pages.power_subpage[
4314				       CTL_PAGE_CURRENT],
4315				       &power_page_default,
4316				       sizeof(power_page_default));
4317				memcpy(&lun->mode_pages.power_subpage[
4318				       CTL_PAGE_CHANGEABLE],
4319				       &power_page_changeable,
4320				       sizeof(power_page_changeable));
4321				memcpy(&lun->mode_pages.power_subpage[
4322				       CTL_PAGE_DEFAULT],
4323				       &power_page_default,
4324				       sizeof(power_page_default));
4325				memcpy(&lun->mode_pages.power_subpage[
4326				       CTL_PAGE_SAVED],
4327				       &power_page_default,
4328				       sizeof(power_page_default));
4329				page_index->page_data =
4330				    (uint8_t *)lun->mode_pages.power_subpage;
4331
4332				current_page = (struct copan_power_subpage *)
4333					(page_index->page_data +
4334					 (page_index->page_len *
4335					  CTL_PAGE_CURRENT));
4336			        saved_page = (struct copan_power_subpage *)
4337				        (page_index->page_data +
4338					 (page_index->page_len *
4339					  CTL_PAGE_SAVED));
4340				break;
4341			}
4342			case APS_SUBPAGE_CODE: {
4343				struct copan_aps_subpage *current_page,
4344							 *saved_page;
4345
4346				// This gets set multiple times but
4347				// it should always be the same. It's
4348				// only done during init so who cares.
4349				index_to_aps_page = i;
4350
4351				memcpy(&lun->mode_pages.aps_subpage[
4352				       CTL_PAGE_CURRENT],
4353				       &aps_page_default,
4354				       sizeof(aps_page_default));
4355				memcpy(&lun->mode_pages.aps_subpage[
4356				       CTL_PAGE_CHANGEABLE],
4357				       &aps_page_changeable,
4358				       sizeof(aps_page_changeable));
4359				memcpy(&lun->mode_pages.aps_subpage[
4360				       CTL_PAGE_DEFAULT],
4361				       &aps_page_default,
4362				       sizeof(aps_page_default));
4363				memcpy(&lun->mode_pages.aps_subpage[
4364				       CTL_PAGE_SAVED],
4365				       &aps_page_default,
4366				       sizeof(aps_page_default));
4367				page_index->page_data =
4368					(uint8_t *)lun->mode_pages.aps_subpage;
4369
4370				current_page = (struct copan_aps_subpage *)
4371					(page_index->page_data +
4372					 (page_index->page_len *
4373					  CTL_PAGE_CURRENT));
4374				saved_page = (struct copan_aps_subpage *)
4375					(page_index->page_data +
4376					 (page_index->page_len *
4377					  CTL_PAGE_SAVED));
4378				break;
4379			}
4380			case DBGCNF_SUBPAGE_CODE: {
4381				struct copan_debugconf_subpage *current_page,
4382							       *saved_page;
4383
4384				memcpy(&lun->mode_pages.debugconf_subpage[
4385				       CTL_PAGE_CURRENT],
4386				       &debugconf_page_default,
4387				       sizeof(debugconf_page_default));
4388				memcpy(&lun->mode_pages.debugconf_subpage[
4389				       CTL_PAGE_CHANGEABLE],
4390				       &debugconf_page_changeable,
4391				       sizeof(debugconf_page_changeable));
4392				memcpy(&lun->mode_pages.debugconf_subpage[
4393				       CTL_PAGE_DEFAULT],
4394				       &debugconf_page_default,
4395				       sizeof(debugconf_page_default));
4396				memcpy(&lun->mode_pages.debugconf_subpage[
4397				       CTL_PAGE_SAVED],
4398				       &debugconf_page_default,
4399				       sizeof(debugconf_page_default));
4400				page_index->page_data =
4401					(uint8_t *)lun->mode_pages.debugconf_subpage;
4402
4403				current_page = (struct copan_debugconf_subpage *)
4404					(page_index->page_data +
4405					 (page_index->page_len *
4406					  CTL_PAGE_CURRENT));
4407				saved_page = (struct copan_debugconf_subpage *)
4408					(page_index->page_data +
4409					 (page_index->page_len *
4410					  CTL_PAGE_SAVED));
4411				break;
4412			}
4413			default:
4414				panic("invalid subpage value %d",
4415				      page_index->subpage);
4416				break;
4417			}
4418   			break;
4419		}
4420		default:
4421			panic("invalid page value %d",
4422			      page_index->page_code & SMPH_PC_MASK);
4423			break;
4424    	}
4425	}
4426
4427	return (CTL_RETVAL_COMPLETE);
4428}
4429
4430/*
4431 * LUN allocation.
4432 *
4433 * Requirements:
4434 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4435 *   wants us to allocate the LUN and he can block.
4436 * - ctl_softc is always set
4437 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4438 *
4439 * Returns 0 for success, non-zero (errno) for failure.
4440 */
4441static int
4442ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4443	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4444{
4445	struct ctl_lun *nlun, *lun;
4446	struct ctl_port *port;
4447	struct scsi_vpd_id_descriptor *desc;
4448	struct scsi_vpd_id_t10 *t10id;
4449	const char *eui, *naa, *scsiname, *vendor, *value;
4450	int lun_number, i, lun_malloced;
4451	int devidlen, idlen1, idlen2 = 0, len;
4452
4453	if (be_lun == NULL)
4454		return (EINVAL);
4455
4456	/*
4457	 * We currently only support Direct Access or Processor LUN types.
4458	 */
4459	switch (be_lun->lun_type) {
4460	case T_DIRECT:
4461		break;
4462	case T_PROCESSOR:
4463		break;
4464	case T_SEQUENTIAL:
4465	case T_CHANGER:
4466	default:
4467		be_lun->lun_config_status(be_lun->be_lun,
4468					  CTL_LUN_CONFIG_FAILURE);
4469		break;
4470	}
4471	if (ctl_lun == NULL) {
4472		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4473		lun_malloced = 1;
4474	} else {
4475		lun_malloced = 0;
4476		lun = ctl_lun;
4477	}
4478
4479	memset(lun, 0, sizeof(*lun));
4480	if (lun_malloced)
4481		lun->flags = CTL_LUN_MALLOCED;
4482
4483	/* Generate LUN ID. */
4484	devidlen = max(CTL_DEVID_MIN_LEN,
4485	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4486	idlen1 = sizeof(*t10id) + devidlen;
4487	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4488	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4489	if (scsiname != NULL) {
4490		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4491		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4492	}
4493	eui = ctl_get_opt(&be_lun->options, "eui");
4494	if (eui != NULL) {
4495		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4496	}
4497	naa = ctl_get_opt(&be_lun->options, "naa");
4498	if (naa != NULL) {
4499		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4500	}
4501	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4502	    M_CTL, M_WAITOK | M_ZERO);
4503	lun->lun_devid->len = len;
4504	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4505	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4506	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4507	desc->length = idlen1;
4508	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4509	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4510	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4511		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4512	} else {
4513		strncpy(t10id->vendor, vendor,
4514		    min(sizeof(t10id->vendor), strlen(vendor)));
4515	}
4516	strncpy((char *)t10id->vendor_spec_id,
4517	    (char *)be_lun->device_id, devidlen);
4518	if (scsiname != NULL) {
4519		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4520		    desc->length);
4521		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4522		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4523		    SVPD_ID_TYPE_SCSI_NAME;
4524		desc->length = idlen2;
4525		strlcpy(desc->identifier, scsiname, idlen2);
4526	}
4527	if (eui != NULL) {
4528		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4529		    desc->length);
4530		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4531		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4532		    SVPD_ID_TYPE_EUI64;
4533		desc->length = 8;
4534		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4535	}
4536	if (naa != NULL) {
4537		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4538		    desc->length);
4539		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4540		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4541		    SVPD_ID_TYPE_NAA;
4542		desc->length = 8;
4543		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4544	}
4545
4546	mtx_lock(&ctl_softc->ctl_lock);
4547	/*
4548	 * See if the caller requested a particular LUN number.  If so, see
4549	 * if it is available.  Otherwise, allocate the first available LUN.
4550	 */
4551	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4552		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4553		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4554			mtx_unlock(&ctl_softc->ctl_lock);
4555			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4556				printf("ctl: requested LUN ID %d is higher "
4557				       "than CTL_MAX_LUNS - 1 (%d)\n",
4558				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4559			} else {
4560				/*
4561				 * XXX KDM return an error, or just assign
4562				 * another LUN ID in this case??
4563				 */
4564				printf("ctl: requested LUN ID %d is already "
4565				       "in use\n", be_lun->req_lun_id);
4566			}
4567			if (lun->flags & CTL_LUN_MALLOCED)
4568				free(lun, M_CTL);
4569			be_lun->lun_config_status(be_lun->be_lun,
4570						  CTL_LUN_CONFIG_FAILURE);
4571			return (ENOSPC);
4572		}
4573		lun_number = be_lun->req_lun_id;
4574	} else {
4575		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4576		if (lun_number == -1) {
4577			mtx_unlock(&ctl_softc->ctl_lock);
4578			printf("ctl: can't allocate LUN on target %ju, out of "
4579			       "LUNs\n", (uintmax_t)target_id.id);
4580			if (lun->flags & CTL_LUN_MALLOCED)
4581				free(lun, M_CTL);
4582			be_lun->lun_config_status(be_lun->be_lun,
4583						  CTL_LUN_CONFIG_FAILURE);
4584			return (ENOSPC);
4585		}
4586	}
4587	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4588
4589	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4590	lun->target = target_id;
4591	lun->lun = lun_number;
4592	lun->be_lun = be_lun;
4593	/*
4594	 * The processor LUN is always enabled.  Disk LUNs come on line
4595	 * disabled, and must be enabled by the backend.
4596	 */
4597	lun->flags |= CTL_LUN_DISABLED;
4598	lun->backend = be_lun->be;
4599	be_lun->ctl_lun = lun;
4600	be_lun->lun_id = lun_number;
4601	atomic_add_int(&be_lun->be->num_luns, 1);
4602	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4603		lun->flags |= CTL_LUN_OFFLINE;
4604
4605	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4606		lun->flags |= CTL_LUN_STOPPED;
4607
4608	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4609		lun->flags |= CTL_LUN_INOPERABLE;
4610
4611	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4612		lun->flags |= CTL_LUN_PRIMARY_SC;
4613
4614	value = ctl_get_opt(&be_lun->options, "readonly");
4615	if (value != NULL && strcmp(value, "on") == 0)
4616		lun->flags |= CTL_LUN_READONLY;
4617
4618	lun->ctl_softc = ctl_softc;
4619	TAILQ_INIT(&lun->ooa_queue);
4620	TAILQ_INIT(&lun->blocked_queue);
4621	STAILQ_INIT(&lun->error_list);
4622	ctl_tpc_lun_init(lun);
4623
4624	/*
4625	 * Initialize the mode page index.
4626	 */
4627	ctl_init_page_index(lun);
4628
4629	/*
4630	 * Set the poweron UA for all initiators on this LUN only.
4631	 */
4632	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4633		lun->pending_ua[i] = CTL_UA_POWERON;
4634
4635	/*
4636	 * Now, before we insert this lun on the lun list, set the lun
4637	 * inventory changed UA for all other luns.
4638	 */
4639	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4640		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4641			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4642		}
4643	}
4644
4645	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4646
4647	ctl_softc->ctl_luns[lun_number] = lun;
4648
4649	ctl_softc->num_luns++;
4650
4651	/* Setup statistics gathering */
4652	lun->stats.device_type = be_lun->lun_type;
4653	lun->stats.lun_number = lun_number;
4654	if (lun->stats.device_type == T_DIRECT)
4655		lun->stats.blocksize = be_lun->blocksize;
4656	else
4657		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4658	for (i = 0;i < CTL_MAX_PORTS;i++)
4659		lun->stats.ports[i].targ_port = i;
4660
4661	mtx_unlock(&ctl_softc->ctl_lock);
4662
4663	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4664
4665	/*
4666	 * Run through each registered FETD and bring it online if it isn't
4667	 * already.  Enable the target ID if it hasn't been enabled, and
4668	 * enable this particular LUN.
4669	 */
4670	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4671		int retval;
4672
4673		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4674		if (retval != 0) {
4675			printf("ctl_alloc_lun: FETD %s port %d returned error "
4676			       "%d for lun_enable on target %ju lun %d\n",
4677			       port->port_name, port->targ_port, retval,
4678			       (uintmax_t)target_id.id, lun_number);
4679		} else
4680			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4681	}
4682	return (0);
4683}
4684
4685/*
4686 * Delete a LUN.
4687 * Assumptions:
4688 * - LUN has already been marked invalid and any pending I/O has been taken
4689 *   care of.
4690 */
4691static int
4692ctl_free_lun(struct ctl_lun *lun)
4693{
4694	struct ctl_softc *softc;
4695#if 0
4696	struct ctl_port *port;
4697#endif
4698	struct ctl_lun *nlun;
4699	int i;
4700
4701	softc = lun->ctl_softc;
4702
4703	mtx_assert(&softc->ctl_lock, MA_OWNED);
4704
4705	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4706
4707	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4708
4709	softc->ctl_luns[lun->lun] = NULL;
4710
4711	if (!TAILQ_EMPTY(&lun->ooa_queue))
4712		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4713
4714	softc->num_luns--;
4715
4716	/*
4717	 * XXX KDM this scheme only works for a single target/multiple LUN
4718	 * setup.  It needs to be revamped for a multiple target scheme.
4719	 *
4720	 * XXX KDM this results in port->lun_disable() getting called twice,
4721	 * once when ctl_disable_lun() is called, and a second time here.
4722	 * We really need to re-think the LUN disable semantics.  There
4723	 * should probably be several steps/levels to LUN removal:
4724	 *  - disable
4725	 *  - invalidate
4726	 *  - free
4727 	 *
4728	 * Right now we only have a disable method when communicating to
4729	 * the front end ports, at least for individual LUNs.
4730	 */
4731#if 0
4732	STAILQ_FOREACH(port, &softc->port_list, links) {
4733		int retval;
4734
4735		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4736					 lun->lun);
4737		if (retval != 0) {
4738			printf("ctl_free_lun: FETD %s port %d returned error "
4739			       "%d for lun_disable on target %ju lun %jd\n",
4740			       port->port_name, port->targ_port, retval,
4741			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4742		}
4743
4744		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4745			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4746
4747			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4748			if (retval != 0) {
4749				printf("ctl_free_lun: FETD %s port %d "
4750				       "returned error %d for targ_disable on "
4751				       "target %ju\n", port->port_name,
4752				       port->targ_port, retval,
4753				       (uintmax_t)lun->target.id);
4754			} else
4755				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4756
4757			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4758				continue;
4759
4760#if 0
4761			port->port_offline(port->onoff_arg);
4762			port->status &= ~CTL_PORT_STATUS_ONLINE;
4763#endif
4764		}
4765	}
4766#endif
4767
4768	/*
4769	 * Tell the backend to free resources, if this LUN has a backend.
4770	 */
4771	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4772	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4773
4774	ctl_tpc_lun_shutdown(lun);
4775	mtx_destroy(&lun->lun_lock);
4776	free(lun->lun_devid, M_CTL);
4777	if (lun->flags & CTL_LUN_MALLOCED)
4778		free(lun, M_CTL);
4779
4780	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4781		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4782			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4783		}
4784	}
4785
4786	return (0);
4787}
4788
4789static void
4790ctl_create_lun(struct ctl_be_lun *be_lun)
4791{
4792	struct ctl_softc *ctl_softc;
4793
4794	ctl_softc = control_softc;
4795
4796	/*
4797	 * ctl_alloc_lun() should handle all potential failure cases.
4798	 */
4799	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4800}
4801
4802int
4803ctl_add_lun(struct ctl_be_lun *be_lun)
4804{
4805	struct ctl_softc *ctl_softc = control_softc;
4806
4807	mtx_lock(&ctl_softc->ctl_lock);
4808	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4809	mtx_unlock(&ctl_softc->ctl_lock);
4810	wakeup(&ctl_softc->pending_lun_queue);
4811
4812	return (0);
4813}
4814
4815int
4816ctl_enable_lun(struct ctl_be_lun *be_lun)
4817{
4818	struct ctl_softc *ctl_softc;
4819	struct ctl_port *port, *nport;
4820	struct ctl_lun *lun;
4821	int retval;
4822
4823	ctl_softc = control_softc;
4824
4825	lun = (struct ctl_lun *)be_lun->ctl_lun;
4826
4827	mtx_lock(&ctl_softc->ctl_lock);
4828	mtx_lock(&lun->lun_lock);
4829	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4830		/*
4831		 * eh?  Why did we get called if the LUN is already
4832		 * enabled?
4833		 */
4834		mtx_unlock(&lun->lun_lock);
4835		mtx_unlock(&ctl_softc->ctl_lock);
4836		return (0);
4837	}
4838	lun->flags &= ~CTL_LUN_DISABLED;
4839	mtx_unlock(&lun->lun_lock);
4840
4841	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4842		nport = STAILQ_NEXT(port, links);
4843
4844		/*
4845		 * Drop the lock while we call the FETD's enable routine.
4846		 * This can lead to a callback into CTL (at least in the
4847		 * case of the internal initiator frontend.
4848		 */
4849		mtx_unlock(&ctl_softc->ctl_lock);
4850		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4851		mtx_lock(&ctl_softc->ctl_lock);
4852		if (retval != 0) {
4853			printf("%s: FETD %s port %d returned error "
4854			       "%d for lun_enable on target %ju lun %jd\n",
4855			       __func__, port->port_name, port->targ_port, retval,
4856			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4857		}
4858#if 0
4859		 else {
4860            /* NOTE:  TODO:  why does lun enable affect port status? */
4861			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4862		}
4863#endif
4864	}
4865
4866	mtx_unlock(&ctl_softc->ctl_lock);
4867
4868	return (0);
4869}
4870
4871int
4872ctl_disable_lun(struct ctl_be_lun *be_lun)
4873{
4874	struct ctl_softc *ctl_softc;
4875	struct ctl_port *port;
4876	struct ctl_lun *lun;
4877	int retval;
4878
4879	ctl_softc = control_softc;
4880
4881	lun = (struct ctl_lun *)be_lun->ctl_lun;
4882
4883	mtx_lock(&ctl_softc->ctl_lock);
4884	mtx_lock(&lun->lun_lock);
4885	if (lun->flags & CTL_LUN_DISABLED) {
4886		mtx_unlock(&lun->lun_lock);
4887		mtx_unlock(&ctl_softc->ctl_lock);
4888		return (0);
4889	}
4890	lun->flags |= CTL_LUN_DISABLED;
4891	mtx_unlock(&lun->lun_lock);
4892
4893	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4894		mtx_unlock(&ctl_softc->ctl_lock);
4895		/*
4896		 * Drop the lock before we call the frontend's disable
4897		 * routine, to avoid lock order reversals.
4898		 *
4899		 * XXX KDM what happens if the frontend list changes while
4900		 * we're traversing it?  It's unlikely, but should be handled.
4901		 */
4902		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4903					 lun->lun);
4904		mtx_lock(&ctl_softc->ctl_lock);
4905		if (retval != 0) {
4906			printf("ctl_alloc_lun: FETD %s port %d returned error "
4907			       "%d for lun_disable on target %ju lun %jd\n",
4908			       port->port_name, port->targ_port, retval,
4909			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4910		}
4911	}
4912
4913	mtx_unlock(&ctl_softc->ctl_lock);
4914
4915	return (0);
4916}
4917
4918int
4919ctl_start_lun(struct ctl_be_lun *be_lun)
4920{
4921	struct ctl_softc *ctl_softc;
4922	struct ctl_lun *lun;
4923
4924	ctl_softc = control_softc;
4925
4926	lun = (struct ctl_lun *)be_lun->ctl_lun;
4927
4928	mtx_lock(&lun->lun_lock);
4929	lun->flags &= ~CTL_LUN_STOPPED;
4930	mtx_unlock(&lun->lun_lock);
4931
4932	return (0);
4933}
4934
4935int
4936ctl_stop_lun(struct ctl_be_lun *be_lun)
4937{
4938	struct ctl_softc *ctl_softc;
4939	struct ctl_lun *lun;
4940
4941	ctl_softc = control_softc;
4942
4943	lun = (struct ctl_lun *)be_lun->ctl_lun;
4944
4945	mtx_lock(&lun->lun_lock);
4946	lun->flags |= CTL_LUN_STOPPED;
4947	mtx_unlock(&lun->lun_lock);
4948
4949	return (0);
4950}
4951
4952int
4953ctl_lun_offline(struct ctl_be_lun *be_lun)
4954{
4955	struct ctl_softc *ctl_softc;
4956	struct ctl_lun *lun;
4957
4958	ctl_softc = control_softc;
4959
4960	lun = (struct ctl_lun *)be_lun->ctl_lun;
4961
4962	mtx_lock(&lun->lun_lock);
4963	lun->flags |= CTL_LUN_OFFLINE;
4964	mtx_unlock(&lun->lun_lock);
4965
4966	return (0);
4967}
4968
4969int
4970ctl_lun_online(struct ctl_be_lun *be_lun)
4971{
4972	struct ctl_softc *ctl_softc;
4973	struct ctl_lun *lun;
4974
4975	ctl_softc = control_softc;
4976
4977	lun = (struct ctl_lun *)be_lun->ctl_lun;
4978
4979	mtx_lock(&lun->lun_lock);
4980	lun->flags &= ~CTL_LUN_OFFLINE;
4981	mtx_unlock(&lun->lun_lock);
4982
4983	return (0);
4984}
4985
4986int
4987ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4988{
4989	struct ctl_softc *ctl_softc;
4990	struct ctl_lun *lun;
4991
4992	ctl_softc = control_softc;
4993
4994	lun = (struct ctl_lun *)be_lun->ctl_lun;
4995
4996	mtx_lock(&lun->lun_lock);
4997
4998	/*
4999	 * The LUN needs to be disabled before it can be marked invalid.
5000	 */
5001	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5002		mtx_unlock(&lun->lun_lock);
5003		return (-1);
5004	}
5005	/*
5006	 * Mark the LUN invalid.
5007	 */
5008	lun->flags |= CTL_LUN_INVALID;
5009
5010	/*
5011	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5012	 * If we have something in the OOA queue, we'll free it when the
5013	 * last I/O completes.
5014	 */
5015	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5016		mtx_unlock(&lun->lun_lock);
5017		mtx_lock(&ctl_softc->ctl_lock);
5018		ctl_free_lun(lun);
5019		mtx_unlock(&ctl_softc->ctl_lock);
5020	} else
5021		mtx_unlock(&lun->lun_lock);
5022
5023	return (0);
5024}
5025
5026int
5027ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5028{
5029	struct ctl_softc *ctl_softc;
5030	struct ctl_lun *lun;
5031
5032	ctl_softc = control_softc;
5033	lun = (struct ctl_lun *)be_lun->ctl_lun;
5034
5035	mtx_lock(&lun->lun_lock);
5036	lun->flags |= CTL_LUN_INOPERABLE;
5037	mtx_unlock(&lun->lun_lock);
5038
5039	return (0);
5040}
5041
5042int
5043ctl_lun_operable(struct ctl_be_lun *be_lun)
5044{
5045	struct ctl_softc *ctl_softc;
5046	struct ctl_lun *lun;
5047
5048	ctl_softc = control_softc;
5049	lun = (struct ctl_lun *)be_lun->ctl_lun;
5050
5051	mtx_lock(&lun->lun_lock);
5052	lun->flags &= ~CTL_LUN_INOPERABLE;
5053	mtx_unlock(&lun->lun_lock);
5054
5055	return (0);
5056}
5057
5058int
5059ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5060		   int lock)
5061{
5062	struct ctl_softc *softc;
5063	struct ctl_lun *lun;
5064	struct copan_aps_subpage *current_sp;
5065	struct ctl_page_index *page_index;
5066	int i;
5067
5068	softc = control_softc;
5069
5070	mtx_lock(&softc->ctl_lock);
5071
5072	lun = (struct ctl_lun *)be_lun->ctl_lun;
5073	mtx_lock(&lun->lun_lock);
5074
5075	page_index = NULL;
5076	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5077		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5078		     APS_PAGE_CODE)
5079			continue;
5080
5081		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5082			continue;
5083		page_index = &lun->mode_pages.index[i];
5084	}
5085
5086	if (page_index == NULL) {
5087		mtx_unlock(&lun->lun_lock);
5088		mtx_unlock(&softc->ctl_lock);
5089		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5090		       (uintmax_t)lun->lun);
5091		return (1);
5092	}
5093#if 0
5094	if ((softc->aps_locked_lun != 0)
5095	 && (softc->aps_locked_lun != lun->lun)) {
5096		printf("%s: attempt to lock LUN %llu when %llu is already "
5097		       "locked\n");
5098		mtx_unlock(&lun->lun_lock);
5099		mtx_unlock(&softc->ctl_lock);
5100		return (1);
5101	}
5102#endif
5103
5104	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5105		(page_index->page_len * CTL_PAGE_CURRENT));
5106
5107	if (lock != 0) {
5108		current_sp->lock_active = APS_LOCK_ACTIVE;
5109		softc->aps_locked_lun = lun->lun;
5110	} else {
5111		current_sp->lock_active = 0;
5112		softc->aps_locked_lun = 0;
5113	}
5114
5115
5116	/*
5117	 * If we're in HA mode, try to send the lock message to the other
5118	 * side.
5119	 */
5120	if (ctl_is_single == 0) {
5121		int isc_retval;
5122		union ctl_ha_msg lock_msg;
5123
5124		lock_msg.hdr.nexus = *nexus;
5125		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5126		if (lock != 0)
5127			lock_msg.aps.lock_flag = 1;
5128		else
5129			lock_msg.aps.lock_flag = 0;
5130		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5131					 sizeof(lock_msg), 0);
5132		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5133			printf("%s: APS (lock=%d) error returned from "
5134			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5135			mtx_unlock(&lun->lun_lock);
5136			mtx_unlock(&softc->ctl_lock);
5137			return (1);
5138		}
5139	}
5140
5141	mtx_unlock(&lun->lun_lock);
5142	mtx_unlock(&softc->ctl_lock);
5143
5144	return (0);
5145}
5146
5147void
5148ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5149{
5150	struct ctl_lun *lun;
5151	struct ctl_softc *softc;
5152	int i;
5153
5154	softc = control_softc;
5155
5156	lun = (struct ctl_lun *)be_lun->ctl_lun;
5157
5158	mtx_lock(&lun->lun_lock);
5159
5160	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5161		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5162
5163	mtx_unlock(&lun->lun_lock);
5164}
5165
5166/*
5167 * Backend "memory move is complete" callback for requests that never
5168 * make it down to say RAIDCore's configuration code.
5169 */
5170int
5171ctl_config_move_done(union ctl_io *io)
5172{
5173	int retval;
5174
5175	retval = CTL_RETVAL_COMPLETE;
5176
5177
5178	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5179	/*
5180	 * XXX KDM this shouldn't happen, but what if it does?
5181	 */
5182	if (io->io_hdr.io_type != CTL_IO_SCSI)
5183		panic("I/O type isn't CTL_IO_SCSI!");
5184
5185	if ((io->io_hdr.port_status == 0)
5186	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5187	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5188		io->io_hdr.status = CTL_SUCCESS;
5189	else if ((io->io_hdr.port_status != 0)
5190	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5191	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5192		/*
5193		 * For hardware error sense keys, the sense key
5194		 * specific value is defined to be a retry count,
5195		 * but we use it to pass back an internal FETD
5196		 * error code.  XXX KDM  Hopefully the FETD is only
5197		 * using 16 bits for an error code, since that's
5198		 * all the space we have in the sks field.
5199		 */
5200		ctl_set_internal_failure(&io->scsiio,
5201					 /*sks_valid*/ 1,
5202					 /*retry_count*/
5203					 io->io_hdr.port_status);
5204		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5205			free(io->scsiio.kern_data_ptr, M_CTL);
5206		ctl_done(io);
5207		goto bailout;
5208	}
5209
5210	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5211	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5212	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5213		/*
5214		 * XXX KDM just assuming a single pointer here, and not a
5215		 * S/G list.  If we start using S/G lists for config data,
5216		 * we'll need to know how to clean them up here as well.
5217		 */
5218		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5219			free(io->scsiio.kern_data_ptr, M_CTL);
5220		/* Hopefully the user has already set the status... */
5221		ctl_done(io);
5222	} else {
5223		/*
5224		 * XXX KDM now we need to continue data movement.  Some
5225		 * options:
5226		 * - call ctl_scsiio() again?  We don't do this for data
5227		 *   writes, because for those at least we know ahead of
5228		 *   time where the write will go and how long it is.  For
5229		 *   config writes, though, that information is largely
5230		 *   contained within the write itself, thus we need to
5231		 *   parse out the data again.
5232		 *
5233		 * - Call some other function once the data is in?
5234		 */
5235
5236		/*
5237		 * XXX KDM call ctl_scsiio() again for now, and check flag
5238		 * bits to see whether we're allocated or not.
5239		 */
5240		retval = ctl_scsiio(&io->scsiio);
5241	}
5242bailout:
5243	return (retval);
5244}
5245
5246/*
5247 * This gets called by a backend driver when it is done with a
5248 * data_submit method.
5249 */
5250void
5251ctl_data_submit_done(union ctl_io *io)
5252{
5253	/*
5254	 * If the IO_CONT flag is set, we need to call the supplied
5255	 * function to continue processing the I/O, instead of completing
5256	 * the I/O just yet.
5257	 *
5258	 * If there is an error, though, we don't want to keep processing.
5259	 * Instead, just send status back to the initiator.
5260	 */
5261	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5262	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5263	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5264	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5265		io->scsiio.io_cont(io);
5266		return;
5267	}
5268	ctl_done(io);
5269}
5270
5271/*
5272 * This gets called by a backend driver when it is done with a
5273 * configuration write.
5274 */
5275void
5276ctl_config_write_done(union ctl_io *io)
5277{
5278	uint8_t *buf;
5279
5280	/*
5281	 * If the IO_CONT flag is set, we need to call the supplied
5282	 * function to continue processing the I/O, instead of completing
5283	 * the I/O just yet.
5284	 *
5285	 * If there is an error, though, we don't want to keep processing.
5286	 * Instead, just send status back to the initiator.
5287	 */
5288	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5289	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5290	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5291	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5292		io->scsiio.io_cont(io);
5293		return;
5294	}
5295	/*
5296	 * Since a configuration write can be done for commands that actually
5297	 * have data allocated, like write buffer, and commands that have
5298	 * no data, like start/stop unit, we need to check here.
5299	 */
5300	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5301		buf = io->scsiio.kern_data_ptr;
5302	else
5303		buf = NULL;
5304	ctl_done(io);
5305	if (buf)
5306		free(buf, M_CTL);
5307}
5308
5309/*
5310 * SCSI release command.
5311 */
5312int
5313ctl_scsi_release(struct ctl_scsiio *ctsio)
5314{
5315	int length, longid, thirdparty_id, resv_id;
5316	struct ctl_softc *ctl_softc;
5317	struct ctl_lun *lun;
5318	uint32_t residx;
5319
5320	length = 0;
5321	resv_id = 0;
5322
5323	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5324
5325	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5326	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5327	ctl_softc = control_softc;
5328
5329	switch (ctsio->cdb[0]) {
5330	case RELEASE_10: {
5331		struct scsi_release_10 *cdb;
5332
5333		cdb = (struct scsi_release_10 *)ctsio->cdb;
5334
5335		if (cdb->byte2 & SR10_LONGID)
5336			longid = 1;
5337		else
5338			thirdparty_id = cdb->thirdparty_id;
5339
5340		resv_id = cdb->resv_id;
5341		length = scsi_2btoul(cdb->length);
5342		break;
5343	}
5344	}
5345
5346
5347	/*
5348	 * XXX KDM right now, we only support LUN reservation.  We don't
5349	 * support 3rd party reservations, or extent reservations, which
5350	 * might actually need the parameter list.  If we've gotten this
5351	 * far, we've got a LUN reservation.  Anything else got kicked out
5352	 * above.  So, according to SPC, ignore the length.
5353	 */
5354	length = 0;
5355
5356	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5357	 && (length > 0)) {
5358		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5359		ctsio->kern_data_len = length;
5360		ctsio->kern_total_len = length;
5361		ctsio->kern_data_resid = 0;
5362		ctsio->kern_rel_offset = 0;
5363		ctsio->kern_sg_entries = 0;
5364		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5365		ctsio->be_move_done = ctl_config_move_done;
5366		ctl_datamove((union ctl_io *)ctsio);
5367
5368		return (CTL_RETVAL_COMPLETE);
5369	}
5370
5371	if (length > 0)
5372		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5373
5374	mtx_lock(&lun->lun_lock);
5375
5376	/*
5377	 * According to SPC, it is not an error for an intiator to attempt
5378	 * to release a reservation on a LUN that isn't reserved, or that
5379	 * is reserved by another initiator.  The reservation can only be
5380	 * released, though, by the initiator who made it or by one of
5381	 * several reset type events.
5382	 */
5383	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5384			lun->flags &= ~CTL_LUN_RESERVED;
5385
5386	mtx_unlock(&lun->lun_lock);
5387
5388	ctsio->scsi_status = SCSI_STATUS_OK;
5389	ctsio->io_hdr.status = CTL_SUCCESS;
5390
5391	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5392		free(ctsio->kern_data_ptr, M_CTL);
5393		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5394	}
5395
5396	ctl_done((union ctl_io *)ctsio);
5397	return (CTL_RETVAL_COMPLETE);
5398}
5399
5400int
5401ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5402{
5403	int extent, thirdparty, longid;
5404	int resv_id, length;
5405	uint64_t thirdparty_id;
5406	struct ctl_softc *ctl_softc;
5407	struct ctl_lun *lun;
5408	uint32_t residx;
5409
5410	extent = 0;
5411	thirdparty = 0;
5412	longid = 0;
5413	resv_id = 0;
5414	length = 0;
5415	thirdparty_id = 0;
5416
5417	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5418
5419	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5420	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5421	ctl_softc = control_softc;
5422
5423	switch (ctsio->cdb[0]) {
5424	case RESERVE_10: {
5425		struct scsi_reserve_10 *cdb;
5426
5427		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5428
5429		if (cdb->byte2 & SR10_LONGID)
5430			longid = 1;
5431		else
5432			thirdparty_id = cdb->thirdparty_id;
5433
5434		resv_id = cdb->resv_id;
5435		length = scsi_2btoul(cdb->length);
5436		break;
5437	}
5438	}
5439
5440	/*
5441	 * XXX KDM right now, we only support LUN reservation.  We don't
5442	 * support 3rd party reservations, or extent reservations, which
5443	 * might actually need the parameter list.  If we've gotten this
5444	 * far, we've got a LUN reservation.  Anything else got kicked out
5445	 * above.  So, according to SPC, ignore the length.
5446	 */
5447	length = 0;
5448
5449	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5450	 && (length > 0)) {
5451		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5452		ctsio->kern_data_len = length;
5453		ctsio->kern_total_len = length;
5454		ctsio->kern_data_resid = 0;
5455		ctsio->kern_rel_offset = 0;
5456		ctsio->kern_sg_entries = 0;
5457		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5458		ctsio->be_move_done = ctl_config_move_done;
5459		ctl_datamove((union ctl_io *)ctsio);
5460
5461		return (CTL_RETVAL_COMPLETE);
5462	}
5463
5464	if (length > 0)
5465		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5466
5467	mtx_lock(&lun->lun_lock);
5468	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5469		ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5470		ctsio->io_hdr.status = CTL_SCSI_ERROR;
5471		goto bailout;
5472	}
5473
5474	lun->flags |= CTL_LUN_RESERVED;
5475	lun->res_idx = residx;
5476
5477	ctsio->scsi_status = SCSI_STATUS_OK;
5478	ctsio->io_hdr.status = CTL_SUCCESS;
5479
5480bailout:
5481	mtx_unlock(&lun->lun_lock);
5482
5483	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5484		free(ctsio->kern_data_ptr, M_CTL);
5485		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5486	}
5487
5488	ctl_done((union ctl_io *)ctsio);
5489	return (CTL_RETVAL_COMPLETE);
5490}
5491
5492int
5493ctl_start_stop(struct ctl_scsiio *ctsio)
5494{
5495	struct scsi_start_stop_unit *cdb;
5496	struct ctl_lun *lun;
5497	struct ctl_softc *ctl_softc;
5498	int retval;
5499
5500	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5501
5502	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5503	ctl_softc = control_softc;
5504	retval = 0;
5505
5506	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5507
5508	/*
5509	 * XXX KDM
5510	 * We don't support the immediate bit on a stop unit.  In order to
5511	 * do that, we would need to code up a way to know that a stop is
5512	 * pending, and hold off any new commands until it completes, one
5513	 * way or another.  Then we could accept or reject those commands
5514	 * depending on its status.  We would almost need to do the reverse
5515	 * of what we do below for an immediate start -- return the copy of
5516	 * the ctl_io to the FETD with status to send to the host (and to
5517	 * free the copy!) and then free the original I/O once the stop
5518	 * actually completes.  That way, the OOA queue mechanism can work
5519	 * to block commands that shouldn't proceed.  Another alternative
5520	 * would be to put the copy in the queue in place of the original,
5521	 * and return the original back to the caller.  That could be
5522	 * slightly safer..
5523	 */
5524	if ((cdb->byte2 & SSS_IMMED)
5525	 && ((cdb->how & SSS_START) == 0)) {
5526		ctl_set_invalid_field(ctsio,
5527				      /*sks_valid*/ 1,
5528				      /*command*/ 1,
5529				      /*field*/ 1,
5530				      /*bit_valid*/ 1,
5531				      /*bit*/ 0);
5532		ctl_done((union ctl_io *)ctsio);
5533		return (CTL_RETVAL_COMPLETE);
5534	}
5535
5536	if ((lun->flags & CTL_LUN_PR_RESERVED)
5537	 && ((cdb->how & SSS_START)==0)) {
5538		uint32_t residx;
5539
5540		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5541		if (lun->pr_keys[residx] == 0
5542		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5543
5544			ctl_set_reservation_conflict(ctsio);
5545			ctl_done((union ctl_io *)ctsio);
5546			return (CTL_RETVAL_COMPLETE);
5547		}
5548	}
5549
5550	/*
5551	 * If there is no backend on this device, we can't start or stop
5552	 * it.  In theory we shouldn't get any start/stop commands in the
5553	 * first place at this level if the LUN doesn't have a backend.
5554	 * That should get stopped by the command decode code.
5555	 */
5556	if (lun->backend == NULL) {
5557		ctl_set_invalid_opcode(ctsio);
5558		ctl_done((union ctl_io *)ctsio);
5559		return (CTL_RETVAL_COMPLETE);
5560	}
5561
5562	/*
5563	 * XXX KDM Copan-specific offline behavior.
5564	 * Figure out a reasonable way to port this?
5565	 */
5566#ifdef NEEDTOPORT
5567	mtx_lock(&lun->lun_lock);
5568
5569	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5570	 && (lun->flags & CTL_LUN_OFFLINE)) {
5571		/*
5572		 * If the LUN is offline, and the on/offline bit isn't set,
5573		 * reject the start or stop.  Otherwise, let it through.
5574		 */
5575		mtx_unlock(&lun->lun_lock);
5576		ctl_set_lun_not_ready(ctsio);
5577		ctl_done((union ctl_io *)ctsio);
5578	} else {
5579		mtx_unlock(&lun->lun_lock);
5580#endif /* NEEDTOPORT */
5581		/*
5582		 * This could be a start or a stop when we're online,
5583		 * or a stop/offline or start/online.  A start or stop when
5584		 * we're offline is covered in the case above.
5585		 */
5586		/*
5587		 * In the non-immediate case, we send the request to
5588		 * the backend and return status to the user when
5589		 * it is done.
5590		 *
5591		 * In the immediate case, we allocate a new ctl_io
5592		 * to hold a copy of the request, and send that to
5593		 * the backend.  We then set good status on the
5594		 * user's request and return it immediately.
5595		 */
5596		if (cdb->byte2 & SSS_IMMED) {
5597			union ctl_io *new_io;
5598
5599			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5600			if (new_io == NULL) {
5601				ctl_set_busy(ctsio);
5602				ctl_done((union ctl_io *)ctsio);
5603			} else {
5604				ctl_copy_io((union ctl_io *)ctsio,
5605					    new_io);
5606				retval = lun->backend->config_write(new_io);
5607				ctl_set_success(ctsio);
5608				ctl_done((union ctl_io *)ctsio);
5609			}
5610		} else {
5611			retval = lun->backend->config_write(
5612				(union ctl_io *)ctsio);
5613		}
5614#ifdef NEEDTOPORT
5615	}
5616#endif
5617	return (retval);
5618}
5619
5620/*
5621 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5622 * we don't really do anything with the LBA and length fields if the user
5623 * passes them in.  Instead we'll just flush out the cache for the entire
5624 * LUN.
5625 */
5626int
5627ctl_sync_cache(struct ctl_scsiio *ctsio)
5628{
5629	struct ctl_lun *lun;
5630	struct ctl_softc *ctl_softc;
5631	uint64_t starting_lba;
5632	uint32_t block_count;
5633	int retval;
5634
5635	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5636
5637	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5638	ctl_softc = control_softc;
5639	retval = 0;
5640
5641	switch (ctsio->cdb[0]) {
5642	case SYNCHRONIZE_CACHE: {
5643		struct scsi_sync_cache *cdb;
5644		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5645
5646		starting_lba = scsi_4btoul(cdb->begin_lba);
5647		block_count = scsi_2btoul(cdb->lb_count);
5648		break;
5649	}
5650	case SYNCHRONIZE_CACHE_16: {
5651		struct scsi_sync_cache_16 *cdb;
5652		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5653
5654		starting_lba = scsi_8btou64(cdb->begin_lba);
5655		block_count = scsi_4btoul(cdb->lb_count);
5656		break;
5657	}
5658	default:
5659		ctl_set_invalid_opcode(ctsio);
5660		ctl_done((union ctl_io *)ctsio);
5661		goto bailout;
5662		break; /* NOTREACHED */
5663	}
5664
5665	/*
5666	 * We check the LBA and length, but don't do anything with them.
5667	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5668	 * get flushed.  This check will just help satisfy anyone who wants
5669	 * to see an error for an out of range LBA.
5670	 */
5671	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5672		ctl_set_lba_out_of_range(ctsio);
5673		ctl_done((union ctl_io *)ctsio);
5674		goto bailout;
5675	}
5676
5677	/*
5678	 * If this LUN has no backend, we can't flush the cache anyway.
5679	 */
5680	if (lun->backend == NULL) {
5681		ctl_set_invalid_opcode(ctsio);
5682		ctl_done((union ctl_io *)ctsio);
5683		goto bailout;
5684	}
5685
5686	/*
5687	 * Check to see whether we're configured to send the SYNCHRONIZE
5688	 * CACHE command directly to the back end.
5689	 */
5690	mtx_lock(&lun->lun_lock);
5691	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5692	 && (++(lun->sync_count) >= lun->sync_interval)) {
5693		lun->sync_count = 0;
5694		mtx_unlock(&lun->lun_lock);
5695		retval = lun->backend->config_write((union ctl_io *)ctsio);
5696	} else {
5697		mtx_unlock(&lun->lun_lock);
5698		ctl_set_success(ctsio);
5699		ctl_done((union ctl_io *)ctsio);
5700	}
5701
5702bailout:
5703
5704	return (retval);
5705}
5706
5707int
5708ctl_format(struct ctl_scsiio *ctsio)
5709{
5710	struct scsi_format *cdb;
5711	struct ctl_lun *lun;
5712	struct ctl_softc *ctl_softc;
5713	int length, defect_list_len;
5714
5715	CTL_DEBUG_PRINT(("ctl_format\n"));
5716
5717	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5718	ctl_softc = control_softc;
5719
5720	cdb = (struct scsi_format *)ctsio->cdb;
5721
5722	length = 0;
5723	if (cdb->byte2 & SF_FMTDATA) {
5724		if (cdb->byte2 & SF_LONGLIST)
5725			length = sizeof(struct scsi_format_header_long);
5726		else
5727			length = sizeof(struct scsi_format_header_short);
5728	}
5729
5730	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5731	 && (length > 0)) {
5732		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5733		ctsio->kern_data_len = length;
5734		ctsio->kern_total_len = length;
5735		ctsio->kern_data_resid = 0;
5736		ctsio->kern_rel_offset = 0;
5737		ctsio->kern_sg_entries = 0;
5738		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5739		ctsio->be_move_done = ctl_config_move_done;
5740		ctl_datamove((union ctl_io *)ctsio);
5741
5742		return (CTL_RETVAL_COMPLETE);
5743	}
5744
5745	defect_list_len = 0;
5746
5747	if (cdb->byte2 & SF_FMTDATA) {
5748		if (cdb->byte2 & SF_LONGLIST) {
5749			struct scsi_format_header_long *header;
5750
5751			header = (struct scsi_format_header_long *)
5752				ctsio->kern_data_ptr;
5753
5754			defect_list_len = scsi_4btoul(header->defect_list_len);
5755			if (defect_list_len != 0) {
5756				ctl_set_invalid_field(ctsio,
5757						      /*sks_valid*/ 1,
5758						      /*command*/ 0,
5759						      /*field*/ 2,
5760						      /*bit_valid*/ 0,
5761						      /*bit*/ 0);
5762				goto bailout;
5763			}
5764		} else {
5765			struct scsi_format_header_short *header;
5766
5767			header = (struct scsi_format_header_short *)
5768				ctsio->kern_data_ptr;
5769
5770			defect_list_len = scsi_2btoul(header->defect_list_len);
5771			if (defect_list_len != 0) {
5772				ctl_set_invalid_field(ctsio,
5773						      /*sks_valid*/ 1,
5774						      /*command*/ 0,
5775						      /*field*/ 2,
5776						      /*bit_valid*/ 0,
5777						      /*bit*/ 0);
5778				goto bailout;
5779			}
5780		}
5781	}
5782
5783	/*
5784	 * The format command will clear out the "Medium format corrupted"
5785	 * status if set by the configuration code.  That status is really
5786	 * just a way to notify the host that we have lost the media, and
5787	 * get them to issue a command that will basically make them think
5788	 * they're blowing away the media.
5789	 */
5790	mtx_lock(&lun->lun_lock);
5791	lun->flags &= ~CTL_LUN_INOPERABLE;
5792	mtx_unlock(&lun->lun_lock);
5793
5794	ctsio->scsi_status = SCSI_STATUS_OK;
5795	ctsio->io_hdr.status = CTL_SUCCESS;
5796bailout:
5797
5798	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5799		free(ctsio->kern_data_ptr, M_CTL);
5800		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5801	}
5802
5803	ctl_done((union ctl_io *)ctsio);
5804	return (CTL_RETVAL_COMPLETE);
5805}
5806
5807int
5808ctl_read_buffer(struct ctl_scsiio *ctsio)
5809{
5810	struct scsi_read_buffer *cdb;
5811	struct ctl_lun *lun;
5812	int buffer_offset, len;
5813	static uint8_t descr[4];
5814	static uint8_t echo_descr[4] = { 0 };
5815
5816	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5817
5818	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5819	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5820
5821	if (lun->flags & CTL_LUN_PR_RESERVED) {
5822		uint32_t residx;
5823
5824		/*
5825		 * XXX KDM need a lock here.
5826		 */
5827		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5828		if ((lun->res_type == SPR_TYPE_EX_AC
5829		  && residx != lun->pr_res_idx)
5830		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5831		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5832		  && lun->pr_keys[residx] == 0)) {
5833			ctl_set_reservation_conflict(ctsio);
5834			ctl_done((union ctl_io *)ctsio);
5835			return (CTL_RETVAL_COMPLETE);
5836	        }
5837	}
5838
5839	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5840	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5841	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5842		ctl_set_invalid_field(ctsio,
5843				      /*sks_valid*/ 1,
5844				      /*command*/ 1,
5845				      /*field*/ 1,
5846				      /*bit_valid*/ 1,
5847				      /*bit*/ 4);
5848		ctl_done((union ctl_io *)ctsio);
5849		return (CTL_RETVAL_COMPLETE);
5850	}
5851
5852	len = scsi_3btoul(cdb->length);
5853	buffer_offset = scsi_3btoul(cdb->offset);
5854
5855	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5856		ctl_set_invalid_field(ctsio,
5857				      /*sks_valid*/ 1,
5858				      /*command*/ 1,
5859				      /*field*/ 6,
5860				      /*bit_valid*/ 0,
5861				      /*bit*/ 0);
5862		ctl_done((union ctl_io *)ctsio);
5863		return (CTL_RETVAL_COMPLETE);
5864	}
5865
5866	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5867		descr[0] = 0;
5868		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5869		ctsio->kern_data_ptr = descr;
5870		len = min(len, sizeof(descr));
5871	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5872		ctsio->kern_data_ptr = echo_descr;
5873		len = min(len, sizeof(echo_descr));
5874	} else
5875		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5876	ctsio->kern_data_len = len;
5877	ctsio->kern_total_len = len;
5878	ctsio->kern_data_resid = 0;
5879	ctsio->kern_rel_offset = 0;
5880	ctsio->kern_sg_entries = 0;
5881	ctsio->be_move_done = ctl_config_move_done;
5882	ctl_datamove((union ctl_io *)ctsio);
5883
5884	return (CTL_RETVAL_COMPLETE);
5885}
5886
5887int
5888ctl_write_buffer(struct ctl_scsiio *ctsio)
5889{
5890	struct scsi_write_buffer *cdb;
5891	struct ctl_lun *lun;
5892	int buffer_offset, len;
5893
5894	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5895
5896	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5897	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5898
5899	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5900		ctl_set_invalid_field(ctsio,
5901				      /*sks_valid*/ 1,
5902				      /*command*/ 1,
5903				      /*field*/ 1,
5904				      /*bit_valid*/ 1,
5905				      /*bit*/ 4);
5906		ctl_done((union ctl_io *)ctsio);
5907		return (CTL_RETVAL_COMPLETE);
5908	}
5909
5910	len = scsi_3btoul(cdb->length);
5911	buffer_offset = scsi_3btoul(cdb->offset);
5912
5913	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5914		ctl_set_invalid_field(ctsio,
5915				      /*sks_valid*/ 1,
5916				      /*command*/ 1,
5917				      /*field*/ 6,
5918				      /*bit_valid*/ 0,
5919				      /*bit*/ 0);
5920		ctl_done((union ctl_io *)ctsio);
5921		return (CTL_RETVAL_COMPLETE);
5922	}
5923
5924	/*
5925	 * If we've got a kernel request that hasn't been malloced yet,
5926	 * malloc it and tell the caller the data buffer is here.
5927	 */
5928	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5929		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5930		ctsio->kern_data_len = len;
5931		ctsio->kern_total_len = len;
5932		ctsio->kern_data_resid = 0;
5933		ctsio->kern_rel_offset = 0;
5934		ctsio->kern_sg_entries = 0;
5935		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5936		ctsio->be_move_done = ctl_config_move_done;
5937		ctl_datamove((union ctl_io *)ctsio);
5938
5939		return (CTL_RETVAL_COMPLETE);
5940	}
5941
5942	ctl_done((union ctl_io *)ctsio);
5943
5944	return (CTL_RETVAL_COMPLETE);
5945}
5946
5947int
5948ctl_write_same(struct ctl_scsiio *ctsio)
5949{
5950	struct ctl_lun *lun;
5951	struct ctl_lba_len_flags *lbalen;
5952	uint64_t lba;
5953	uint32_t num_blocks;
5954	int len, retval;
5955	uint8_t byte2;
5956
5957	retval = CTL_RETVAL_COMPLETE;
5958
5959	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5960
5961	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5962
5963	switch (ctsio->cdb[0]) {
5964	case WRITE_SAME_10: {
5965		struct scsi_write_same_10 *cdb;
5966
5967		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5968
5969		lba = scsi_4btoul(cdb->addr);
5970		num_blocks = scsi_2btoul(cdb->length);
5971		byte2 = cdb->byte2;
5972		break;
5973	}
5974	case WRITE_SAME_16: {
5975		struct scsi_write_same_16 *cdb;
5976
5977		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5978
5979		lba = scsi_8btou64(cdb->addr);
5980		num_blocks = scsi_4btoul(cdb->length);
5981		byte2 = cdb->byte2;
5982		break;
5983	}
5984	default:
5985		/*
5986		 * We got a command we don't support.  This shouldn't
5987		 * happen, commands should be filtered out above us.
5988		 */
5989		ctl_set_invalid_opcode(ctsio);
5990		ctl_done((union ctl_io *)ctsio);
5991
5992		return (CTL_RETVAL_COMPLETE);
5993		break; /* NOTREACHED */
5994	}
5995
5996	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5997	if ((byte2 & SWS_UNMAP) == 0 &&
5998	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5999		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6000		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6001		ctl_done((union ctl_io *)ctsio);
6002		return (CTL_RETVAL_COMPLETE);
6003	}
6004
6005	/*
6006	 * The first check is to make sure we're in bounds, the second
6007	 * check is to catch wrap-around problems.  If the lba + num blocks
6008	 * is less than the lba, then we've wrapped around and the block
6009	 * range is invalid anyway.
6010	 */
6011	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6012	 || ((lba + num_blocks) < lba)) {
6013		ctl_set_lba_out_of_range(ctsio);
6014		ctl_done((union ctl_io *)ctsio);
6015		return (CTL_RETVAL_COMPLETE);
6016	}
6017
6018	/* Zero number of blocks means "to the last logical block" */
6019	if (num_blocks == 0) {
6020		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6021			ctl_set_invalid_field(ctsio,
6022					      /*sks_valid*/ 0,
6023					      /*command*/ 1,
6024					      /*field*/ 0,
6025					      /*bit_valid*/ 0,
6026					      /*bit*/ 0);
6027			ctl_done((union ctl_io *)ctsio);
6028			return (CTL_RETVAL_COMPLETE);
6029		}
6030		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6031	}
6032
6033	len = lun->be_lun->blocksize;
6034
6035	/*
6036	 * If we've got a kernel request that hasn't been malloced yet,
6037	 * malloc it and tell the caller the data buffer is here.
6038	 */
6039	if ((byte2 & SWS_NDOB) == 0 &&
6040	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6041		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6042		ctsio->kern_data_len = len;
6043		ctsio->kern_total_len = len;
6044		ctsio->kern_data_resid = 0;
6045		ctsio->kern_rel_offset = 0;
6046		ctsio->kern_sg_entries = 0;
6047		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6048		ctsio->be_move_done = ctl_config_move_done;
6049		ctl_datamove((union ctl_io *)ctsio);
6050
6051		return (CTL_RETVAL_COMPLETE);
6052	}
6053
6054	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6055	lbalen->lba = lba;
6056	lbalen->len = num_blocks;
6057	lbalen->flags = byte2;
6058	retval = lun->backend->config_write((union ctl_io *)ctsio);
6059
6060	return (retval);
6061}
6062
6063int
6064ctl_unmap(struct ctl_scsiio *ctsio)
6065{
6066	struct ctl_lun *lun;
6067	struct scsi_unmap *cdb;
6068	struct ctl_ptr_len_flags *ptrlen;
6069	struct scsi_unmap_header *hdr;
6070	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6071	uint64_t lba;
6072	uint32_t num_blocks;
6073	int len, retval;
6074	uint8_t byte2;
6075
6076	retval = CTL_RETVAL_COMPLETE;
6077
6078	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6079
6080	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6081	cdb = (struct scsi_unmap *)ctsio->cdb;
6082
6083	len = scsi_2btoul(cdb->length);
6084	byte2 = cdb->byte2;
6085
6086	/*
6087	 * If we've got a kernel request that hasn't been malloced yet,
6088	 * malloc it and tell the caller the data buffer is here.
6089	 */
6090	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6091		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6092		ctsio->kern_data_len = len;
6093		ctsio->kern_total_len = len;
6094		ctsio->kern_data_resid = 0;
6095		ctsio->kern_rel_offset = 0;
6096		ctsio->kern_sg_entries = 0;
6097		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6098		ctsio->be_move_done = ctl_config_move_done;
6099		ctl_datamove((union ctl_io *)ctsio);
6100
6101		return (CTL_RETVAL_COMPLETE);
6102	}
6103
6104	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6105	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6106	if (len < sizeof (*hdr) ||
6107	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6108	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6109	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6110		ctl_set_invalid_field(ctsio,
6111				      /*sks_valid*/ 0,
6112				      /*command*/ 0,
6113				      /*field*/ 0,
6114				      /*bit_valid*/ 0,
6115				      /*bit*/ 0);
6116		ctl_done((union ctl_io *)ctsio);
6117		return (CTL_RETVAL_COMPLETE);
6118	}
6119	len = scsi_2btoul(hdr->desc_length);
6120	buf = (struct scsi_unmap_desc *)(hdr + 1);
6121	end = buf + len / sizeof(*buf);
6122
6123	endnz = buf;
6124	for (range = buf; range < end; range++) {
6125		lba = scsi_8btou64(range->lba);
6126		num_blocks = scsi_4btoul(range->length);
6127		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6128		 || ((lba + num_blocks) < lba)) {
6129			ctl_set_lba_out_of_range(ctsio);
6130			ctl_done((union ctl_io *)ctsio);
6131			return (CTL_RETVAL_COMPLETE);
6132		}
6133		if (num_blocks != 0)
6134			endnz = range + 1;
6135	}
6136
6137	/*
6138	 * Block backend can not handle zero last range.
6139	 * Filter it out and return if there is nothing left.
6140	 */
6141	len = (uint8_t *)endnz - (uint8_t *)buf;
6142	if (len == 0) {
6143		ctl_set_success(ctsio);
6144		ctl_done((union ctl_io *)ctsio);
6145		return (CTL_RETVAL_COMPLETE);
6146	}
6147
6148	mtx_lock(&lun->lun_lock);
6149	ptrlen = (struct ctl_ptr_len_flags *)
6150	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6151	ptrlen->ptr = (void *)buf;
6152	ptrlen->len = len;
6153	ptrlen->flags = byte2;
6154	ctl_check_blocked(lun);
6155	mtx_unlock(&lun->lun_lock);
6156
6157	retval = lun->backend->config_write((union ctl_io *)ctsio);
6158	return (retval);
6159}
6160
6161/*
6162 * Note that this function currently doesn't actually do anything inside
6163 * CTL to enforce things if the DQue bit is turned on.
6164 *
6165 * Also note that this function can't be used in the default case, because
6166 * the DQue bit isn't set in the changeable mask for the control mode page
6167 * anyway.  This is just here as an example for how to implement a page
6168 * handler, and a placeholder in case we want to allow the user to turn
6169 * tagged queueing on and off.
6170 *
6171 * The D_SENSE bit handling is functional, however, and will turn
6172 * descriptor sense on and off for a given LUN.
6173 */
6174int
6175ctl_control_page_handler(struct ctl_scsiio *ctsio,
6176			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6177{
6178	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6179	struct ctl_lun *lun;
6180	struct ctl_softc *softc;
6181	int set_ua;
6182	uint32_t initidx;
6183
6184	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6185	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6186	set_ua = 0;
6187
6188	user_cp = (struct scsi_control_page *)page_ptr;
6189	current_cp = (struct scsi_control_page *)
6190		(page_index->page_data + (page_index->page_len *
6191		CTL_PAGE_CURRENT));
6192	saved_cp = (struct scsi_control_page *)
6193		(page_index->page_data + (page_index->page_len *
6194		CTL_PAGE_SAVED));
6195
6196	softc = control_softc;
6197
6198	mtx_lock(&lun->lun_lock);
6199	if (((current_cp->rlec & SCP_DSENSE) == 0)
6200	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6201		/*
6202		 * Descriptor sense is currently turned off and the user
6203		 * wants to turn it on.
6204		 */
6205		current_cp->rlec |= SCP_DSENSE;
6206		saved_cp->rlec |= SCP_DSENSE;
6207		lun->flags |= CTL_LUN_SENSE_DESC;
6208		set_ua = 1;
6209	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6210		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6211		/*
6212		 * Descriptor sense is currently turned on, and the user
6213		 * wants to turn it off.
6214		 */
6215		current_cp->rlec &= ~SCP_DSENSE;
6216		saved_cp->rlec &= ~SCP_DSENSE;
6217		lun->flags &= ~CTL_LUN_SENSE_DESC;
6218		set_ua = 1;
6219	}
6220	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6221	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6222		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6223		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6224		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6225		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6226		set_ua = 1;
6227	}
6228	if ((current_cp->eca_and_aen & SCP_SWP) !=
6229	    (user_cp->eca_and_aen & SCP_SWP)) {
6230		current_cp->eca_and_aen &= ~SCP_SWP;
6231		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6232		saved_cp->eca_and_aen &= ~SCP_SWP;
6233		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6234		set_ua = 1;
6235	}
6236	if (set_ua != 0) {
6237		int i;
6238		/*
6239		 * Let other initiators know that the mode
6240		 * parameters for this LUN have changed.
6241		 */
6242		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6243			if (i == initidx)
6244				continue;
6245
6246			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6247		}
6248	}
6249	mtx_unlock(&lun->lun_lock);
6250
6251	return (0);
6252}
6253
6254int
6255ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6256		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6257{
6258	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6259	struct ctl_lun *lun;
6260	int set_ua;
6261	uint32_t initidx;
6262
6263	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6264	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6265	set_ua = 0;
6266
6267	user_cp = (struct scsi_caching_page *)page_ptr;
6268	current_cp = (struct scsi_caching_page *)
6269		(page_index->page_data + (page_index->page_len *
6270		CTL_PAGE_CURRENT));
6271	saved_cp = (struct scsi_caching_page *)
6272		(page_index->page_data + (page_index->page_len *
6273		CTL_PAGE_SAVED));
6274
6275	mtx_lock(&lun->lun_lock);
6276	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6277	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6278		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6279		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6280		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6281		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6282		set_ua = 1;
6283	}
6284	if (set_ua != 0) {
6285		int i;
6286		/*
6287		 * Let other initiators know that the mode
6288		 * parameters for this LUN have changed.
6289		 */
6290		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6291			if (i == initidx)
6292				continue;
6293
6294			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6295		}
6296	}
6297	mtx_unlock(&lun->lun_lock);
6298
6299	return (0);
6300}
6301
6302int
6303ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6304		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6305{
6306	return (0);
6307}
6308
6309int
6310ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6311			   struct ctl_page_index *page_index, int pc)
6312{
6313	struct copan_power_subpage *page;
6314
6315	page = (struct copan_power_subpage *)page_index->page_data +
6316		(page_index->page_len * pc);
6317
6318	switch (pc) {
6319	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6320		/*
6321		 * We don't update the changable bits for this page.
6322		 */
6323		break;
6324	case SMS_PAGE_CTRL_CURRENT >> 6:
6325	case SMS_PAGE_CTRL_DEFAULT >> 6:
6326	case SMS_PAGE_CTRL_SAVED >> 6:
6327#ifdef NEEDTOPORT
6328		ctl_update_power_subpage(page);
6329#endif
6330		break;
6331	default:
6332#ifdef NEEDTOPORT
6333		EPRINT(0, "Invalid PC %d!!", pc);
6334#endif
6335		break;
6336	}
6337	return (0);
6338}
6339
6340
6341int
6342ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6343		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6344{
6345	struct copan_aps_subpage *user_sp;
6346	struct copan_aps_subpage *current_sp;
6347	union ctl_modepage_info *modepage_info;
6348	struct ctl_softc *softc;
6349	struct ctl_lun *lun;
6350	int retval;
6351
6352	retval = CTL_RETVAL_COMPLETE;
6353	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6354		     (page_index->page_len * CTL_PAGE_CURRENT));
6355	softc = control_softc;
6356	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6357
6358	user_sp = (struct copan_aps_subpage *)page_ptr;
6359
6360	modepage_info = (union ctl_modepage_info *)
6361		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6362
6363	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6364	modepage_info->header.subpage = page_index->subpage;
6365	modepage_info->aps.lock_active = user_sp->lock_active;
6366
6367	mtx_lock(&softc->ctl_lock);
6368
6369	/*
6370	 * If there is a request to lock the LUN and another LUN is locked
6371	 * this is an error. If the requested LUN is already locked ignore
6372	 * the request. If no LUN is locked attempt to lock it.
6373	 * if there is a request to unlock the LUN and the LUN is currently
6374	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6375	 * if another LUN is locked or no LUN is locked.
6376	 */
6377	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6378		if (softc->aps_locked_lun == lun->lun) {
6379			/*
6380			 * This LUN is already locked, so we're done.
6381			 */
6382			retval = CTL_RETVAL_COMPLETE;
6383		} else if (softc->aps_locked_lun == 0) {
6384			/*
6385			 * No one has the lock, pass the request to the
6386			 * backend.
6387			 */
6388			retval = lun->backend->config_write(
6389				(union ctl_io *)ctsio);
6390		} else {
6391			/*
6392			 * Someone else has the lock, throw out the request.
6393			 */
6394			ctl_set_already_locked(ctsio);
6395			free(ctsio->kern_data_ptr, M_CTL);
6396			ctl_done((union ctl_io *)ctsio);
6397
6398			/*
6399			 * Set the return value so that ctl_do_mode_select()
6400			 * won't try to complete the command.  We already
6401			 * completed it here.
6402			 */
6403			retval = CTL_RETVAL_ERROR;
6404		}
6405	} else if (softc->aps_locked_lun == lun->lun) {
6406		/*
6407		 * This LUN is locked, so pass the unlock request to the
6408		 * backend.
6409		 */
6410		retval = lun->backend->config_write((union ctl_io *)ctsio);
6411	}
6412	mtx_unlock(&softc->ctl_lock);
6413
6414	return (retval);
6415}
6416
6417int
6418ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6419				struct ctl_page_index *page_index,
6420				uint8_t *page_ptr)
6421{
6422	uint8_t *c;
6423	int i;
6424
6425	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6426	ctl_time_io_secs =
6427		(c[0] << 8) |
6428		(c[1] << 0) |
6429		0;
6430	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6431	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6432	printf("page data:");
6433	for (i=0; i<8; i++)
6434		printf(" %.2x",page_ptr[i]);
6435	printf("\n");
6436	return (0);
6437}
6438
6439int
6440ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6441			       struct ctl_page_index *page_index,
6442			       int pc)
6443{
6444	struct copan_debugconf_subpage *page;
6445
6446	page = (struct copan_debugconf_subpage *)page_index->page_data +
6447		(page_index->page_len * pc);
6448
6449	switch (pc) {
6450	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6451	case SMS_PAGE_CTRL_DEFAULT >> 6:
6452	case SMS_PAGE_CTRL_SAVED >> 6:
6453		/*
6454		 * We don't update the changable or default bits for this page.
6455		 */
6456		break;
6457	case SMS_PAGE_CTRL_CURRENT >> 6:
6458		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6459		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6460		break;
6461	default:
6462#ifdef NEEDTOPORT
6463		EPRINT(0, "Invalid PC %d!!", pc);
6464#endif /* NEEDTOPORT */
6465		break;
6466	}
6467	return (0);
6468}
6469
6470
6471static int
6472ctl_do_mode_select(union ctl_io *io)
6473{
6474	struct scsi_mode_page_header *page_header;
6475	struct ctl_page_index *page_index;
6476	struct ctl_scsiio *ctsio;
6477	int control_dev, page_len;
6478	int page_len_offset, page_len_size;
6479	union ctl_modepage_info *modepage_info;
6480	struct ctl_lun *lun;
6481	int *len_left, *len_used;
6482	int retval, i;
6483
6484	ctsio = &io->scsiio;
6485	page_index = NULL;
6486	page_len = 0;
6487	retval = CTL_RETVAL_COMPLETE;
6488
6489	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6490
6491	if (lun->be_lun->lun_type != T_DIRECT)
6492		control_dev = 1;
6493	else
6494		control_dev = 0;
6495
6496	modepage_info = (union ctl_modepage_info *)
6497		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6498	len_left = &modepage_info->header.len_left;
6499	len_used = &modepage_info->header.len_used;
6500
6501do_next_page:
6502
6503	page_header = (struct scsi_mode_page_header *)
6504		(ctsio->kern_data_ptr + *len_used);
6505
6506	if (*len_left == 0) {
6507		free(ctsio->kern_data_ptr, M_CTL);
6508		ctl_set_success(ctsio);
6509		ctl_done((union ctl_io *)ctsio);
6510		return (CTL_RETVAL_COMPLETE);
6511	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6512
6513		free(ctsio->kern_data_ptr, M_CTL);
6514		ctl_set_param_len_error(ctsio);
6515		ctl_done((union ctl_io *)ctsio);
6516		return (CTL_RETVAL_COMPLETE);
6517
6518	} else if ((page_header->page_code & SMPH_SPF)
6519		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6520
6521		free(ctsio->kern_data_ptr, M_CTL);
6522		ctl_set_param_len_error(ctsio);
6523		ctl_done((union ctl_io *)ctsio);
6524		return (CTL_RETVAL_COMPLETE);
6525	}
6526
6527
6528	/*
6529	 * XXX KDM should we do something with the block descriptor?
6530	 */
6531	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6532
6533		if ((control_dev != 0)
6534		 && (lun->mode_pages.index[i].page_flags &
6535		     CTL_PAGE_FLAG_DISK_ONLY))
6536			continue;
6537
6538		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6539		    (page_header->page_code & SMPH_PC_MASK))
6540			continue;
6541
6542		/*
6543		 * If neither page has a subpage code, then we've got a
6544		 * match.
6545		 */
6546		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6547		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6548			page_index = &lun->mode_pages.index[i];
6549			page_len = page_header->page_length;
6550			break;
6551		}
6552
6553		/*
6554		 * If both pages have subpages, then the subpage numbers
6555		 * have to match.
6556		 */
6557		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6558		  && (page_header->page_code & SMPH_SPF)) {
6559			struct scsi_mode_page_header_sp *sph;
6560
6561			sph = (struct scsi_mode_page_header_sp *)page_header;
6562
6563			if (lun->mode_pages.index[i].subpage ==
6564			    sph->subpage) {
6565				page_index = &lun->mode_pages.index[i];
6566				page_len = scsi_2btoul(sph->page_length);
6567				break;
6568			}
6569		}
6570	}
6571
6572	/*
6573	 * If we couldn't find the page, or if we don't have a mode select
6574	 * handler for it, send back an error to the user.
6575	 */
6576	if ((page_index == NULL)
6577	 || (page_index->select_handler == NULL)) {
6578		ctl_set_invalid_field(ctsio,
6579				      /*sks_valid*/ 1,
6580				      /*command*/ 0,
6581				      /*field*/ *len_used,
6582				      /*bit_valid*/ 0,
6583				      /*bit*/ 0);
6584		free(ctsio->kern_data_ptr, M_CTL);
6585		ctl_done((union ctl_io *)ctsio);
6586		return (CTL_RETVAL_COMPLETE);
6587	}
6588
6589	if (page_index->page_code & SMPH_SPF) {
6590		page_len_offset = 2;
6591		page_len_size = 2;
6592	} else {
6593		page_len_size = 1;
6594		page_len_offset = 1;
6595	}
6596
6597	/*
6598	 * If the length the initiator gives us isn't the one we specify in
6599	 * the mode page header, or if they didn't specify enough data in
6600	 * the CDB to avoid truncating this page, kick out the request.
6601	 */
6602	if ((page_len != (page_index->page_len - page_len_offset -
6603			  page_len_size))
6604	 || (*len_left < page_index->page_len)) {
6605
6606
6607		ctl_set_invalid_field(ctsio,
6608				      /*sks_valid*/ 1,
6609				      /*command*/ 0,
6610				      /*field*/ *len_used + page_len_offset,
6611				      /*bit_valid*/ 0,
6612				      /*bit*/ 0);
6613		free(ctsio->kern_data_ptr, M_CTL);
6614		ctl_done((union ctl_io *)ctsio);
6615		return (CTL_RETVAL_COMPLETE);
6616	}
6617
6618	/*
6619	 * Run through the mode page, checking to make sure that the bits
6620	 * the user changed are actually legal for him to change.
6621	 */
6622	for (i = 0; i < page_index->page_len; i++) {
6623		uint8_t *user_byte, *change_mask, *current_byte;
6624		int bad_bit;
6625		int j;
6626
6627		user_byte = (uint8_t *)page_header + i;
6628		change_mask = page_index->page_data +
6629			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6630		current_byte = page_index->page_data +
6631			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6632
6633		/*
6634		 * Check to see whether the user set any bits in this byte
6635		 * that he is not allowed to set.
6636		 */
6637		if ((*user_byte & ~(*change_mask)) ==
6638		    (*current_byte & ~(*change_mask)))
6639			continue;
6640
6641		/*
6642		 * Go through bit by bit to determine which one is illegal.
6643		 */
6644		bad_bit = 0;
6645		for (j = 7; j >= 0; j--) {
6646			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6647			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6648				bad_bit = i;
6649				break;
6650			}
6651		}
6652		ctl_set_invalid_field(ctsio,
6653				      /*sks_valid*/ 1,
6654				      /*command*/ 0,
6655				      /*field*/ *len_used + i,
6656				      /*bit_valid*/ 1,
6657				      /*bit*/ bad_bit);
6658		free(ctsio->kern_data_ptr, M_CTL);
6659		ctl_done((union ctl_io *)ctsio);
6660		return (CTL_RETVAL_COMPLETE);
6661	}
6662
6663	/*
6664	 * Decrement these before we call the page handler, since we may
6665	 * end up getting called back one way or another before the handler
6666	 * returns to this context.
6667	 */
6668	*len_left -= page_index->page_len;
6669	*len_used += page_index->page_len;
6670
6671	retval = page_index->select_handler(ctsio, page_index,
6672					    (uint8_t *)page_header);
6673
6674	/*
6675	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6676	 * wait until this queued command completes to finish processing
6677	 * the mode page.  If it returns anything other than
6678	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6679	 * already set the sense information, freed the data pointer, and
6680	 * completed the io for us.
6681	 */
6682	if (retval != CTL_RETVAL_COMPLETE)
6683		goto bailout_no_done;
6684
6685	/*
6686	 * If the initiator sent us more than one page, parse the next one.
6687	 */
6688	if (*len_left > 0)
6689		goto do_next_page;
6690
6691	ctl_set_success(ctsio);
6692	free(ctsio->kern_data_ptr, M_CTL);
6693	ctl_done((union ctl_io *)ctsio);
6694
6695bailout_no_done:
6696
6697	return (CTL_RETVAL_COMPLETE);
6698
6699}
6700
6701int
6702ctl_mode_select(struct ctl_scsiio *ctsio)
6703{
6704	int param_len, pf, sp;
6705	int header_size, bd_len;
6706	int len_left, len_used;
6707	struct ctl_page_index *page_index;
6708	struct ctl_lun *lun;
6709	int control_dev, page_len;
6710	union ctl_modepage_info *modepage_info;
6711	int retval;
6712
6713	pf = 0;
6714	sp = 0;
6715	page_len = 0;
6716	len_used = 0;
6717	len_left = 0;
6718	retval = 0;
6719	bd_len = 0;
6720	page_index = NULL;
6721
6722	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6723
6724	if (lun->be_lun->lun_type != T_DIRECT)
6725		control_dev = 1;
6726	else
6727		control_dev = 0;
6728
6729	switch (ctsio->cdb[0]) {
6730	case MODE_SELECT_6: {
6731		struct scsi_mode_select_6 *cdb;
6732
6733		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6734
6735		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6736		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6737
6738		param_len = cdb->length;
6739		header_size = sizeof(struct scsi_mode_header_6);
6740		break;
6741	}
6742	case MODE_SELECT_10: {
6743		struct scsi_mode_select_10 *cdb;
6744
6745		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6746
6747		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6748		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6749
6750		param_len = scsi_2btoul(cdb->length);
6751		header_size = sizeof(struct scsi_mode_header_10);
6752		break;
6753	}
6754	default:
6755		ctl_set_invalid_opcode(ctsio);
6756		ctl_done((union ctl_io *)ctsio);
6757		return (CTL_RETVAL_COMPLETE);
6758		break; /* NOTREACHED */
6759	}
6760
6761	/*
6762	 * From SPC-3:
6763	 * "A parameter list length of zero indicates that the Data-Out Buffer
6764	 * shall be empty. This condition shall not be considered as an error."
6765	 */
6766	if (param_len == 0) {
6767		ctl_set_success(ctsio);
6768		ctl_done((union ctl_io *)ctsio);
6769		return (CTL_RETVAL_COMPLETE);
6770	}
6771
6772	/*
6773	 * Since we'll hit this the first time through, prior to
6774	 * allocation, we don't need to free a data buffer here.
6775	 */
6776	if (param_len < header_size) {
6777		ctl_set_param_len_error(ctsio);
6778		ctl_done((union ctl_io *)ctsio);
6779		return (CTL_RETVAL_COMPLETE);
6780	}
6781
6782	/*
6783	 * Allocate the data buffer and grab the user's data.  In theory,
6784	 * we shouldn't have to sanity check the parameter list length here
6785	 * because the maximum size is 64K.  We should be able to malloc
6786	 * that much without too many problems.
6787	 */
6788	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6789		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6790		ctsio->kern_data_len = param_len;
6791		ctsio->kern_total_len = param_len;
6792		ctsio->kern_data_resid = 0;
6793		ctsio->kern_rel_offset = 0;
6794		ctsio->kern_sg_entries = 0;
6795		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6796		ctsio->be_move_done = ctl_config_move_done;
6797		ctl_datamove((union ctl_io *)ctsio);
6798
6799		return (CTL_RETVAL_COMPLETE);
6800	}
6801
6802	switch (ctsio->cdb[0]) {
6803	case MODE_SELECT_6: {
6804		struct scsi_mode_header_6 *mh6;
6805
6806		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6807		bd_len = mh6->blk_desc_len;
6808		break;
6809	}
6810	case MODE_SELECT_10: {
6811		struct scsi_mode_header_10 *mh10;
6812
6813		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6814		bd_len = scsi_2btoul(mh10->blk_desc_len);
6815		break;
6816	}
6817	default:
6818		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6819		break;
6820	}
6821
6822	if (param_len < (header_size + bd_len)) {
6823		free(ctsio->kern_data_ptr, M_CTL);
6824		ctl_set_param_len_error(ctsio);
6825		ctl_done((union ctl_io *)ctsio);
6826		return (CTL_RETVAL_COMPLETE);
6827	}
6828
6829	/*
6830	 * Set the IO_CONT flag, so that if this I/O gets passed to
6831	 * ctl_config_write_done(), it'll get passed back to
6832	 * ctl_do_mode_select() for further processing, or completion if
6833	 * we're all done.
6834	 */
6835	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6836	ctsio->io_cont = ctl_do_mode_select;
6837
6838	modepage_info = (union ctl_modepage_info *)
6839		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6840
6841	memset(modepage_info, 0, sizeof(*modepage_info));
6842
6843	len_left = param_len - header_size - bd_len;
6844	len_used = header_size + bd_len;
6845
6846	modepage_info->header.len_left = len_left;
6847	modepage_info->header.len_used = len_used;
6848
6849	return (ctl_do_mode_select((union ctl_io *)ctsio));
6850}
6851
6852int
6853ctl_mode_sense(struct ctl_scsiio *ctsio)
6854{
6855	struct ctl_lun *lun;
6856	int pc, page_code, dbd, llba, subpage;
6857	int alloc_len, page_len, header_len, total_len;
6858	struct scsi_mode_block_descr *block_desc;
6859	struct ctl_page_index *page_index;
6860	int control_dev;
6861
6862	dbd = 0;
6863	llba = 0;
6864	block_desc = NULL;
6865	page_index = NULL;
6866
6867	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6868
6869	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6870
6871	if (lun->be_lun->lun_type != T_DIRECT)
6872		control_dev = 1;
6873	else
6874		control_dev = 0;
6875
6876	if (lun->flags & CTL_LUN_PR_RESERVED) {
6877		uint32_t residx;
6878
6879		/*
6880		 * XXX KDM need a lock here.
6881		 */
6882		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6883		if ((lun->res_type == SPR_TYPE_EX_AC
6884		  && residx != lun->pr_res_idx)
6885		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6886		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6887		  && lun->pr_keys[residx] == 0)) {
6888			ctl_set_reservation_conflict(ctsio);
6889			ctl_done((union ctl_io *)ctsio);
6890			return (CTL_RETVAL_COMPLETE);
6891		}
6892	}
6893
6894	switch (ctsio->cdb[0]) {
6895	case MODE_SENSE_6: {
6896		struct scsi_mode_sense_6 *cdb;
6897
6898		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6899
6900		header_len = sizeof(struct scsi_mode_hdr_6);
6901		if (cdb->byte2 & SMS_DBD)
6902			dbd = 1;
6903		else
6904			header_len += sizeof(struct scsi_mode_block_descr);
6905
6906		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6907		page_code = cdb->page & SMS_PAGE_CODE;
6908		subpage = cdb->subpage;
6909		alloc_len = cdb->length;
6910		break;
6911	}
6912	case MODE_SENSE_10: {
6913		struct scsi_mode_sense_10 *cdb;
6914
6915		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6916
6917		header_len = sizeof(struct scsi_mode_hdr_10);
6918
6919		if (cdb->byte2 & SMS_DBD)
6920			dbd = 1;
6921		else
6922			header_len += sizeof(struct scsi_mode_block_descr);
6923		if (cdb->byte2 & SMS10_LLBAA)
6924			llba = 1;
6925		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6926		page_code = cdb->page & SMS_PAGE_CODE;
6927		subpage = cdb->subpage;
6928		alloc_len = scsi_2btoul(cdb->length);
6929		break;
6930	}
6931	default:
6932		ctl_set_invalid_opcode(ctsio);
6933		ctl_done((union ctl_io *)ctsio);
6934		return (CTL_RETVAL_COMPLETE);
6935		break; /* NOTREACHED */
6936	}
6937
6938	/*
6939	 * We have to make a first pass through to calculate the size of
6940	 * the pages that match the user's query.  Then we allocate enough
6941	 * memory to hold it, and actually copy the data into the buffer.
6942	 */
6943	switch (page_code) {
6944	case SMS_ALL_PAGES_PAGE: {
6945		int i;
6946
6947		page_len = 0;
6948
6949		/*
6950		 * At the moment, values other than 0 and 0xff here are
6951		 * reserved according to SPC-3.
6952		 */
6953		if ((subpage != SMS_SUBPAGE_PAGE_0)
6954		 && (subpage != SMS_SUBPAGE_ALL)) {
6955			ctl_set_invalid_field(ctsio,
6956					      /*sks_valid*/ 1,
6957					      /*command*/ 1,
6958					      /*field*/ 3,
6959					      /*bit_valid*/ 0,
6960					      /*bit*/ 0);
6961			ctl_done((union ctl_io *)ctsio);
6962			return (CTL_RETVAL_COMPLETE);
6963		}
6964
6965		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6966			if ((control_dev != 0)
6967			 && (lun->mode_pages.index[i].page_flags &
6968			     CTL_PAGE_FLAG_DISK_ONLY))
6969				continue;
6970
6971			/*
6972			 * We don't use this subpage if the user didn't
6973			 * request all subpages.
6974			 */
6975			if ((lun->mode_pages.index[i].subpage != 0)
6976			 && (subpage == SMS_SUBPAGE_PAGE_0))
6977				continue;
6978
6979#if 0
6980			printf("found page %#x len %d\n",
6981			       lun->mode_pages.index[i].page_code &
6982			       SMPH_PC_MASK,
6983			       lun->mode_pages.index[i].page_len);
6984#endif
6985			page_len += lun->mode_pages.index[i].page_len;
6986		}
6987		break;
6988	}
6989	default: {
6990		int i;
6991
6992		page_len = 0;
6993
6994		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6995			/* Look for the right page code */
6996			if ((lun->mode_pages.index[i].page_code &
6997			     SMPH_PC_MASK) != page_code)
6998				continue;
6999
7000			/* Look for the right subpage or the subpage wildcard*/
7001			if ((lun->mode_pages.index[i].subpage != subpage)
7002			 && (subpage != SMS_SUBPAGE_ALL))
7003				continue;
7004
7005			/* Make sure the page is supported for this dev type */
7006			if ((control_dev != 0)
7007			 && (lun->mode_pages.index[i].page_flags &
7008			     CTL_PAGE_FLAG_DISK_ONLY))
7009				continue;
7010
7011#if 0
7012			printf("found page %#x len %d\n",
7013			       lun->mode_pages.index[i].page_code &
7014			       SMPH_PC_MASK,
7015			       lun->mode_pages.index[i].page_len);
7016#endif
7017
7018			page_len += lun->mode_pages.index[i].page_len;
7019		}
7020
7021		if (page_len == 0) {
7022			ctl_set_invalid_field(ctsio,
7023					      /*sks_valid*/ 1,
7024					      /*command*/ 1,
7025					      /*field*/ 2,
7026					      /*bit_valid*/ 1,
7027					      /*bit*/ 5);
7028			ctl_done((union ctl_io *)ctsio);
7029			return (CTL_RETVAL_COMPLETE);
7030		}
7031		break;
7032	}
7033	}
7034
7035	total_len = header_len + page_len;
7036#if 0
7037	printf("header_len = %d, page_len = %d, total_len = %d\n",
7038	       header_len, page_len, total_len);
7039#endif
7040
7041	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7042	ctsio->kern_sg_entries = 0;
7043	ctsio->kern_data_resid = 0;
7044	ctsio->kern_rel_offset = 0;
7045	if (total_len < alloc_len) {
7046		ctsio->residual = alloc_len - total_len;
7047		ctsio->kern_data_len = total_len;
7048		ctsio->kern_total_len = total_len;
7049	} else {
7050		ctsio->residual = 0;
7051		ctsio->kern_data_len = alloc_len;
7052		ctsio->kern_total_len = alloc_len;
7053	}
7054
7055	switch (ctsio->cdb[0]) {
7056	case MODE_SENSE_6: {
7057		struct scsi_mode_hdr_6 *header;
7058
7059		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7060
7061		header->datalen = ctl_min(total_len - 1, 254);
7062		if (control_dev == 0) {
7063			header->dev_specific = 0x10; /* DPOFUA */
7064			if ((lun->flags & CTL_LUN_READONLY) ||
7065			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7066			    .eca_and_aen & SCP_SWP) != 0)
7067				    header->dev_specific |= 0x80; /* WP */
7068		}
7069		if (dbd)
7070			header->block_descr_len = 0;
7071		else
7072			header->block_descr_len =
7073				sizeof(struct scsi_mode_block_descr);
7074		block_desc = (struct scsi_mode_block_descr *)&header[1];
7075		break;
7076	}
7077	case MODE_SENSE_10: {
7078		struct scsi_mode_hdr_10 *header;
7079		int datalen;
7080
7081		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7082
7083		datalen = ctl_min(total_len - 2, 65533);
7084		scsi_ulto2b(datalen, header->datalen);
7085		if (control_dev == 0) {
7086			header->dev_specific = 0x10; /* DPOFUA */
7087			if ((lun->flags & CTL_LUN_READONLY) ||
7088			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7089			    .eca_and_aen & SCP_SWP) != 0)
7090				    header->dev_specific |= 0x80; /* WP */
7091		}
7092		if (dbd)
7093			scsi_ulto2b(0, header->block_descr_len);
7094		else
7095			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7096				    header->block_descr_len);
7097		block_desc = (struct scsi_mode_block_descr *)&header[1];
7098		break;
7099	}
7100	default:
7101		panic("invalid CDB type %#x", ctsio->cdb[0]);
7102		break; /* NOTREACHED */
7103	}
7104
7105	/*
7106	 * If we've got a disk, use its blocksize in the block
7107	 * descriptor.  Otherwise, just set it to 0.
7108	 */
7109	if (dbd == 0) {
7110		if (control_dev == 0)
7111			scsi_ulto3b(lun->be_lun->blocksize,
7112				    block_desc->block_len);
7113		else
7114			scsi_ulto3b(0, block_desc->block_len);
7115	}
7116
7117	switch (page_code) {
7118	case SMS_ALL_PAGES_PAGE: {
7119		int i, data_used;
7120
7121		data_used = header_len;
7122		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7123			struct ctl_page_index *page_index;
7124
7125			page_index = &lun->mode_pages.index[i];
7126
7127			if ((control_dev != 0)
7128			 && (page_index->page_flags &
7129			    CTL_PAGE_FLAG_DISK_ONLY))
7130				continue;
7131
7132			/*
7133			 * We don't use this subpage if the user didn't
7134			 * request all subpages.  We already checked (above)
7135			 * to make sure the user only specified a subpage
7136			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7137			 */
7138			if ((page_index->subpage != 0)
7139			 && (subpage == SMS_SUBPAGE_PAGE_0))
7140				continue;
7141
7142			/*
7143			 * Call the handler, if it exists, to update the
7144			 * page to the latest values.
7145			 */
7146			if (page_index->sense_handler != NULL)
7147				page_index->sense_handler(ctsio, page_index,pc);
7148
7149			memcpy(ctsio->kern_data_ptr + data_used,
7150			       page_index->page_data +
7151			       (page_index->page_len * pc),
7152			       page_index->page_len);
7153			data_used += page_index->page_len;
7154		}
7155		break;
7156	}
7157	default: {
7158		int i, data_used;
7159
7160		data_used = header_len;
7161
7162		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7163			struct ctl_page_index *page_index;
7164
7165			page_index = &lun->mode_pages.index[i];
7166
7167			/* Look for the right page code */
7168			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7169				continue;
7170
7171			/* Look for the right subpage or the subpage wildcard*/
7172			if ((page_index->subpage != subpage)
7173			 && (subpage != SMS_SUBPAGE_ALL))
7174				continue;
7175
7176			/* Make sure the page is supported for this dev type */
7177			if ((control_dev != 0)
7178			 && (page_index->page_flags &
7179			     CTL_PAGE_FLAG_DISK_ONLY))
7180				continue;
7181
7182			/*
7183			 * Call the handler, if it exists, to update the
7184			 * page to the latest values.
7185			 */
7186			if (page_index->sense_handler != NULL)
7187				page_index->sense_handler(ctsio, page_index,pc);
7188
7189			memcpy(ctsio->kern_data_ptr + data_used,
7190			       page_index->page_data +
7191			       (page_index->page_len * pc),
7192			       page_index->page_len);
7193			data_used += page_index->page_len;
7194		}
7195		break;
7196	}
7197	}
7198
7199	ctsio->scsi_status = SCSI_STATUS_OK;
7200
7201	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7202	ctsio->be_move_done = ctl_config_move_done;
7203	ctl_datamove((union ctl_io *)ctsio);
7204
7205	return (CTL_RETVAL_COMPLETE);
7206}
7207
7208int
7209ctl_read_capacity(struct ctl_scsiio *ctsio)
7210{
7211	struct scsi_read_capacity *cdb;
7212	struct scsi_read_capacity_data *data;
7213	struct ctl_lun *lun;
7214	uint32_t lba;
7215
7216	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7217
7218	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7219
7220	lba = scsi_4btoul(cdb->addr);
7221	if (((cdb->pmi & SRC_PMI) == 0)
7222	 && (lba != 0)) {
7223		ctl_set_invalid_field(/*ctsio*/ ctsio,
7224				      /*sks_valid*/ 1,
7225				      /*command*/ 1,
7226				      /*field*/ 2,
7227				      /*bit_valid*/ 0,
7228				      /*bit*/ 0);
7229		ctl_done((union ctl_io *)ctsio);
7230		return (CTL_RETVAL_COMPLETE);
7231	}
7232
7233	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7234
7235	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7236	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7237	ctsio->residual = 0;
7238	ctsio->kern_data_len = sizeof(*data);
7239	ctsio->kern_total_len = sizeof(*data);
7240	ctsio->kern_data_resid = 0;
7241	ctsio->kern_rel_offset = 0;
7242	ctsio->kern_sg_entries = 0;
7243
7244	/*
7245	 * If the maximum LBA is greater than 0xfffffffe, the user must
7246	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7247	 * serivce action set.
7248	 */
7249	if (lun->be_lun->maxlba > 0xfffffffe)
7250		scsi_ulto4b(0xffffffff, data->addr);
7251	else
7252		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7253
7254	/*
7255	 * XXX KDM this may not be 512 bytes...
7256	 */
7257	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7258
7259	ctsio->scsi_status = SCSI_STATUS_OK;
7260
7261	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7262	ctsio->be_move_done = ctl_config_move_done;
7263	ctl_datamove((union ctl_io *)ctsio);
7264
7265	return (CTL_RETVAL_COMPLETE);
7266}
7267
7268int
7269ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7270{
7271	struct scsi_read_capacity_16 *cdb;
7272	struct scsi_read_capacity_data_long *data;
7273	struct ctl_lun *lun;
7274	uint64_t lba;
7275	uint32_t alloc_len;
7276
7277	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7278
7279	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7280
7281	alloc_len = scsi_4btoul(cdb->alloc_len);
7282	lba = scsi_8btou64(cdb->addr);
7283
7284	if ((cdb->reladr & SRC16_PMI)
7285	 && (lba != 0)) {
7286		ctl_set_invalid_field(/*ctsio*/ ctsio,
7287				      /*sks_valid*/ 1,
7288				      /*command*/ 1,
7289				      /*field*/ 2,
7290				      /*bit_valid*/ 0,
7291				      /*bit*/ 0);
7292		ctl_done((union ctl_io *)ctsio);
7293		return (CTL_RETVAL_COMPLETE);
7294	}
7295
7296	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7297
7298	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7299	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7300
7301	if (sizeof(*data) < alloc_len) {
7302		ctsio->residual = alloc_len - sizeof(*data);
7303		ctsio->kern_data_len = sizeof(*data);
7304		ctsio->kern_total_len = sizeof(*data);
7305	} else {
7306		ctsio->residual = 0;
7307		ctsio->kern_data_len = alloc_len;
7308		ctsio->kern_total_len = alloc_len;
7309	}
7310	ctsio->kern_data_resid = 0;
7311	ctsio->kern_rel_offset = 0;
7312	ctsio->kern_sg_entries = 0;
7313
7314	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7315	/* XXX KDM this may not be 512 bytes... */
7316	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7317	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7318	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7319	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7320		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7321
7322	ctsio->scsi_status = SCSI_STATUS_OK;
7323
7324	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7325	ctsio->be_move_done = ctl_config_move_done;
7326	ctl_datamove((union ctl_io *)ctsio);
7327
7328	return (CTL_RETVAL_COMPLETE);
7329}
7330
7331int
7332ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7333{
7334	struct scsi_maintenance_in *cdb;
7335	int retval;
7336	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7337	int num_target_port_groups, num_target_ports, single;
7338	struct ctl_lun *lun;
7339	struct ctl_softc *softc;
7340	struct ctl_port *port;
7341	struct scsi_target_group_data *rtg_ptr;
7342	struct scsi_target_group_data_extended *rtg_ext_ptr;
7343	struct scsi_target_port_group_descriptor *tpg_desc;
7344
7345	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7346
7347	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7348	softc = control_softc;
7349	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7350
7351	retval = CTL_RETVAL_COMPLETE;
7352
7353	switch (cdb->byte2 & STG_PDF_MASK) {
7354	case STG_PDF_LENGTH:
7355		ext = 0;
7356		break;
7357	case STG_PDF_EXTENDED:
7358		ext = 1;
7359		break;
7360	default:
7361		ctl_set_invalid_field(/*ctsio*/ ctsio,
7362				      /*sks_valid*/ 1,
7363				      /*command*/ 1,
7364				      /*field*/ 2,
7365				      /*bit_valid*/ 1,
7366				      /*bit*/ 5);
7367		ctl_done((union ctl_io *)ctsio);
7368		return(retval);
7369	}
7370
7371	single = ctl_is_single;
7372	if (single)
7373		num_target_port_groups = 1;
7374	else
7375		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7376	num_target_ports = 0;
7377	mtx_lock(&softc->ctl_lock);
7378	STAILQ_FOREACH(port, &softc->port_list, links) {
7379		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7380			continue;
7381		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7382			continue;
7383		num_target_ports++;
7384	}
7385	mtx_unlock(&softc->ctl_lock);
7386
7387	if (ext)
7388		total_len = sizeof(struct scsi_target_group_data_extended);
7389	else
7390		total_len = sizeof(struct scsi_target_group_data);
7391	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7392		num_target_port_groups +
7393	    sizeof(struct scsi_target_port_descriptor) *
7394		num_target_ports * num_target_port_groups;
7395
7396	alloc_len = scsi_4btoul(cdb->length);
7397
7398	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7399
7400	ctsio->kern_sg_entries = 0;
7401
7402	if (total_len < alloc_len) {
7403		ctsio->residual = alloc_len - total_len;
7404		ctsio->kern_data_len = total_len;
7405		ctsio->kern_total_len = total_len;
7406	} else {
7407		ctsio->residual = 0;
7408		ctsio->kern_data_len = alloc_len;
7409		ctsio->kern_total_len = alloc_len;
7410	}
7411	ctsio->kern_data_resid = 0;
7412	ctsio->kern_rel_offset = 0;
7413
7414	if (ext) {
7415		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7416		    ctsio->kern_data_ptr;
7417		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7418		rtg_ext_ptr->format_type = 0x10;
7419		rtg_ext_ptr->implicit_transition_time = 0;
7420		tpg_desc = &rtg_ext_ptr->groups[0];
7421	} else {
7422		rtg_ptr = (struct scsi_target_group_data *)
7423		    ctsio->kern_data_ptr;
7424		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7425		tpg_desc = &rtg_ptr->groups[0];
7426	}
7427
7428	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7429	mtx_lock(&softc->ctl_lock);
7430	for (g = 0; g < num_target_port_groups; g++) {
7431		if (g == pg)
7432			tpg_desc->pref_state = TPG_PRIMARY |
7433			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7434		else
7435			tpg_desc->pref_state =
7436			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7437		tpg_desc->support = TPG_AO_SUP;
7438		if (!single)
7439			tpg_desc->support |= TPG_AN_SUP;
7440		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7441		tpg_desc->status = TPG_IMPLICIT;
7442		pc = 0;
7443		STAILQ_FOREACH(port, &softc->port_list, links) {
7444			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7445				continue;
7446			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7447			    CTL_MAX_LUNS)
7448				continue;
7449			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7450			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7451			    relative_target_port_identifier);
7452			pc++;
7453		}
7454		tpg_desc->target_port_count = pc;
7455		tpg_desc = (struct scsi_target_port_group_descriptor *)
7456		    &tpg_desc->descriptors[pc];
7457	}
7458	mtx_unlock(&softc->ctl_lock);
7459
7460	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7461	ctsio->be_move_done = ctl_config_move_done;
7462
7463	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7464			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7465			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7466			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7467			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7468
7469	ctl_datamove((union ctl_io *)ctsio);
7470	return(retval);
7471}
7472
7473int
7474ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7475{
7476	struct ctl_lun *lun;
7477	struct scsi_report_supported_opcodes *cdb;
7478	const struct ctl_cmd_entry *entry, *sentry;
7479	struct scsi_report_supported_opcodes_all *all;
7480	struct scsi_report_supported_opcodes_descr *descr;
7481	struct scsi_report_supported_opcodes_one *one;
7482	int retval;
7483	int alloc_len, total_len;
7484	int opcode, service_action, i, j, num;
7485
7486	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7487
7488	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7489	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7490
7491	retval = CTL_RETVAL_COMPLETE;
7492
7493	opcode = cdb->requested_opcode;
7494	service_action = scsi_2btoul(cdb->requested_service_action);
7495	switch (cdb->options & RSO_OPTIONS_MASK) {
7496	case RSO_OPTIONS_ALL:
7497		num = 0;
7498		for (i = 0; i < 256; i++) {
7499			entry = &ctl_cmd_table[i];
7500			if (entry->flags & CTL_CMD_FLAG_SA5) {
7501				for (j = 0; j < 32; j++) {
7502					sentry = &((const struct ctl_cmd_entry *)
7503					    entry->execute)[j];
7504					if (ctl_cmd_applicable(
7505					    lun->be_lun->lun_type, sentry))
7506						num++;
7507				}
7508			} else {
7509				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7510				    entry))
7511					num++;
7512			}
7513		}
7514		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7515		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7516		break;
7517	case RSO_OPTIONS_OC:
7518		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7519			ctl_set_invalid_field(/*ctsio*/ ctsio,
7520					      /*sks_valid*/ 1,
7521					      /*command*/ 1,
7522					      /*field*/ 2,
7523					      /*bit_valid*/ 1,
7524					      /*bit*/ 2);
7525			ctl_done((union ctl_io *)ctsio);
7526			return (CTL_RETVAL_COMPLETE);
7527		}
7528		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7529		break;
7530	case RSO_OPTIONS_OC_SA:
7531		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7532		    service_action >= 32) {
7533			ctl_set_invalid_field(/*ctsio*/ ctsio,
7534					      /*sks_valid*/ 1,
7535					      /*command*/ 1,
7536					      /*field*/ 2,
7537					      /*bit_valid*/ 1,
7538					      /*bit*/ 2);
7539			ctl_done((union ctl_io *)ctsio);
7540			return (CTL_RETVAL_COMPLETE);
7541		}
7542		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7543		break;
7544	default:
7545		ctl_set_invalid_field(/*ctsio*/ ctsio,
7546				      /*sks_valid*/ 1,
7547				      /*command*/ 1,
7548				      /*field*/ 2,
7549				      /*bit_valid*/ 1,
7550				      /*bit*/ 2);
7551		ctl_done((union ctl_io *)ctsio);
7552		return (CTL_RETVAL_COMPLETE);
7553	}
7554
7555	alloc_len = scsi_4btoul(cdb->length);
7556
7557	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7558
7559	ctsio->kern_sg_entries = 0;
7560
7561	if (total_len < alloc_len) {
7562		ctsio->residual = alloc_len - total_len;
7563		ctsio->kern_data_len = total_len;
7564		ctsio->kern_total_len = total_len;
7565	} else {
7566		ctsio->residual = 0;
7567		ctsio->kern_data_len = alloc_len;
7568		ctsio->kern_total_len = alloc_len;
7569	}
7570	ctsio->kern_data_resid = 0;
7571	ctsio->kern_rel_offset = 0;
7572
7573	switch (cdb->options & RSO_OPTIONS_MASK) {
7574	case RSO_OPTIONS_ALL:
7575		all = (struct scsi_report_supported_opcodes_all *)
7576		    ctsio->kern_data_ptr;
7577		num = 0;
7578		for (i = 0; i < 256; i++) {
7579			entry = &ctl_cmd_table[i];
7580			if (entry->flags & CTL_CMD_FLAG_SA5) {
7581				for (j = 0; j < 32; j++) {
7582					sentry = &((const struct ctl_cmd_entry *)
7583					    entry->execute)[j];
7584					if (!ctl_cmd_applicable(
7585					    lun->be_lun->lun_type, sentry))
7586						continue;
7587					descr = &all->descr[num++];
7588					descr->opcode = i;
7589					scsi_ulto2b(j, descr->service_action);
7590					descr->flags = RSO_SERVACTV;
7591					scsi_ulto2b(sentry->length,
7592					    descr->cdb_length);
7593				}
7594			} else {
7595				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7596				    entry))
7597					continue;
7598				descr = &all->descr[num++];
7599				descr->opcode = i;
7600				scsi_ulto2b(0, descr->service_action);
7601				descr->flags = 0;
7602				scsi_ulto2b(entry->length, descr->cdb_length);
7603			}
7604		}
7605		scsi_ulto4b(
7606		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7607		    all->length);
7608		break;
7609	case RSO_OPTIONS_OC:
7610		one = (struct scsi_report_supported_opcodes_one *)
7611		    ctsio->kern_data_ptr;
7612		entry = &ctl_cmd_table[opcode];
7613		goto fill_one;
7614	case RSO_OPTIONS_OC_SA:
7615		one = (struct scsi_report_supported_opcodes_one *)
7616		    ctsio->kern_data_ptr;
7617		entry = &ctl_cmd_table[opcode];
7618		entry = &((const struct ctl_cmd_entry *)
7619		    entry->execute)[service_action];
7620fill_one:
7621		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7622			one->support = 3;
7623			scsi_ulto2b(entry->length, one->cdb_length);
7624			one->cdb_usage[0] = opcode;
7625			memcpy(&one->cdb_usage[1], entry->usage,
7626			    entry->length - 1);
7627		} else
7628			one->support = 1;
7629		break;
7630	}
7631
7632	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7633	ctsio->be_move_done = ctl_config_move_done;
7634
7635	ctl_datamove((union ctl_io *)ctsio);
7636	return(retval);
7637}
7638
7639int
7640ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7641{
7642	struct ctl_lun *lun;
7643	struct scsi_report_supported_tmf *cdb;
7644	struct scsi_report_supported_tmf_data *data;
7645	int retval;
7646	int alloc_len, total_len;
7647
7648	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7649
7650	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7651	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7652
7653	retval = CTL_RETVAL_COMPLETE;
7654
7655	total_len = sizeof(struct scsi_report_supported_tmf_data);
7656	alloc_len = scsi_4btoul(cdb->length);
7657
7658	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7659
7660	ctsio->kern_sg_entries = 0;
7661
7662	if (total_len < alloc_len) {
7663		ctsio->residual = alloc_len - total_len;
7664		ctsio->kern_data_len = total_len;
7665		ctsio->kern_total_len = total_len;
7666	} else {
7667		ctsio->residual = 0;
7668		ctsio->kern_data_len = alloc_len;
7669		ctsio->kern_total_len = alloc_len;
7670	}
7671	ctsio->kern_data_resid = 0;
7672	ctsio->kern_rel_offset = 0;
7673
7674	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7675	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7676	data->byte2 |= RST_ITNRS;
7677
7678	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7679	ctsio->be_move_done = ctl_config_move_done;
7680
7681	ctl_datamove((union ctl_io *)ctsio);
7682	return (retval);
7683}
7684
7685int
7686ctl_report_timestamp(struct ctl_scsiio *ctsio)
7687{
7688	struct ctl_lun *lun;
7689	struct scsi_report_timestamp *cdb;
7690	struct scsi_report_timestamp_data *data;
7691	struct timeval tv;
7692	int64_t timestamp;
7693	int retval;
7694	int alloc_len, total_len;
7695
7696	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7697
7698	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7699	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7700
7701	retval = CTL_RETVAL_COMPLETE;
7702
7703	total_len = sizeof(struct scsi_report_timestamp_data);
7704	alloc_len = scsi_4btoul(cdb->length);
7705
7706	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7707
7708	ctsio->kern_sg_entries = 0;
7709
7710	if (total_len < alloc_len) {
7711		ctsio->residual = alloc_len - total_len;
7712		ctsio->kern_data_len = total_len;
7713		ctsio->kern_total_len = total_len;
7714	} else {
7715		ctsio->residual = 0;
7716		ctsio->kern_data_len = alloc_len;
7717		ctsio->kern_total_len = alloc_len;
7718	}
7719	ctsio->kern_data_resid = 0;
7720	ctsio->kern_rel_offset = 0;
7721
7722	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7723	scsi_ulto2b(sizeof(*data) - 2, data->length);
7724	data->origin = RTS_ORIG_OUTSIDE;
7725	getmicrotime(&tv);
7726	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7727	scsi_ulto4b(timestamp >> 16, data->timestamp);
7728	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7729
7730	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7731	ctsio->be_move_done = ctl_config_move_done;
7732
7733	ctl_datamove((union ctl_io *)ctsio);
7734	return (retval);
7735}
7736
7737int
7738ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7739{
7740	struct scsi_per_res_in *cdb;
7741	int alloc_len, total_len = 0;
7742	/* struct scsi_per_res_in_rsrv in_data; */
7743	struct ctl_lun *lun;
7744	struct ctl_softc *softc;
7745
7746	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7747
7748	softc = control_softc;
7749
7750	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7751
7752	alloc_len = scsi_2btoul(cdb->length);
7753
7754	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7755
7756retry:
7757	mtx_lock(&lun->lun_lock);
7758	switch (cdb->action) {
7759	case SPRI_RK: /* read keys */
7760		total_len = sizeof(struct scsi_per_res_in_keys) +
7761			lun->pr_key_count *
7762			sizeof(struct scsi_per_res_key);
7763		break;
7764	case SPRI_RR: /* read reservation */
7765		if (lun->flags & CTL_LUN_PR_RESERVED)
7766			total_len = sizeof(struct scsi_per_res_in_rsrv);
7767		else
7768			total_len = sizeof(struct scsi_per_res_in_header);
7769		break;
7770	case SPRI_RC: /* report capabilities */
7771		total_len = sizeof(struct scsi_per_res_cap);
7772		break;
7773	case SPRI_RS: /* read full status */
7774		total_len = sizeof(struct scsi_per_res_in_header) +
7775		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7776		    lun->pr_key_count;
7777		break;
7778	default:
7779		panic("Invalid PR type %x", cdb->action);
7780	}
7781	mtx_unlock(&lun->lun_lock);
7782
7783	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7784
7785	if (total_len < alloc_len) {
7786		ctsio->residual = alloc_len - total_len;
7787		ctsio->kern_data_len = total_len;
7788		ctsio->kern_total_len = total_len;
7789	} else {
7790		ctsio->residual = 0;
7791		ctsio->kern_data_len = alloc_len;
7792		ctsio->kern_total_len = alloc_len;
7793	}
7794
7795	ctsio->kern_data_resid = 0;
7796	ctsio->kern_rel_offset = 0;
7797	ctsio->kern_sg_entries = 0;
7798
7799	mtx_lock(&lun->lun_lock);
7800	switch (cdb->action) {
7801	case SPRI_RK: { // read keys
7802        struct scsi_per_res_in_keys *res_keys;
7803		int i, key_count;
7804
7805		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7806
7807		/*
7808		 * We had to drop the lock to allocate our buffer, which
7809		 * leaves time for someone to come in with another
7810		 * persistent reservation.  (That is unlikely, though,
7811		 * since this should be the only persistent reservation
7812		 * command active right now.)
7813		 */
7814		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7815		    (lun->pr_key_count *
7816		     sizeof(struct scsi_per_res_key)))){
7817			mtx_unlock(&lun->lun_lock);
7818			free(ctsio->kern_data_ptr, M_CTL);
7819			printf("%s: reservation length changed, retrying\n",
7820			       __func__);
7821			goto retry;
7822		}
7823
7824		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7825
7826		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7827			     lun->pr_key_count, res_keys->header.length);
7828
7829		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7830			if (lun->pr_keys[i] == 0)
7831				continue;
7832
7833			/*
7834			 * We used lun->pr_key_count to calculate the
7835			 * size to allocate.  If it turns out the number of
7836			 * initiators with the registered flag set is
7837			 * larger than that (i.e. they haven't been kept in
7838			 * sync), we've got a problem.
7839			 */
7840			if (key_count >= lun->pr_key_count) {
7841#ifdef NEEDTOPORT
7842				csevent_log(CSC_CTL | CSC_SHELF_SW |
7843					    CTL_PR_ERROR,
7844					    csevent_LogType_Fault,
7845					    csevent_AlertLevel_Yellow,
7846					    csevent_FRU_ShelfController,
7847					    csevent_FRU_Firmware,
7848				        csevent_FRU_Unknown,
7849					    "registered keys %d >= key "
7850					    "count %d", key_count,
7851					    lun->pr_key_count);
7852#endif
7853				key_count++;
7854				continue;
7855			}
7856			scsi_u64to8b(lun->pr_keys[i],
7857			    res_keys->keys[key_count].key);
7858			key_count++;
7859		}
7860		break;
7861	}
7862	case SPRI_RR: { // read reservation
7863		struct scsi_per_res_in_rsrv *res;
7864		int tmp_len, header_only;
7865
7866		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7867
7868		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7869
7870		if (lun->flags & CTL_LUN_PR_RESERVED)
7871		{
7872			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7873			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7874				    res->header.length);
7875			header_only = 0;
7876		} else {
7877			tmp_len = sizeof(struct scsi_per_res_in_header);
7878			scsi_ulto4b(0, res->header.length);
7879			header_only = 1;
7880		}
7881
7882		/*
7883		 * We had to drop the lock to allocate our buffer, which
7884		 * leaves time for someone to come in with another
7885		 * persistent reservation.  (That is unlikely, though,
7886		 * since this should be the only persistent reservation
7887		 * command active right now.)
7888		 */
7889		if (tmp_len != total_len) {
7890			mtx_unlock(&lun->lun_lock);
7891			free(ctsio->kern_data_ptr, M_CTL);
7892			printf("%s: reservation status changed, retrying\n",
7893			       __func__);
7894			goto retry;
7895		}
7896
7897		/*
7898		 * No reservation held, so we're done.
7899		 */
7900		if (header_only != 0)
7901			break;
7902
7903		/*
7904		 * If the registration is an All Registrants type, the key
7905		 * is 0, since it doesn't really matter.
7906		 */
7907		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7908			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7909			    res->data.reservation);
7910		}
7911		res->data.scopetype = lun->res_type;
7912		break;
7913	}
7914	case SPRI_RC:     //report capabilities
7915	{
7916		struct scsi_per_res_cap *res_cap;
7917		uint16_t type_mask;
7918
7919		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7920		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7921		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7922		type_mask = SPRI_TM_WR_EX_AR |
7923			    SPRI_TM_EX_AC_RO |
7924			    SPRI_TM_WR_EX_RO |
7925			    SPRI_TM_EX_AC |
7926			    SPRI_TM_WR_EX |
7927			    SPRI_TM_EX_AC_AR;
7928		scsi_ulto2b(type_mask, res_cap->type_mask);
7929		break;
7930	}
7931	case SPRI_RS: { // read full status
7932		struct scsi_per_res_in_full *res_status;
7933		struct scsi_per_res_in_full_desc *res_desc;
7934		struct ctl_port *port;
7935		int i, len;
7936
7937		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7938
7939		/*
7940		 * We had to drop the lock to allocate our buffer, which
7941		 * leaves time for someone to come in with another
7942		 * persistent reservation.  (That is unlikely, though,
7943		 * since this should be the only persistent reservation
7944		 * command active right now.)
7945		 */
7946		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7947		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7948		     lun->pr_key_count)){
7949			mtx_unlock(&lun->lun_lock);
7950			free(ctsio->kern_data_ptr, M_CTL);
7951			printf("%s: reservation length changed, retrying\n",
7952			       __func__);
7953			goto retry;
7954		}
7955
7956		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7957
7958		res_desc = &res_status->desc[0];
7959		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7960			if (lun->pr_keys[i] == 0)
7961				continue;
7962
7963			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7964			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7965			    (lun->pr_res_idx == i ||
7966			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7967				res_desc->flags = SPRI_FULL_R_HOLDER;
7968				res_desc->scopetype = lun->res_type;
7969			}
7970			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7971			    res_desc->rel_trgt_port_id);
7972			len = 0;
7973			port = softc->ctl_ports[
7974			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7975			if (port != NULL)
7976				len = ctl_create_iid(port,
7977				    i % CTL_MAX_INIT_PER_PORT,
7978				    res_desc->transport_id);
7979			scsi_ulto4b(len, res_desc->additional_length);
7980			res_desc = (struct scsi_per_res_in_full_desc *)
7981			    &res_desc->transport_id[len];
7982		}
7983		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7984		    res_status->header.length);
7985		break;
7986	}
7987	default:
7988		/*
7989		 * This is a bug, because we just checked for this above,
7990		 * and should have returned an error.
7991		 */
7992		panic("Invalid PR type %x", cdb->action);
7993		break; /* NOTREACHED */
7994	}
7995	mtx_unlock(&lun->lun_lock);
7996
7997	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7998	ctsio->be_move_done = ctl_config_move_done;
7999
8000	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8001			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8002			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8003			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8004			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8005
8006	ctl_datamove((union ctl_io *)ctsio);
8007
8008	return (CTL_RETVAL_COMPLETE);
8009}
8010
8011/*
8012 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8013 * it should return.
8014 */
8015static int
8016ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8017		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8018		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8019		struct scsi_per_res_out_parms* param)
8020{
8021	union ctl_ha_msg persis_io;
8022	int retval, i;
8023	int isc_retval;
8024
8025	retval = 0;
8026
8027	mtx_lock(&lun->lun_lock);
8028	if (sa_res_key == 0) {
8029		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8030			/* validate scope and type */
8031			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8032			     SPR_LU_SCOPE) {
8033				mtx_unlock(&lun->lun_lock);
8034				ctl_set_invalid_field(/*ctsio*/ ctsio,
8035						      /*sks_valid*/ 1,
8036						      /*command*/ 1,
8037						      /*field*/ 2,
8038						      /*bit_valid*/ 1,
8039						      /*bit*/ 4);
8040				ctl_done((union ctl_io *)ctsio);
8041				return (1);
8042			}
8043
8044		        if (type>8 || type==2 || type==4 || type==0) {
8045				mtx_unlock(&lun->lun_lock);
8046				ctl_set_invalid_field(/*ctsio*/ ctsio,
8047       	           				      /*sks_valid*/ 1,
8048						      /*command*/ 1,
8049						      /*field*/ 2,
8050						      /*bit_valid*/ 1,
8051						      /*bit*/ 0);
8052				ctl_done((union ctl_io *)ctsio);
8053				return (1);
8054		        }
8055
8056			/*
8057			 * Unregister everybody else and build UA for
8058			 * them
8059			 */
8060			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8061				if (i == residx || lun->pr_keys[i] == 0)
8062					continue;
8063
8064				if (!persis_offset
8065				 && i <CTL_MAX_INITIATORS)
8066					lun->pending_ua[i] |=
8067						CTL_UA_REG_PREEMPT;
8068				else if (persis_offset
8069				      && i >= persis_offset)
8070					lun->pending_ua[i-persis_offset] |=
8071						CTL_UA_REG_PREEMPT;
8072				lun->pr_keys[i] = 0;
8073			}
8074			lun->pr_key_count = 1;
8075			lun->res_type = type;
8076			if (lun->res_type != SPR_TYPE_WR_EX_AR
8077			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8078				lun->pr_res_idx = residx;
8079
8080			/* send msg to other side */
8081			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8082			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8083			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8084			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8085			persis_io.pr.pr_info.res_type = type;
8086			memcpy(persis_io.pr.pr_info.sa_res_key,
8087			       param->serv_act_res_key,
8088			       sizeof(param->serv_act_res_key));
8089			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8090			     &persis_io, sizeof(persis_io), 0)) >
8091			     CTL_HA_STATUS_SUCCESS) {
8092				printf("CTL:Persis Out error returned "
8093				       "from ctl_ha_msg_send %d\n",
8094				       isc_retval);
8095			}
8096		} else {
8097			/* not all registrants */
8098			mtx_unlock(&lun->lun_lock);
8099			free(ctsio->kern_data_ptr, M_CTL);
8100			ctl_set_invalid_field(ctsio,
8101					      /*sks_valid*/ 1,
8102					      /*command*/ 0,
8103					      /*field*/ 8,
8104					      /*bit_valid*/ 0,
8105					      /*bit*/ 0);
8106			ctl_done((union ctl_io *)ctsio);
8107			return (1);
8108		}
8109	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8110		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8111		int found = 0;
8112
8113		if (res_key == sa_res_key) {
8114			/* special case */
8115			/*
8116			 * The spec implies this is not good but doesn't
8117			 * say what to do. There are two choices either
8118			 * generate a res conflict or check condition
8119			 * with illegal field in parameter data. Since
8120			 * that is what is done when the sa_res_key is
8121			 * zero I'll take that approach since this has
8122			 * to do with the sa_res_key.
8123			 */
8124			mtx_unlock(&lun->lun_lock);
8125			free(ctsio->kern_data_ptr, M_CTL);
8126			ctl_set_invalid_field(ctsio,
8127					      /*sks_valid*/ 1,
8128					      /*command*/ 0,
8129					      /*field*/ 8,
8130					      /*bit_valid*/ 0,
8131					      /*bit*/ 0);
8132			ctl_done((union ctl_io *)ctsio);
8133			return (1);
8134		}
8135
8136		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8137			if (lun->pr_keys[i] != sa_res_key)
8138				continue;
8139
8140			found = 1;
8141			lun->pr_keys[i] = 0;
8142			lun->pr_key_count--;
8143
8144			if (!persis_offset && i < CTL_MAX_INITIATORS)
8145				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8146			else if (persis_offset && i >= persis_offset)
8147				lun->pending_ua[i-persis_offset] |=
8148					CTL_UA_REG_PREEMPT;
8149		}
8150		if (!found) {
8151			mtx_unlock(&lun->lun_lock);
8152			free(ctsio->kern_data_ptr, M_CTL);
8153			ctl_set_reservation_conflict(ctsio);
8154			ctl_done((union ctl_io *)ctsio);
8155			return (CTL_RETVAL_COMPLETE);
8156		}
8157		/* send msg to other side */
8158		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8159		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8160		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8161		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8162		persis_io.pr.pr_info.res_type = type;
8163		memcpy(persis_io.pr.pr_info.sa_res_key,
8164		       param->serv_act_res_key,
8165		       sizeof(param->serv_act_res_key));
8166		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8167		     &persis_io, sizeof(persis_io), 0)) >
8168		     CTL_HA_STATUS_SUCCESS) {
8169			printf("CTL:Persis Out error returned from "
8170			       "ctl_ha_msg_send %d\n", isc_retval);
8171		}
8172	} else {
8173		/* Reserved but not all registrants */
8174		/* sa_res_key is res holder */
8175		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8176			/* validate scope and type */
8177			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8178			     SPR_LU_SCOPE) {
8179				mtx_unlock(&lun->lun_lock);
8180				ctl_set_invalid_field(/*ctsio*/ ctsio,
8181						      /*sks_valid*/ 1,
8182						      /*command*/ 1,
8183						      /*field*/ 2,
8184						      /*bit_valid*/ 1,
8185						      /*bit*/ 4);
8186				ctl_done((union ctl_io *)ctsio);
8187				return (1);
8188			}
8189
8190			if (type>8 || type==2 || type==4 || type==0) {
8191				mtx_unlock(&lun->lun_lock);
8192				ctl_set_invalid_field(/*ctsio*/ ctsio,
8193						      /*sks_valid*/ 1,
8194						      /*command*/ 1,
8195						      /*field*/ 2,
8196						      /*bit_valid*/ 1,
8197						      /*bit*/ 0);
8198				ctl_done((union ctl_io *)ctsio);
8199				return (1);
8200			}
8201
8202			/*
8203			 * Do the following:
8204			 * if sa_res_key != res_key remove all
8205			 * registrants w/sa_res_key and generate UA
8206			 * for these registrants(Registrations
8207			 * Preempted) if it wasn't an exclusive
8208			 * reservation generate UA(Reservations
8209			 * Preempted) for all other registered nexuses
8210			 * if the type has changed. Establish the new
8211			 * reservation and holder. If res_key and
8212			 * sa_res_key are the same do the above
8213			 * except don't unregister the res holder.
8214			 */
8215
8216			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8217				if (i == residx || lun->pr_keys[i] == 0)
8218					continue;
8219
8220				if (sa_res_key == lun->pr_keys[i]) {
8221					lun->pr_keys[i] = 0;
8222					lun->pr_key_count--;
8223
8224					if (!persis_offset
8225					 && i < CTL_MAX_INITIATORS)
8226						lun->pending_ua[i] |=
8227							CTL_UA_REG_PREEMPT;
8228					else if (persis_offset
8229					      && i >= persis_offset)
8230						lun->pending_ua[i-persis_offset] |=
8231						  CTL_UA_REG_PREEMPT;
8232				} else if (type != lun->res_type
8233					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8234					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8235						if (!persis_offset
8236						 && i < CTL_MAX_INITIATORS)
8237							lun->pending_ua[i] |=
8238							CTL_UA_RES_RELEASE;
8239						else if (persis_offset
8240						      && i >= persis_offset)
8241							lun->pending_ua[
8242							i-persis_offset] |=
8243							CTL_UA_RES_RELEASE;
8244				}
8245			}
8246			lun->res_type = type;
8247			if (lun->res_type != SPR_TYPE_WR_EX_AR
8248			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8249				lun->pr_res_idx = residx;
8250			else
8251				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8252
8253			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8254			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8255			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8256			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8257			persis_io.pr.pr_info.res_type = type;
8258			memcpy(persis_io.pr.pr_info.sa_res_key,
8259			       param->serv_act_res_key,
8260			       sizeof(param->serv_act_res_key));
8261			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8262			     &persis_io, sizeof(persis_io), 0)) >
8263			     CTL_HA_STATUS_SUCCESS) {
8264				printf("CTL:Persis Out error returned "
8265				       "from ctl_ha_msg_send %d\n",
8266				       isc_retval);
8267			}
8268		} else {
8269			/*
8270			 * sa_res_key is not the res holder just
8271			 * remove registrants
8272			 */
8273			int found=0;
8274
8275			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8276				if (sa_res_key != lun->pr_keys[i])
8277					continue;
8278
8279				found = 1;
8280				lun->pr_keys[i] = 0;
8281				lun->pr_key_count--;
8282
8283				if (!persis_offset
8284				 && i < CTL_MAX_INITIATORS)
8285					lun->pending_ua[i] |=
8286						CTL_UA_REG_PREEMPT;
8287				else if (persis_offset
8288				      && i >= persis_offset)
8289					lun->pending_ua[i-persis_offset] |=
8290						CTL_UA_REG_PREEMPT;
8291			}
8292
8293			if (!found) {
8294				mtx_unlock(&lun->lun_lock);
8295				free(ctsio->kern_data_ptr, M_CTL);
8296				ctl_set_reservation_conflict(ctsio);
8297				ctl_done((union ctl_io *)ctsio);
8298		        	return (1);
8299			}
8300			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8301			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8302			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8303			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8304			persis_io.pr.pr_info.res_type = type;
8305			memcpy(persis_io.pr.pr_info.sa_res_key,
8306			       param->serv_act_res_key,
8307			       sizeof(param->serv_act_res_key));
8308			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8309			     &persis_io, sizeof(persis_io), 0)) >
8310			     CTL_HA_STATUS_SUCCESS) {
8311				printf("CTL:Persis Out error returned "
8312				       "from ctl_ha_msg_send %d\n",
8313				isc_retval);
8314			}
8315		}
8316	}
8317
8318	lun->PRGeneration++;
8319	mtx_unlock(&lun->lun_lock);
8320
8321	return (retval);
8322}
8323
8324static void
8325ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8326{
8327	uint64_t sa_res_key;
8328	int i;
8329
8330	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8331
8332	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8333	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8334	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8335		if (sa_res_key == 0) {
8336			/*
8337			 * Unregister everybody else and build UA for
8338			 * them
8339			 */
8340			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8341				if (i == msg->pr.pr_info.residx ||
8342				    lun->pr_keys[i] == 0)
8343					continue;
8344
8345				if (!persis_offset
8346				 && i < CTL_MAX_INITIATORS)
8347					lun->pending_ua[i] |=
8348						CTL_UA_REG_PREEMPT;
8349				else if (persis_offset && i >= persis_offset)
8350					lun->pending_ua[i - persis_offset] |=
8351						CTL_UA_REG_PREEMPT;
8352				lun->pr_keys[i] = 0;
8353			}
8354
8355			lun->pr_key_count = 1;
8356			lun->res_type = msg->pr.pr_info.res_type;
8357			if (lun->res_type != SPR_TYPE_WR_EX_AR
8358			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8359				lun->pr_res_idx = msg->pr.pr_info.residx;
8360		} else {
8361		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8362				if (sa_res_key == lun->pr_keys[i])
8363					continue;
8364
8365				lun->pr_keys[i] = 0;
8366				lun->pr_key_count--;
8367
8368				if (!persis_offset
8369				 && i < persis_offset)
8370					lun->pending_ua[i] |=
8371						CTL_UA_REG_PREEMPT;
8372				else if (persis_offset
8373				      && i >= persis_offset)
8374					lun->pending_ua[i - persis_offset] |=
8375						CTL_UA_REG_PREEMPT;
8376			}
8377		}
8378	} else {
8379		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8380			if (i == msg->pr.pr_info.residx ||
8381			    lun->pr_keys[i] == 0)
8382				continue;
8383
8384			if (sa_res_key == lun->pr_keys[i]) {
8385				lun->pr_keys[i] = 0;
8386				lun->pr_key_count--;
8387				if (!persis_offset
8388				 && i < CTL_MAX_INITIATORS)
8389					lun->pending_ua[i] |=
8390						CTL_UA_REG_PREEMPT;
8391				else if (persis_offset
8392				      && i >= persis_offset)
8393					lun->pending_ua[i - persis_offset] |=
8394						CTL_UA_REG_PREEMPT;
8395			} else if (msg->pr.pr_info.res_type != lun->res_type
8396				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8397				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8398					if (!persis_offset
8399					 && i < persis_offset)
8400						lun->pending_ua[i] |=
8401							CTL_UA_RES_RELEASE;
8402					else if (persis_offset
8403					      && i >= persis_offset)
8404					lun->pending_ua[i - persis_offset] |=
8405						CTL_UA_RES_RELEASE;
8406			}
8407		}
8408		lun->res_type = msg->pr.pr_info.res_type;
8409		if (lun->res_type != SPR_TYPE_WR_EX_AR
8410		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8411			lun->pr_res_idx = msg->pr.pr_info.residx;
8412		else
8413			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8414	}
8415	lun->PRGeneration++;
8416
8417}
8418
8419
8420int
8421ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8422{
8423	int retval;
8424	int isc_retval;
8425	u_int32_t param_len;
8426	struct scsi_per_res_out *cdb;
8427	struct ctl_lun *lun;
8428	struct scsi_per_res_out_parms* param;
8429	struct ctl_softc *softc;
8430	uint32_t residx;
8431	uint64_t res_key, sa_res_key;
8432	uint8_t type;
8433	union ctl_ha_msg persis_io;
8434	int    i;
8435
8436	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8437
8438	retval = CTL_RETVAL_COMPLETE;
8439
8440	softc = control_softc;
8441
8442	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8443	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8444
8445	/*
8446	 * We only support whole-LUN scope.  The scope & type are ignored for
8447	 * register, register and ignore existing key and clear.
8448	 * We sometimes ignore scope and type on preempts too!!
8449	 * Verify reservation type here as well.
8450	 */
8451	type = cdb->scope_type & SPR_TYPE_MASK;
8452	if ((cdb->action == SPRO_RESERVE)
8453	 || (cdb->action == SPRO_RELEASE)) {
8454		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8455			ctl_set_invalid_field(/*ctsio*/ ctsio,
8456					      /*sks_valid*/ 1,
8457					      /*command*/ 1,
8458					      /*field*/ 2,
8459					      /*bit_valid*/ 1,
8460					      /*bit*/ 4);
8461			ctl_done((union ctl_io *)ctsio);
8462			return (CTL_RETVAL_COMPLETE);
8463		}
8464
8465		if (type>8 || type==2 || type==4 || type==0) {
8466			ctl_set_invalid_field(/*ctsio*/ ctsio,
8467					      /*sks_valid*/ 1,
8468					      /*command*/ 1,
8469					      /*field*/ 2,
8470					      /*bit_valid*/ 1,
8471					      /*bit*/ 0);
8472			ctl_done((union ctl_io *)ctsio);
8473			return (CTL_RETVAL_COMPLETE);
8474		}
8475	}
8476
8477	param_len = scsi_4btoul(cdb->length);
8478
8479	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8480		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8481		ctsio->kern_data_len = param_len;
8482		ctsio->kern_total_len = param_len;
8483		ctsio->kern_data_resid = 0;
8484		ctsio->kern_rel_offset = 0;
8485		ctsio->kern_sg_entries = 0;
8486		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8487		ctsio->be_move_done = ctl_config_move_done;
8488		ctl_datamove((union ctl_io *)ctsio);
8489
8490		return (CTL_RETVAL_COMPLETE);
8491	}
8492
8493	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8494
8495	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8496	res_key = scsi_8btou64(param->res_key.key);
8497	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8498
8499	/*
8500	 * Validate the reservation key here except for SPRO_REG_IGNO
8501	 * This must be done for all other service actions
8502	 */
8503	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8504		mtx_lock(&lun->lun_lock);
8505		if (lun->pr_keys[residx] != 0) {
8506		    if (res_key != lun->pr_keys[residx]) {
8507				/*
8508				 * The current key passed in doesn't match
8509				 * the one the initiator previously
8510				 * registered.
8511				 */
8512				mtx_unlock(&lun->lun_lock);
8513				free(ctsio->kern_data_ptr, M_CTL);
8514				ctl_set_reservation_conflict(ctsio);
8515				ctl_done((union ctl_io *)ctsio);
8516				return (CTL_RETVAL_COMPLETE);
8517			}
8518		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8519			/*
8520			 * We are not registered
8521			 */
8522			mtx_unlock(&lun->lun_lock);
8523			free(ctsio->kern_data_ptr, M_CTL);
8524			ctl_set_reservation_conflict(ctsio);
8525			ctl_done((union ctl_io *)ctsio);
8526			return (CTL_RETVAL_COMPLETE);
8527		} else if (res_key != 0) {
8528			/*
8529			 * We are not registered and trying to register but
8530			 * the register key isn't zero.
8531			 */
8532			mtx_unlock(&lun->lun_lock);
8533			free(ctsio->kern_data_ptr, M_CTL);
8534			ctl_set_reservation_conflict(ctsio);
8535			ctl_done((union ctl_io *)ctsio);
8536			return (CTL_RETVAL_COMPLETE);
8537		}
8538		mtx_unlock(&lun->lun_lock);
8539	}
8540
8541	switch (cdb->action & SPRO_ACTION_MASK) {
8542	case SPRO_REGISTER:
8543	case SPRO_REG_IGNO: {
8544
8545#if 0
8546		printf("Registration received\n");
8547#endif
8548
8549		/*
8550		 * We don't support any of these options, as we report in
8551		 * the read capabilities request (see
8552		 * ctl_persistent_reserve_in(), above).
8553		 */
8554		if ((param->flags & SPR_SPEC_I_PT)
8555		 || (param->flags & SPR_ALL_TG_PT)
8556		 || (param->flags & SPR_APTPL)) {
8557			int bit_ptr;
8558
8559			if (param->flags & SPR_APTPL)
8560				bit_ptr = 0;
8561			else if (param->flags & SPR_ALL_TG_PT)
8562				bit_ptr = 2;
8563			else /* SPR_SPEC_I_PT */
8564				bit_ptr = 3;
8565
8566			free(ctsio->kern_data_ptr, M_CTL);
8567			ctl_set_invalid_field(ctsio,
8568					      /*sks_valid*/ 1,
8569					      /*command*/ 0,
8570					      /*field*/ 20,
8571					      /*bit_valid*/ 1,
8572					      /*bit*/ bit_ptr);
8573			ctl_done((union ctl_io *)ctsio);
8574			return (CTL_RETVAL_COMPLETE);
8575		}
8576
8577		mtx_lock(&lun->lun_lock);
8578
8579		/*
8580		 * The initiator wants to clear the
8581		 * key/unregister.
8582		 */
8583		if (sa_res_key == 0) {
8584			if ((res_key == 0
8585			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8586			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8587			  && lun->pr_keys[residx] == 0)) {
8588				mtx_unlock(&lun->lun_lock);
8589				goto done;
8590			}
8591
8592			lun->pr_keys[residx] = 0;
8593			lun->pr_key_count--;
8594
8595			if (residx == lun->pr_res_idx) {
8596				lun->flags &= ~CTL_LUN_PR_RESERVED;
8597				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8598
8599				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8600				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8601				 && lun->pr_key_count) {
8602					/*
8603					 * If the reservation is a registrants
8604					 * only type we need to generate a UA
8605					 * for other registered inits.  The
8606					 * sense code should be RESERVATIONS
8607					 * RELEASED
8608					 */
8609
8610					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8611						if (lun->pr_keys[
8612						    i + persis_offset] == 0)
8613							continue;
8614						lun->pending_ua[i] |=
8615							CTL_UA_RES_RELEASE;
8616					}
8617				}
8618				lun->res_type = 0;
8619			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8620				if (lun->pr_key_count==0) {
8621					lun->flags &= ~CTL_LUN_PR_RESERVED;
8622					lun->res_type = 0;
8623					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8624				}
8625			}
8626			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8627			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8628			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8629			persis_io.pr.pr_info.residx = residx;
8630			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8631			     &persis_io, sizeof(persis_io), 0 )) >
8632			     CTL_HA_STATUS_SUCCESS) {
8633				printf("CTL:Persis Out error returned from "
8634				       "ctl_ha_msg_send %d\n", isc_retval);
8635			}
8636		} else /* sa_res_key != 0 */ {
8637
8638			/*
8639			 * If we aren't registered currently then increment
8640			 * the key count and set the registered flag.
8641			 */
8642			if (lun->pr_keys[residx] == 0)
8643				lun->pr_key_count++;
8644			lun->pr_keys[residx] = sa_res_key;
8645
8646			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8647			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8648			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8649			persis_io.pr.pr_info.residx = residx;
8650			memcpy(persis_io.pr.pr_info.sa_res_key,
8651			       param->serv_act_res_key,
8652			       sizeof(param->serv_act_res_key));
8653			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8654			     &persis_io, sizeof(persis_io), 0)) >
8655			     CTL_HA_STATUS_SUCCESS) {
8656				printf("CTL:Persis Out error returned from "
8657				       "ctl_ha_msg_send %d\n", isc_retval);
8658			}
8659		}
8660		lun->PRGeneration++;
8661		mtx_unlock(&lun->lun_lock);
8662
8663		break;
8664	}
8665	case SPRO_RESERVE:
8666#if 0
8667                printf("Reserve executed type %d\n", type);
8668#endif
8669		mtx_lock(&lun->lun_lock);
8670		if (lun->flags & CTL_LUN_PR_RESERVED) {
8671			/*
8672			 * if this isn't the reservation holder and it's
8673			 * not a "all registrants" type or if the type is
8674			 * different then we have a conflict
8675			 */
8676			if ((lun->pr_res_idx != residx
8677			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8678			 || lun->res_type != type) {
8679				mtx_unlock(&lun->lun_lock);
8680				free(ctsio->kern_data_ptr, M_CTL);
8681				ctl_set_reservation_conflict(ctsio);
8682				ctl_done((union ctl_io *)ctsio);
8683				return (CTL_RETVAL_COMPLETE);
8684			}
8685			mtx_unlock(&lun->lun_lock);
8686		} else /* create a reservation */ {
8687			/*
8688			 * If it's not an "all registrants" type record
8689			 * reservation holder
8690			 */
8691			if (type != SPR_TYPE_WR_EX_AR
8692			 && type != SPR_TYPE_EX_AC_AR)
8693				lun->pr_res_idx = residx; /* Res holder */
8694			else
8695				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8696
8697			lun->flags |= CTL_LUN_PR_RESERVED;
8698			lun->res_type = type;
8699
8700			mtx_unlock(&lun->lun_lock);
8701
8702			/* send msg to other side */
8703			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8704			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8705			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8706			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8707			persis_io.pr.pr_info.res_type = type;
8708			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8709			     &persis_io, sizeof(persis_io), 0)) >
8710			     CTL_HA_STATUS_SUCCESS) {
8711				printf("CTL:Persis Out error returned from "
8712				       "ctl_ha_msg_send %d\n", isc_retval);
8713			}
8714		}
8715		break;
8716
8717	case SPRO_RELEASE:
8718		mtx_lock(&lun->lun_lock);
8719		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8720			/* No reservation exists return good status */
8721			mtx_unlock(&lun->lun_lock);
8722			goto done;
8723		}
8724		/*
8725		 * Is this nexus a reservation holder?
8726		 */
8727		if (lun->pr_res_idx != residx
8728		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8729			/*
8730			 * not a res holder return good status but
8731			 * do nothing
8732			 */
8733			mtx_unlock(&lun->lun_lock);
8734			goto done;
8735		}
8736
8737		if (lun->res_type != type) {
8738			mtx_unlock(&lun->lun_lock);
8739			free(ctsio->kern_data_ptr, M_CTL);
8740			ctl_set_illegal_pr_release(ctsio);
8741			ctl_done((union ctl_io *)ctsio);
8742			return (CTL_RETVAL_COMPLETE);
8743		}
8744
8745		/* okay to release */
8746		lun->flags &= ~CTL_LUN_PR_RESERVED;
8747		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8748		lun->res_type = 0;
8749
8750		/*
8751		 * if this isn't an exclusive access
8752		 * res generate UA for all other
8753		 * registrants.
8754		 */
8755		if (type != SPR_TYPE_EX_AC
8756		 && type != SPR_TYPE_WR_EX) {
8757			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8758				if (i == residx ||
8759				    lun->pr_keys[i + persis_offset] == 0)
8760					continue;
8761				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8762			}
8763		}
8764		mtx_unlock(&lun->lun_lock);
8765		/* Send msg to other side */
8766		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8767		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8768		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8769		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8770		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8771			printf("CTL:Persis Out error returned from "
8772			       "ctl_ha_msg_send %d\n", isc_retval);
8773		}
8774		break;
8775
8776	case SPRO_CLEAR:
8777		/* send msg to other side */
8778
8779		mtx_lock(&lun->lun_lock);
8780		lun->flags &= ~CTL_LUN_PR_RESERVED;
8781		lun->res_type = 0;
8782		lun->pr_key_count = 0;
8783		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8784
8785		lun->pr_keys[residx] = 0;
8786
8787		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8788			if (lun->pr_keys[i] != 0) {
8789				if (!persis_offset && i < CTL_MAX_INITIATORS)
8790					lun->pending_ua[i] |=
8791						CTL_UA_RES_PREEMPT;
8792				else if (persis_offset && i >= persis_offset)
8793					lun->pending_ua[i-persis_offset] |=
8794					    CTL_UA_RES_PREEMPT;
8795
8796				lun->pr_keys[i] = 0;
8797			}
8798		lun->PRGeneration++;
8799		mtx_unlock(&lun->lun_lock);
8800		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8801		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8802		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8803		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8804		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8805			printf("CTL:Persis Out error returned from "
8806			       "ctl_ha_msg_send %d\n", isc_retval);
8807		}
8808		break;
8809
8810	case SPRO_PREEMPT: {
8811		int nretval;
8812
8813		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8814					  residx, ctsio, cdb, param);
8815		if (nretval != 0)
8816			return (CTL_RETVAL_COMPLETE);
8817		break;
8818	}
8819	default:
8820		panic("Invalid PR type %x", cdb->action);
8821	}
8822
8823done:
8824	free(ctsio->kern_data_ptr, M_CTL);
8825	ctl_set_success(ctsio);
8826	ctl_done((union ctl_io *)ctsio);
8827
8828	return (retval);
8829}
8830
8831/*
8832 * This routine is for handling a message from the other SC pertaining to
8833 * persistent reserve out. All the error checking will have been done
8834 * so only perorming the action need be done here to keep the two
8835 * in sync.
8836 */
8837static void
8838ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8839{
8840	struct ctl_lun *lun;
8841	struct ctl_softc *softc;
8842	int i;
8843	uint32_t targ_lun;
8844
8845	softc = control_softc;
8846
8847	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8848	lun = softc->ctl_luns[targ_lun];
8849	mtx_lock(&lun->lun_lock);
8850	switch(msg->pr.pr_info.action) {
8851	case CTL_PR_REG_KEY:
8852		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8853			lun->pr_key_count++;
8854		lun->pr_keys[msg->pr.pr_info.residx] =
8855		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8856		lun->PRGeneration++;
8857		break;
8858
8859	case CTL_PR_UNREG_KEY:
8860		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8861		lun->pr_key_count--;
8862
8863		/* XXX Need to see if the reservation has been released */
8864		/* if so do we need to generate UA? */
8865		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8866			lun->flags &= ~CTL_LUN_PR_RESERVED;
8867			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8868
8869			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8870			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8871			 && lun->pr_key_count) {
8872				/*
8873				 * If the reservation is a registrants
8874				 * only type we need to generate a UA
8875				 * for other registered inits.  The
8876				 * sense code should be RESERVATIONS
8877				 * RELEASED
8878				 */
8879
8880				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8881					if (lun->pr_keys[i+
8882					    persis_offset] == 0)
8883						continue;
8884
8885					lun->pending_ua[i] |=
8886						CTL_UA_RES_RELEASE;
8887				}
8888			}
8889			lun->res_type = 0;
8890		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8891			if (lun->pr_key_count==0) {
8892				lun->flags &= ~CTL_LUN_PR_RESERVED;
8893				lun->res_type = 0;
8894				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8895			}
8896		}
8897		lun->PRGeneration++;
8898		break;
8899
8900	case CTL_PR_RESERVE:
8901		lun->flags |= CTL_LUN_PR_RESERVED;
8902		lun->res_type = msg->pr.pr_info.res_type;
8903		lun->pr_res_idx = msg->pr.pr_info.residx;
8904
8905		break;
8906
8907	case CTL_PR_RELEASE:
8908		/*
8909		 * if this isn't an exclusive access res generate UA for all
8910		 * other registrants.
8911		 */
8912		if (lun->res_type != SPR_TYPE_EX_AC
8913		 && lun->res_type != SPR_TYPE_WR_EX) {
8914			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8915				if (lun->pr_keys[i+persis_offset] != 0)
8916					lun->pending_ua[i] |=
8917						CTL_UA_RES_RELEASE;
8918		}
8919
8920		lun->flags &= ~CTL_LUN_PR_RESERVED;
8921		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8922		lun->res_type = 0;
8923		break;
8924
8925	case CTL_PR_PREEMPT:
8926		ctl_pro_preempt_other(lun, msg);
8927		break;
8928	case CTL_PR_CLEAR:
8929		lun->flags &= ~CTL_LUN_PR_RESERVED;
8930		lun->res_type = 0;
8931		lun->pr_key_count = 0;
8932		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8933
8934		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8935			if (lun->pr_keys[i] == 0)
8936				continue;
8937			if (!persis_offset
8938			 && i < CTL_MAX_INITIATORS)
8939				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8940			else if (persis_offset
8941			      && i >= persis_offset)
8942				lun->pending_ua[i-persis_offset] |=
8943					CTL_UA_RES_PREEMPT;
8944			lun->pr_keys[i] = 0;
8945		}
8946		lun->PRGeneration++;
8947		break;
8948	}
8949
8950	mtx_unlock(&lun->lun_lock);
8951}
8952
8953int
8954ctl_read_write(struct ctl_scsiio *ctsio)
8955{
8956	struct ctl_lun *lun;
8957	struct ctl_lba_len_flags *lbalen;
8958	uint64_t lba;
8959	uint32_t num_blocks;
8960	int flags, retval;
8961	int isread;
8962
8963	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8964
8965	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8966
8967	flags = 0;
8968	retval = CTL_RETVAL_COMPLETE;
8969
8970	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8971	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8972	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8973		uint32_t residx;
8974
8975		/*
8976		 * XXX KDM need a lock here.
8977		 */
8978		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8979		if ((lun->res_type == SPR_TYPE_EX_AC
8980		  && residx != lun->pr_res_idx)
8981		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8982		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8983		  && lun->pr_keys[residx] == 0)) {
8984			ctl_set_reservation_conflict(ctsio);
8985			ctl_done((union ctl_io *)ctsio);
8986			return (CTL_RETVAL_COMPLETE);
8987	        }
8988	}
8989
8990	switch (ctsio->cdb[0]) {
8991	case READ_6:
8992	case WRITE_6: {
8993		struct scsi_rw_6 *cdb;
8994
8995		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8996
8997		lba = scsi_3btoul(cdb->addr);
8998		/* only 5 bits are valid in the most significant address byte */
8999		lba &= 0x1fffff;
9000		num_blocks = cdb->length;
9001		/*
9002		 * This is correct according to SBC-2.
9003		 */
9004		if (num_blocks == 0)
9005			num_blocks = 256;
9006		break;
9007	}
9008	case READ_10:
9009	case WRITE_10: {
9010		struct scsi_rw_10 *cdb;
9011
9012		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9013		if (cdb->byte2 & SRW10_FUA)
9014			flags |= CTL_LLF_FUA;
9015		if (cdb->byte2 & SRW10_DPO)
9016			flags |= CTL_LLF_DPO;
9017		lba = scsi_4btoul(cdb->addr);
9018		num_blocks = scsi_2btoul(cdb->length);
9019		break;
9020	}
9021	case WRITE_VERIFY_10: {
9022		struct scsi_write_verify_10 *cdb;
9023
9024		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9025		flags |= CTL_LLF_FUA;
9026		if (cdb->byte2 & SWV_DPO)
9027			flags |= CTL_LLF_DPO;
9028		lba = scsi_4btoul(cdb->addr);
9029		num_blocks = scsi_2btoul(cdb->length);
9030		break;
9031	}
9032	case READ_12:
9033	case WRITE_12: {
9034		struct scsi_rw_12 *cdb;
9035
9036		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9037		if (cdb->byte2 & SRW12_FUA)
9038			flags |= CTL_LLF_FUA;
9039		if (cdb->byte2 & SRW12_DPO)
9040			flags |= CTL_LLF_DPO;
9041		lba = scsi_4btoul(cdb->addr);
9042		num_blocks = scsi_4btoul(cdb->length);
9043		break;
9044	}
9045	case WRITE_VERIFY_12: {
9046		struct scsi_write_verify_12 *cdb;
9047
9048		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9049		flags |= CTL_LLF_FUA;
9050		if (cdb->byte2 & SWV_DPO)
9051			flags |= CTL_LLF_DPO;
9052		lba = scsi_4btoul(cdb->addr);
9053		num_blocks = scsi_4btoul(cdb->length);
9054		break;
9055	}
9056	case READ_16:
9057	case WRITE_16: {
9058		struct scsi_rw_16 *cdb;
9059
9060		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9061		if (cdb->byte2 & SRW12_FUA)
9062			flags |= CTL_LLF_FUA;
9063		if (cdb->byte2 & SRW12_DPO)
9064			flags |= CTL_LLF_DPO;
9065		lba = scsi_8btou64(cdb->addr);
9066		num_blocks = scsi_4btoul(cdb->length);
9067		break;
9068	}
9069	case WRITE_ATOMIC_16: {
9070		struct scsi_rw_16 *cdb;
9071
9072		if (lun->be_lun->atomicblock == 0) {
9073			ctl_set_invalid_opcode(ctsio);
9074			ctl_done((union ctl_io *)ctsio);
9075			return (CTL_RETVAL_COMPLETE);
9076		}
9077
9078		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9079		if (cdb->byte2 & SRW12_FUA)
9080			flags |= CTL_LLF_FUA;
9081		if (cdb->byte2 & SRW12_DPO)
9082			flags |= CTL_LLF_DPO;
9083		lba = scsi_8btou64(cdb->addr);
9084		num_blocks = scsi_4btoul(cdb->length);
9085		if (num_blocks > lun->be_lun->atomicblock) {
9086			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9087			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9088			    /*bit*/ 0);
9089			ctl_done((union ctl_io *)ctsio);
9090			return (CTL_RETVAL_COMPLETE);
9091		}
9092		break;
9093	}
9094	case WRITE_VERIFY_16: {
9095		struct scsi_write_verify_16 *cdb;
9096
9097		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9098		flags |= CTL_LLF_FUA;
9099		if (cdb->byte2 & SWV_DPO)
9100			flags |= CTL_LLF_DPO;
9101		lba = scsi_8btou64(cdb->addr);
9102		num_blocks = scsi_4btoul(cdb->length);
9103		break;
9104	}
9105	default:
9106		/*
9107		 * We got a command we don't support.  This shouldn't
9108		 * happen, commands should be filtered out above us.
9109		 */
9110		ctl_set_invalid_opcode(ctsio);
9111		ctl_done((union ctl_io *)ctsio);
9112
9113		return (CTL_RETVAL_COMPLETE);
9114		break; /* NOTREACHED */
9115	}
9116
9117	/*
9118	 * The first check is to make sure we're in bounds, the second
9119	 * check is to catch wrap-around problems.  If the lba + num blocks
9120	 * is less than the lba, then we've wrapped around and the block
9121	 * range is invalid anyway.
9122	 */
9123	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9124	 || ((lba + num_blocks) < lba)) {
9125		ctl_set_lba_out_of_range(ctsio);
9126		ctl_done((union ctl_io *)ctsio);
9127		return (CTL_RETVAL_COMPLETE);
9128	}
9129
9130	/*
9131	 * According to SBC-3, a transfer length of 0 is not an error.
9132	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9133	 * translates to 256 blocks for those commands.
9134	 */
9135	if (num_blocks == 0) {
9136		ctl_set_success(ctsio);
9137		ctl_done((union ctl_io *)ctsio);
9138		return (CTL_RETVAL_COMPLETE);
9139	}
9140
9141	/* Set FUA and/or DPO if caches are disabled. */
9142	if (isread) {
9143		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9144		    SCP_RCD) != 0)
9145			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9146	} else {
9147		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9148		    SCP_WCE) == 0)
9149			flags |= CTL_LLF_FUA;
9150	}
9151
9152	lbalen = (struct ctl_lba_len_flags *)
9153	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9154	lbalen->lba = lba;
9155	lbalen->len = num_blocks;
9156	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9157
9158	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9159	ctsio->kern_rel_offset = 0;
9160
9161	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9162
9163	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9164
9165	return (retval);
9166}
9167
9168static int
9169ctl_cnw_cont(union ctl_io *io)
9170{
9171	struct ctl_scsiio *ctsio;
9172	struct ctl_lun *lun;
9173	struct ctl_lba_len_flags *lbalen;
9174	int retval;
9175
9176	ctsio = &io->scsiio;
9177	ctsio->io_hdr.status = CTL_STATUS_NONE;
9178	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9179	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9180	lbalen = (struct ctl_lba_len_flags *)
9181	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9182	lbalen->flags &= ~CTL_LLF_COMPARE;
9183	lbalen->flags |= CTL_LLF_WRITE;
9184
9185	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9186	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9187	return (retval);
9188}
9189
9190int
9191ctl_cnw(struct ctl_scsiio *ctsio)
9192{
9193	struct ctl_lun *lun;
9194	struct ctl_lba_len_flags *lbalen;
9195	uint64_t lba;
9196	uint32_t num_blocks;
9197	int flags, retval;
9198
9199	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9200
9201	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9202
9203	flags = 0;
9204	retval = CTL_RETVAL_COMPLETE;
9205
9206	switch (ctsio->cdb[0]) {
9207	case COMPARE_AND_WRITE: {
9208		struct scsi_compare_and_write *cdb;
9209
9210		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9211		if (cdb->byte2 & SRW10_FUA)
9212			flags |= CTL_LLF_FUA;
9213		if (cdb->byte2 & SRW10_DPO)
9214			flags |= CTL_LLF_DPO;
9215		lba = scsi_8btou64(cdb->addr);
9216		num_blocks = cdb->length;
9217		break;
9218	}
9219	default:
9220		/*
9221		 * We got a command we don't support.  This shouldn't
9222		 * happen, commands should be filtered out above us.
9223		 */
9224		ctl_set_invalid_opcode(ctsio);
9225		ctl_done((union ctl_io *)ctsio);
9226
9227		return (CTL_RETVAL_COMPLETE);
9228		break; /* NOTREACHED */
9229	}
9230
9231	/*
9232	 * The first check is to make sure we're in bounds, the second
9233	 * check is to catch wrap-around problems.  If the lba + num blocks
9234	 * is less than the lba, then we've wrapped around and the block
9235	 * range is invalid anyway.
9236	 */
9237	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9238	 || ((lba + num_blocks) < lba)) {
9239		ctl_set_lba_out_of_range(ctsio);
9240		ctl_done((union ctl_io *)ctsio);
9241		return (CTL_RETVAL_COMPLETE);
9242	}
9243
9244	/*
9245	 * According to SBC-3, a transfer length of 0 is not an error.
9246	 */
9247	if (num_blocks == 0) {
9248		ctl_set_success(ctsio);
9249		ctl_done((union ctl_io *)ctsio);
9250		return (CTL_RETVAL_COMPLETE);
9251	}
9252
9253	/* Set FUA if write cache is disabled. */
9254	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9255	    SCP_WCE) == 0)
9256		flags |= CTL_LLF_FUA;
9257
9258	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9259	ctsio->kern_rel_offset = 0;
9260
9261	/*
9262	 * Set the IO_CONT flag, so that if this I/O gets passed to
9263	 * ctl_data_submit_done(), it'll get passed back to
9264	 * ctl_ctl_cnw_cont() for further processing.
9265	 */
9266	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9267	ctsio->io_cont = ctl_cnw_cont;
9268
9269	lbalen = (struct ctl_lba_len_flags *)
9270	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9271	lbalen->lba = lba;
9272	lbalen->len = num_blocks;
9273	lbalen->flags = CTL_LLF_COMPARE | flags;
9274
9275	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9276	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9277	return (retval);
9278}
9279
9280int
9281ctl_verify(struct ctl_scsiio *ctsio)
9282{
9283	struct ctl_lun *lun;
9284	struct ctl_lba_len_flags *lbalen;
9285	uint64_t lba;
9286	uint32_t num_blocks;
9287	int bytchk, flags;
9288	int retval;
9289
9290	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9291
9292	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9293
9294	bytchk = 0;
9295	flags = CTL_LLF_FUA;
9296	retval = CTL_RETVAL_COMPLETE;
9297
9298	switch (ctsio->cdb[0]) {
9299	case VERIFY_10: {
9300		struct scsi_verify_10 *cdb;
9301
9302		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9303		if (cdb->byte2 & SVFY_BYTCHK)
9304			bytchk = 1;
9305		if (cdb->byte2 & SVFY_DPO)
9306			flags |= CTL_LLF_DPO;
9307		lba = scsi_4btoul(cdb->addr);
9308		num_blocks = scsi_2btoul(cdb->length);
9309		break;
9310	}
9311	case VERIFY_12: {
9312		struct scsi_verify_12 *cdb;
9313
9314		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9315		if (cdb->byte2 & SVFY_BYTCHK)
9316			bytchk = 1;
9317		if (cdb->byte2 & SVFY_DPO)
9318			flags |= CTL_LLF_DPO;
9319		lba = scsi_4btoul(cdb->addr);
9320		num_blocks = scsi_4btoul(cdb->length);
9321		break;
9322	}
9323	case VERIFY_16: {
9324		struct scsi_rw_16 *cdb;
9325
9326		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9327		if (cdb->byte2 & SVFY_BYTCHK)
9328			bytchk = 1;
9329		if (cdb->byte2 & SVFY_DPO)
9330			flags |= CTL_LLF_DPO;
9331		lba = scsi_8btou64(cdb->addr);
9332		num_blocks = scsi_4btoul(cdb->length);
9333		break;
9334	}
9335	default:
9336		/*
9337		 * We got a command we don't support.  This shouldn't
9338		 * happen, commands should be filtered out above us.
9339		 */
9340		ctl_set_invalid_opcode(ctsio);
9341		ctl_done((union ctl_io *)ctsio);
9342		return (CTL_RETVAL_COMPLETE);
9343	}
9344
9345	/*
9346	 * The first check is to make sure we're in bounds, the second
9347	 * check is to catch wrap-around problems.  If the lba + num blocks
9348	 * is less than the lba, then we've wrapped around and the block
9349	 * range is invalid anyway.
9350	 */
9351	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9352	 || ((lba + num_blocks) < lba)) {
9353		ctl_set_lba_out_of_range(ctsio);
9354		ctl_done((union ctl_io *)ctsio);
9355		return (CTL_RETVAL_COMPLETE);
9356	}
9357
9358	/*
9359	 * According to SBC-3, a transfer length of 0 is not an error.
9360	 */
9361	if (num_blocks == 0) {
9362		ctl_set_success(ctsio);
9363		ctl_done((union ctl_io *)ctsio);
9364		return (CTL_RETVAL_COMPLETE);
9365	}
9366
9367	lbalen = (struct ctl_lba_len_flags *)
9368	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9369	lbalen->lba = lba;
9370	lbalen->len = num_blocks;
9371	if (bytchk) {
9372		lbalen->flags = CTL_LLF_COMPARE | flags;
9373		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9374	} else {
9375		lbalen->flags = CTL_LLF_VERIFY | flags;
9376		ctsio->kern_total_len = 0;
9377	}
9378	ctsio->kern_rel_offset = 0;
9379
9380	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9381	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9382	return (retval);
9383}
9384
9385int
9386ctl_report_luns(struct ctl_scsiio *ctsio)
9387{
9388	struct scsi_report_luns *cdb;
9389	struct scsi_report_luns_data *lun_data;
9390	struct ctl_lun *lun, *request_lun;
9391	int num_luns, retval;
9392	uint32_t alloc_len, lun_datalen;
9393	int num_filled, well_known;
9394	uint32_t initidx, targ_lun_id, lun_id;
9395
9396	retval = CTL_RETVAL_COMPLETE;
9397	well_known = 0;
9398
9399	cdb = (struct scsi_report_luns *)ctsio->cdb;
9400
9401	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9402
9403	mtx_lock(&control_softc->ctl_lock);
9404	num_luns = control_softc->num_luns;
9405	mtx_unlock(&control_softc->ctl_lock);
9406
9407	switch (cdb->select_report) {
9408	case RPL_REPORT_DEFAULT:
9409	case RPL_REPORT_ALL:
9410		break;
9411	case RPL_REPORT_WELLKNOWN:
9412		well_known = 1;
9413		num_luns = 0;
9414		break;
9415	default:
9416		ctl_set_invalid_field(ctsio,
9417				      /*sks_valid*/ 1,
9418				      /*command*/ 1,
9419				      /*field*/ 2,
9420				      /*bit_valid*/ 0,
9421				      /*bit*/ 0);
9422		ctl_done((union ctl_io *)ctsio);
9423		return (retval);
9424		break; /* NOTREACHED */
9425	}
9426
9427	alloc_len = scsi_4btoul(cdb->length);
9428	/*
9429	 * The initiator has to allocate at least 16 bytes for this request,
9430	 * so he can at least get the header and the first LUN.  Otherwise
9431	 * we reject the request (per SPC-3 rev 14, section 6.21).
9432	 */
9433	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9434	    sizeof(struct scsi_report_luns_lundata))) {
9435		ctl_set_invalid_field(ctsio,
9436				      /*sks_valid*/ 1,
9437				      /*command*/ 1,
9438				      /*field*/ 6,
9439				      /*bit_valid*/ 0,
9440				      /*bit*/ 0);
9441		ctl_done((union ctl_io *)ctsio);
9442		return (retval);
9443	}
9444
9445	request_lun = (struct ctl_lun *)
9446		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9447
9448	lun_datalen = sizeof(*lun_data) +
9449		(num_luns * sizeof(struct scsi_report_luns_lundata));
9450
9451	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9452	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9453	ctsio->kern_sg_entries = 0;
9454
9455	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9456
9457	mtx_lock(&control_softc->ctl_lock);
9458	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9459		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9460		if (lun_id >= CTL_MAX_LUNS)
9461			continue;
9462		lun = control_softc->ctl_luns[lun_id];
9463		if (lun == NULL)
9464			continue;
9465
9466		if (targ_lun_id <= 0xff) {
9467			/*
9468			 * Peripheral addressing method, bus number 0.
9469			 */
9470			lun_data->luns[num_filled].lundata[0] =
9471				RPL_LUNDATA_ATYP_PERIPH;
9472			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9473			num_filled++;
9474		} else if (targ_lun_id <= 0x3fff) {
9475			/*
9476			 * Flat addressing method.
9477			 */
9478			lun_data->luns[num_filled].lundata[0] =
9479				RPL_LUNDATA_ATYP_FLAT |
9480				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9481#ifdef OLDCTLHEADERS
9482				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9483				(targ_lun_id & SRLD_BUS_LUN_MASK);
9484#endif
9485			lun_data->luns[num_filled].lundata[1] =
9486#ifdef OLDCTLHEADERS
9487				targ_lun_id >> SRLD_BUS_LUN_BITS;
9488#endif
9489				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9490			num_filled++;
9491		} else {
9492			printf("ctl_report_luns: bogus LUN number %jd, "
9493			       "skipping\n", (intmax_t)targ_lun_id);
9494		}
9495		/*
9496		 * According to SPC-3, rev 14 section 6.21:
9497		 *
9498		 * "The execution of a REPORT LUNS command to any valid and
9499		 * installed logical unit shall clear the REPORTED LUNS DATA
9500		 * HAS CHANGED unit attention condition for all logical
9501		 * units of that target with respect to the requesting
9502		 * initiator. A valid and installed logical unit is one
9503		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9504		 * INQUIRY data (see 6.4.2)."
9505		 *
9506		 * If request_lun is NULL, the LUN this report luns command
9507		 * was issued to is either disabled or doesn't exist. In that
9508		 * case, we shouldn't clear any pending lun change unit
9509		 * attention.
9510		 */
9511		if (request_lun != NULL) {
9512			mtx_lock(&lun->lun_lock);
9513			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9514			mtx_unlock(&lun->lun_lock);
9515		}
9516	}
9517	mtx_unlock(&control_softc->ctl_lock);
9518
9519	/*
9520	 * It's quite possible that we've returned fewer LUNs than we allocated
9521	 * space for.  Trim it.
9522	 */
9523	lun_datalen = sizeof(*lun_data) +
9524		(num_filled * sizeof(struct scsi_report_luns_lundata));
9525
9526	if (lun_datalen < alloc_len) {
9527		ctsio->residual = alloc_len - lun_datalen;
9528		ctsio->kern_data_len = lun_datalen;
9529		ctsio->kern_total_len = lun_datalen;
9530	} else {
9531		ctsio->residual = 0;
9532		ctsio->kern_data_len = alloc_len;
9533		ctsio->kern_total_len = alloc_len;
9534	}
9535	ctsio->kern_data_resid = 0;
9536	ctsio->kern_rel_offset = 0;
9537	ctsio->kern_sg_entries = 0;
9538
9539	/*
9540	 * We set this to the actual data length, regardless of how much
9541	 * space we actually have to return results.  If the user looks at
9542	 * this value, he'll know whether or not he allocated enough space
9543	 * and reissue the command if necessary.  We don't support well
9544	 * known logical units, so if the user asks for that, return none.
9545	 */
9546	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9547
9548	/*
9549	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9550	 * this request.
9551	 */
9552	ctsio->scsi_status = SCSI_STATUS_OK;
9553
9554	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9555	ctsio->be_move_done = ctl_config_move_done;
9556	ctl_datamove((union ctl_io *)ctsio);
9557
9558	return (retval);
9559}
9560
9561int
9562ctl_request_sense(struct ctl_scsiio *ctsio)
9563{
9564	struct scsi_request_sense *cdb;
9565	struct scsi_sense_data *sense_ptr;
9566	struct ctl_lun *lun;
9567	uint32_t initidx;
9568	int have_error;
9569	scsi_sense_data_type sense_format;
9570
9571	cdb = (struct scsi_request_sense *)ctsio->cdb;
9572
9573	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9574
9575	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9576
9577	/*
9578	 * Determine which sense format the user wants.
9579	 */
9580	if (cdb->byte2 & SRS_DESC)
9581		sense_format = SSD_TYPE_DESC;
9582	else
9583		sense_format = SSD_TYPE_FIXED;
9584
9585	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9586	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9587	ctsio->kern_sg_entries = 0;
9588
9589	/*
9590	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9591	 * larger than the largest allowed value for the length field in the
9592	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9593	 */
9594	ctsio->residual = 0;
9595	ctsio->kern_data_len = cdb->length;
9596	ctsio->kern_total_len = cdb->length;
9597
9598	ctsio->kern_data_resid = 0;
9599	ctsio->kern_rel_offset = 0;
9600	ctsio->kern_sg_entries = 0;
9601
9602	/*
9603	 * If we don't have a LUN, we don't have any pending sense.
9604	 */
9605	if (lun == NULL)
9606		goto no_sense;
9607
9608	have_error = 0;
9609	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9610	/*
9611	 * Check for pending sense, and then for pending unit attentions.
9612	 * Pending sense gets returned first, then pending unit attentions.
9613	 */
9614	mtx_lock(&lun->lun_lock);
9615#ifdef CTL_WITH_CA
9616	if (ctl_is_set(lun->have_ca, initidx)) {
9617		scsi_sense_data_type stored_format;
9618
9619		/*
9620		 * Check to see which sense format was used for the stored
9621		 * sense data.
9622		 */
9623		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9624
9625		/*
9626		 * If the user requested a different sense format than the
9627		 * one we stored, then we need to convert it to the other
9628		 * format.  If we're going from descriptor to fixed format
9629		 * sense data, we may lose things in translation, depending
9630		 * on what options were used.
9631		 *
9632		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9633		 * for some reason we'll just copy it out as-is.
9634		 */
9635		if ((stored_format == SSD_TYPE_FIXED)
9636		 && (sense_format == SSD_TYPE_DESC))
9637			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9638			    &lun->pending_sense[initidx],
9639			    (struct scsi_sense_data_desc *)sense_ptr);
9640		else if ((stored_format == SSD_TYPE_DESC)
9641		      && (sense_format == SSD_TYPE_FIXED))
9642			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9643			    &lun->pending_sense[initidx],
9644			    (struct scsi_sense_data_fixed *)sense_ptr);
9645		else
9646			memcpy(sense_ptr, &lun->pending_sense[initidx],
9647			       ctl_min(sizeof(*sense_ptr),
9648			       sizeof(lun->pending_sense[initidx])));
9649
9650		ctl_clear_mask(lun->have_ca, initidx);
9651		have_error = 1;
9652	} else
9653#endif
9654	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9655		ctl_ua_type ua_type;
9656
9657		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9658				       sense_ptr, sense_format);
9659		if (ua_type != CTL_UA_NONE)
9660			have_error = 1;
9661	}
9662	mtx_unlock(&lun->lun_lock);
9663
9664	/*
9665	 * We already have a pending error, return it.
9666	 */
9667	if (have_error != 0) {
9668		/*
9669		 * We report the SCSI status as OK, since the status of the
9670		 * request sense command itself is OK.
9671		 */
9672		ctsio->scsi_status = SCSI_STATUS_OK;
9673
9674		/*
9675		 * We report 0 for the sense length, because we aren't doing
9676		 * autosense in this case.  We're reporting sense as
9677		 * parameter data.
9678		 */
9679		ctsio->sense_len = 0;
9680		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9681		ctsio->be_move_done = ctl_config_move_done;
9682		ctl_datamove((union ctl_io *)ctsio);
9683
9684		return (CTL_RETVAL_COMPLETE);
9685	}
9686
9687no_sense:
9688
9689	/*
9690	 * No sense information to report, so we report that everything is
9691	 * okay.
9692	 */
9693	ctl_set_sense_data(sense_ptr,
9694			   lun,
9695			   sense_format,
9696			   /*current_error*/ 1,
9697			   /*sense_key*/ SSD_KEY_NO_SENSE,
9698			   /*asc*/ 0x00,
9699			   /*ascq*/ 0x00,
9700			   SSD_ELEM_NONE);
9701
9702	ctsio->scsi_status = SCSI_STATUS_OK;
9703
9704	/*
9705	 * We report 0 for the sense length, because we aren't doing
9706	 * autosense in this case.  We're reporting sense as parameter data.
9707	 */
9708	ctsio->sense_len = 0;
9709	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9710	ctsio->be_move_done = ctl_config_move_done;
9711	ctl_datamove((union ctl_io *)ctsio);
9712
9713	return (CTL_RETVAL_COMPLETE);
9714}
9715
9716int
9717ctl_tur(struct ctl_scsiio *ctsio)
9718{
9719	struct ctl_lun *lun;
9720
9721	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9722
9723	CTL_DEBUG_PRINT(("ctl_tur\n"));
9724
9725	if (lun == NULL)
9726		return (EINVAL);
9727
9728	ctsio->scsi_status = SCSI_STATUS_OK;
9729	ctsio->io_hdr.status = CTL_SUCCESS;
9730
9731	ctl_done((union ctl_io *)ctsio);
9732
9733	return (CTL_RETVAL_COMPLETE);
9734}
9735
9736#ifdef notyet
9737static int
9738ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9739{
9740
9741}
9742#endif
9743
9744static int
9745ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9746{
9747	struct scsi_vpd_supported_pages *pages;
9748	int sup_page_size;
9749	struct ctl_lun *lun;
9750
9751	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9752
9753	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9754	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9755	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9756	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9757	ctsio->kern_sg_entries = 0;
9758
9759	if (sup_page_size < alloc_len) {
9760		ctsio->residual = alloc_len - sup_page_size;
9761		ctsio->kern_data_len = sup_page_size;
9762		ctsio->kern_total_len = sup_page_size;
9763	} else {
9764		ctsio->residual = 0;
9765		ctsio->kern_data_len = alloc_len;
9766		ctsio->kern_total_len = alloc_len;
9767	}
9768	ctsio->kern_data_resid = 0;
9769	ctsio->kern_rel_offset = 0;
9770	ctsio->kern_sg_entries = 0;
9771
9772	/*
9773	 * The control device is always connected.  The disk device, on the
9774	 * other hand, may not be online all the time.  Need to change this
9775	 * to figure out whether the disk device is actually online or not.
9776	 */
9777	if (lun != NULL)
9778		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9779				lun->be_lun->lun_type;
9780	else
9781		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9782
9783	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9784	/* Supported VPD pages */
9785	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9786	/* Serial Number */
9787	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9788	/* Device Identification */
9789	pages->page_list[2] = SVPD_DEVICE_ID;
9790	/* Extended INQUIRY Data */
9791	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9792	/* Mode Page Policy */
9793	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9794	/* SCSI Ports */
9795	pages->page_list[5] = SVPD_SCSI_PORTS;
9796	/* Third-party Copy */
9797	pages->page_list[6] = SVPD_SCSI_TPC;
9798	/* Block limits */
9799	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9800	/* Block Device Characteristics */
9801	pages->page_list[8] = SVPD_BDC;
9802	/* Logical Block Provisioning */
9803	pages->page_list[9] = SVPD_LBP;
9804
9805	ctsio->scsi_status = SCSI_STATUS_OK;
9806
9807	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9808	ctsio->be_move_done = ctl_config_move_done;
9809	ctl_datamove((union ctl_io *)ctsio);
9810
9811	return (CTL_RETVAL_COMPLETE);
9812}
9813
9814static int
9815ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9816{
9817	struct scsi_vpd_unit_serial_number *sn_ptr;
9818	struct ctl_lun *lun;
9819
9820	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9821
9822	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9823	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9824	ctsio->kern_sg_entries = 0;
9825
9826	if (sizeof(*sn_ptr) < alloc_len) {
9827		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9828		ctsio->kern_data_len = sizeof(*sn_ptr);
9829		ctsio->kern_total_len = sizeof(*sn_ptr);
9830	} else {
9831		ctsio->residual = 0;
9832		ctsio->kern_data_len = alloc_len;
9833		ctsio->kern_total_len = alloc_len;
9834	}
9835	ctsio->kern_data_resid = 0;
9836	ctsio->kern_rel_offset = 0;
9837	ctsio->kern_sg_entries = 0;
9838
9839	/*
9840	 * The control device is always connected.  The disk device, on the
9841	 * other hand, may not be online all the time.  Need to change this
9842	 * to figure out whether the disk device is actually online or not.
9843	 */
9844	if (lun != NULL)
9845		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9846				  lun->be_lun->lun_type;
9847	else
9848		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9849
9850	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9851	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9852	/*
9853	 * If we don't have a LUN, we just leave the serial number as
9854	 * all spaces.
9855	 */
9856	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9857	if (lun != NULL) {
9858		strncpy((char *)sn_ptr->serial_num,
9859			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9860	}
9861	ctsio->scsi_status = SCSI_STATUS_OK;
9862
9863	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9864	ctsio->be_move_done = ctl_config_move_done;
9865	ctl_datamove((union ctl_io *)ctsio);
9866
9867	return (CTL_RETVAL_COMPLETE);
9868}
9869
9870
9871static int
9872ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9873{
9874	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9875	struct ctl_lun *lun;
9876	int data_len;
9877
9878	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9879
9880	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9881	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9882	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9883	ctsio->kern_sg_entries = 0;
9884
9885	if (data_len < alloc_len) {
9886		ctsio->residual = alloc_len - data_len;
9887		ctsio->kern_data_len = data_len;
9888		ctsio->kern_total_len = data_len;
9889	} else {
9890		ctsio->residual = 0;
9891		ctsio->kern_data_len = alloc_len;
9892		ctsio->kern_total_len = alloc_len;
9893	}
9894	ctsio->kern_data_resid = 0;
9895	ctsio->kern_rel_offset = 0;
9896	ctsio->kern_sg_entries = 0;
9897
9898	/*
9899	 * The control device is always connected.  The disk device, on the
9900	 * other hand, may not be online all the time.
9901	 */
9902	if (lun != NULL)
9903		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9904				     lun->be_lun->lun_type;
9905	else
9906		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9907	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9908	eid_ptr->page_length = data_len - 4;
9909	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9910	eid_ptr->flags3 = SVPD_EID_V_SUP;
9911
9912	ctsio->scsi_status = SCSI_STATUS_OK;
9913	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9914	ctsio->be_move_done = ctl_config_move_done;
9915	ctl_datamove((union ctl_io *)ctsio);
9916
9917	return (CTL_RETVAL_COMPLETE);
9918}
9919
9920static int
9921ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9922{
9923	struct scsi_vpd_mode_page_policy *mpp_ptr;
9924	struct ctl_lun *lun;
9925	int data_len;
9926
9927	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9928
9929	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9930	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9931
9932	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9933	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9934	ctsio->kern_sg_entries = 0;
9935
9936	if (data_len < alloc_len) {
9937		ctsio->residual = alloc_len - data_len;
9938		ctsio->kern_data_len = data_len;
9939		ctsio->kern_total_len = data_len;
9940	} else {
9941		ctsio->residual = 0;
9942		ctsio->kern_data_len = alloc_len;
9943		ctsio->kern_total_len = alloc_len;
9944	}
9945	ctsio->kern_data_resid = 0;
9946	ctsio->kern_rel_offset = 0;
9947	ctsio->kern_sg_entries = 0;
9948
9949	/*
9950	 * The control device is always connected.  The disk device, on the
9951	 * other hand, may not be online all the time.
9952	 */
9953	if (lun != NULL)
9954		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9955				     lun->be_lun->lun_type;
9956	else
9957		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9958	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9959	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9960	mpp_ptr->descr[0].page_code = 0x3f;
9961	mpp_ptr->descr[0].subpage_code = 0xff;
9962	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9963
9964	ctsio->scsi_status = SCSI_STATUS_OK;
9965	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9966	ctsio->be_move_done = ctl_config_move_done;
9967	ctl_datamove((union ctl_io *)ctsio);
9968
9969	return (CTL_RETVAL_COMPLETE);
9970}
9971
9972static int
9973ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9974{
9975	struct scsi_vpd_device_id *devid_ptr;
9976	struct scsi_vpd_id_descriptor *desc;
9977	struct ctl_softc *ctl_softc;
9978	struct ctl_lun *lun;
9979	struct ctl_port *port;
9980	int data_len;
9981	uint8_t proto;
9982
9983	ctl_softc = control_softc;
9984
9985	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9986	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9987
9988	data_len = sizeof(struct scsi_vpd_device_id) +
9989	    sizeof(struct scsi_vpd_id_descriptor) +
9990		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9991	    sizeof(struct scsi_vpd_id_descriptor) +
9992		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9993	if (lun && lun->lun_devid)
9994		data_len += lun->lun_devid->len;
9995	if (port->port_devid)
9996		data_len += port->port_devid->len;
9997	if (port->target_devid)
9998		data_len += port->target_devid->len;
9999
10000	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10001	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10002	ctsio->kern_sg_entries = 0;
10003
10004	if (data_len < alloc_len) {
10005		ctsio->residual = alloc_len - data_len;
10006		ctsio->kern_data_len = data_len;
10007		ctsio->kern_total_len = data_len;
10008	} else {
10009		ctsio->residual = 0;
10010		ctsio->kern_data_len = alloc_len;
10011		ctsio->kern_total_len = alloc_len;
10012	}
10013	ctsio->kern_data_resid = 0;
10014	ctsio->kern_rel_offset = 0;
10015	ctsio->kern_sg_entries = 0;
10016
10017	/*
10018	 * The control device is always connected.  The disk device, on the
10019	 * other hand, may not be online all the time.
10020	 */
10021	if (lun != NULL)
10022		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10023				     lun->be_lun->lun_type;
10024	else
10025		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10026	devid_ptr->page_code = SVPD_DEVICE_ID;
10027	scsi_ulto2b(data_len - 4, devid_ptr->length);
10028
10029	if (port->port_type == CTL_PORT_FC)
10030		proto = SCSI_PROTO_FC << 4;
10031	else if (port->port_type == CTL_PORT_ISCSI)
10032		proto = SCSI_PROTO_ISCSI << 4;
10033	else
10034		proto = SCSI_PROTO_SPI << 4;
10035	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10036
10037	/*
10038	 * We're using a LUN association here.  i.e., this device ID is a
10039	 * per-LUN identifier.
10040	 */
10041	if (lun && lun->lun_devid) {
10042		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10043		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10044		    lun->lun_devid->len);
10045	}
10046
10047	/*
10048	 * This is for the WWPN which is a port association.
10049	 */
10050	if (port->port_devid) {
10051		memcpy(desc, port->port_devid->data, port->port_devid->len);
10052		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10053		    port->port_devid->len);
10054	}
10055
10056	/*
10057	 * This is for the Relative Target Port(type 4h) identifier
10058	 */
10059	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10060	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10061	    SVPD_ID_TYPE_RELTARG;
10062	desc->length = 4;
10063	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10064	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10065	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10066
10067	/*
10068	 * This is for the Target Port Group(type 5h) identifier
10069	 */
10070	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10071	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10072	    SVPD_ID_TYPE_TPORTGRP;
10073	desc->length = 4;
10074	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10075	    &desc->identifier[2]);
10076	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10077	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10078
10079	/*
10080	 * This is for the Target identifier
10081	 */
10082	if (port->target_devid) {
10083		memcpy(desc, port->target_devid->data, port->target_devid->len);
10084	}
10085
10086	ctsio->scsi_status = SCSI_STATUS_OK;
10087	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10088	ctsio->be_move_done = ctl_config_move_done;
10089	ctl_datamove((union ctl_io *)ctsio);
10090
10091	return (CTL_RETVAL_COMPLETE);
10092}
10093
10094static int
10095ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10096{
10097	struct ctl_softc *softc = control_softc;
10098	struct scsi_vpd_scsi_ports *sp;
10099	struct scsi_vpd_port_designation *pd;
10100	struct scsi_vpd_port_designation_cont *pdc;
10101	struct ctl_lun *lun;
10102	struct ctl_port *port;
10103	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10104	int num_target_port_groups, single;
10105
10106	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10107
10108	single = ctl_is_single;
10109	if (single)
10110		num_target_port_groups = 1;
10111	else
10112		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10113	num_target_ports = 0;
10114	iid_len = 0;
10115	id_len = 0;
10116	mtx_lock(&softc->ctl_lock);
10117	STAILQ_FOREACH(port, &softc->port_list, links) {
10118		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10119			continue;
10120		if (lun != NULL &&
10121		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10122		    CTL_MAX_LUNS)
10123			continue;
10124		num_target_ports++;
10125		if (port->init_devid)
10126			iid_len += port->init_devid->len;
10127		if (port->port_devid)
10128			id_len += port->port_devid->len;
10129	}
10130	mtx_unlock(&softc->ctl_lock);
10131
10132	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10133	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10134	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10135	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10136	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10137	ctsio->kern_sg_entries = 0;
10138
10139	if (data_len < alloc_len) {
10140		ctsio->residual = alloc_len - data_len;
10141		ctsio->kern_data_len = data_len;
10142		ctsio->kern_total_len = data_len;
10143	} else {
10144		ctsio->residual = 0;
10145		ctsio->kern_data_len = alloc_len;
10146		ctsio->kern_total_len = alloc_len;
10147	}
10148	ctsio->kern_data_resid = 0;
10149	ctsio->kern_rel_offset = 0;
10150	ctsio->kern_sg_entries = 0;
10151
10152	/*
10153	 * The control device is always connected.  The disk device, on the
10154	 * other hand, may not be online all the time.  Need to change this
10155	 * to figure out whether the disk device is actually online or not.
10156	 */
10157	if (lun != NULL)
10158		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10159				  lun->be_lun->lun_type;
10160	else
10161		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10162
10163	sp->page_code = SVPD_SCSI_PORTS;
10164	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10165	    sp->page_length);
10166	pd = &sp->design[0];
10167
10168	mtx_lock(&softc->ctl_lock);
10169	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10170		pg = 0;
10171	else
10172		pg = 1;
10173	for (g = 0; g < num_target_port_groups; g++) {
10174		STAILQ_FOREACH(port, &softc->port_list, links) {
10175			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10176				continue;
10177			if (lun != NULL &&
10178			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10179			    CTL_MAX_LUNS)
10180				continue;
10181			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10182			scsi_ulto2b(p, pd->relative_port_id);
10183			if (port->init_devid && g == pg) {
10184				iid_len = port->init_devid->len;
10185				memcpy(pd->initiator_transportid,
10186				    port->init_devid->data, port->init_devid->len);
10187			} else
10188				iid_len = 0;
10189			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10190			pdc = (struct scsi_vpd_port_designation_cont *)
10191			    (&pd->initiator_transportid[iid_len]);
10192			if (port->port_devid && g == pg) {
10193				id_len = port->port_devid->len;
10194				memcpy(pdc->target_port_descriptors,
10195				    port->port_devid->data, port->port_devid->len);
10196			} else
10197				id_len = 0;
10198			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10199			pd = (struct scsi_vpd_port_designation *)
10200			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10201		}
10202	}
10203	mtx_unlock(&softc->ctl_lock);
10204
10205	ctsio->scsi_status = SCSI_STATUS_OK;
10206	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10207	ctsio->be_move_done = ctl_config_move_done;
10208	ctl_datamove((union ctl_io *)ctsio);
10209
10210	return (CTL_RETVAL_COMPLETE);
10211}
10212
10213static int
10214ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10215{
10216	struct scsi_vpd_block_limits *bl_ptr;
10217	struct ctl_lun *lun;
10218	int bs;
10219
10220	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10221
10222	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10223	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10224	ctsio->kern_sg_entries = 0;
10225
10226	if (sizeof(*bl_ptr) < alloc_len) {
10227		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10228		ctsio->kern_data_len = sizeof(*bl_ptr);
10229		ctsio->kern_total_len = sizeof(*bl_ptr);
10230	} else {
10231		ctsio->residual = 0;
10232		ctsio->kern_data_len = alloc_len;
10233		ctsio->kern_total_len = alloc_len;
10234	}
10235	ctsio->kern_data_resid = 0;
10236	ctsio->kern_rel_offset = 0;
10237	ctsio->kern_sg_entries = 0;
10238
10239	/*
10240	 * The control device is always connected.  The disk device, on the
10241	 * other hand, may not be online all the time.  Need to change this
10242	 * to figure out whether the disk device is actually online or not.
10243	 */
10244	if (lun != NULL)
10245		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10246				  lun->be_lun->lun_type;
10247	else
10248		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10249
10250	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10251	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10252	bl_ptr->max_cmp_write_len = 0xff;
10253	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10254	if (lun != NULL) {
10255		bs = lun->be_lun->blocksize;
10256		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10257		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10258			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10259			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10260			if (lun->be_lun->pblockexp != 0) {
10261				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10262				    bl_ptr->opt_unmap_grain);
10263				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10264				    bl_ptr->unmap_grain_align);
10265			}
10266		}
10267		scsi_ulto4b(lun->be_lun->atomicblock,
10268		    bl_ptr->max_atomic_transfer_length);
10269		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10270		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10271	}
10272	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10273
10274	ctsio->scsi_status = SCSI_STATUS_OK;
10275	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10276	ctsio->be_move_done = ctl_config_move_done;
10277	ctl_datamove((union ctl_io *)ctsio);
10278
10279	return (CTL_RETVAL_COMPLETE);
10280}
10281
10282static int
10283ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10284{
10285	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10286	struct ctl_lun *lun;
10287
10288	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10289
10290	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10291	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10292	ctsio->kern_sg_entries = 0;
10293
10294	if (sizeof(*bdc_ptr) < alloc_len) {
10295		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10296		ctsio->kern_data_len = sizeof(*bdc_ptr);
10297		ctsio->kern_total_len = sizeof(*bdc_ptr);
10298	} else {
10299		ctsio->residual = 0;
10300		ctsio->kern_data_len = alloc_len;
10301		ctsio->kern_total_len = alloc_len;
10302	}
10303	ctsio->kern_data_resid = 0;
10304	ctsio->kern_rel_offset = 0;
10305	ctsio->kern_sg_entries = 0;
10306
10307	/*
10308	 * The control device is always connected.  The disk device, on the
10309	 * other hand, may not be online all the time.  Need to change this
10310	 * to figure out whether the disk device is actually online or not.
10311	 */
10312	if (lun != NULL)
10313		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10314				  lun->be_lun->lun_type;
10315	else
10316		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10317	bdc_ptr->page_code = SVPD_BDC;
10318	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10319	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10320	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10321
10322	ctsio->scsi_status = SCSI_STATUS_OK;
10323	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10324	ctsio->be_move_done = ctl_config_move_done;
10325	ctl_datamove((union ctl_io *)ctsio);
10326
10327	return (CTL_RETVAL_COMPLETE);
10328}
10329
10330static int
10331ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10332{
10333	struct scsi_vpd_logical_block_prov *lbp_ptr;
10334	struct ctl_lun *lun;
10335
10336	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10337
10338	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10339	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10340	ctsio->kern_sg_entries = 0;
10341
10342	if (sizeof(*lbp_ptr) < alloc_len) {
10343		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10344		ctsio->kern_data_len = sizeof(*lbp_ptr);
10345		ctsio->kern_total_len = sizeof(*lbp_ptr);
10346	} else {
10347		ctsio->residual = 0;
10348		ctsio->kern_data_len = alloc_len;
10349		ctsio->kern_total_len = alloc_len;
10350	}
10351	ctsio->kern_data_resid = 0;
10352	ctsio->kern_rel_offset = 0;
10353	ctsio->kern_sg_entries = 0;
10354
10355	/*
10356	 * The control device is always connected.  The disk device, on the
10357	 * other hand, may not be online all the time.  Need to change this
10358	 * to figure out whether the disk device is actually online or not.
10359	 */
10360	if (lun != NULL)
10361		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10362				  lun->be_lun->lun_type;
10363	else
10364		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10365
10366	lbp_ptr->page_code = SVPD_LBP;
10367	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10368	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10369		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10370		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10371		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10372	}
10373
10374	ctsio->scsi_status = SCSI_STATUS_OK;
10375	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10376	ctsio->be_move_done = ctl_config_move_done;
10377	ctl_datamove((union ctl_io *)ctsio);
10378
10379	return (CTL_RETVAL_COMPLETE);
10380}
10381
10382static int
10383ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10384{
10385	struct scsi_inquiry *cdb;
10386	struct ctl_lun *lun;
10387	int alloc_len, retval;
10388
10389	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10390	cdb = (struct scsi_inquiry *)ctsio->cdb;
10391
10392	retval = CTL_RETVAL_COMPLETE;
10393
10394	alloc_len = scsi_2btoul(cdb->length);
10395
10396	switch (cdb->page_code) {
10397	case SVPD_SUPPORTED_PAGES:
10398		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10399		break;
10400	case SVPD_UNIT_SERIAL_NUMBER:
10401		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10402		break;
10403	case SVPD_DEVICE_ID:
10404		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10405		break;
10406	case SVPD_EXTENDED_INQUIRY_DATA:
10407		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10408		break;
10409	case SVPD_MODE_PAGE_POLICY:
10410		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10411		break;
10412	case SVPD_SCSI_PORTS:
10413		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10414		break;
10415	case SVPD_SCSI_TPC:
10416		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10417		break;
10418	case SVPD_BLOCK_LIMITS:
10419		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10420		break;
10421	case SVPD_BDC:
10422		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10423		break;
10424	case SVPD_LBP:
10425		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10426		break;
10427	default:
10428		ctl_set_invalid_field(ctsio,
10429				      /*sks_valid*/ 1,
10430				      /*command*/ 1,
10431				      /*field*/ 2,
10432				      /*bit_valid*/ 0,
10433				      /*bit*/ 0);
10434		ctl_done((union ctl_io *)ctsio);
10435		retval = CTL_RETVAL_COMPLETE;
10436		break;
10437	}
10438
10439	return (retval);
10440}
10441
10442static int
10443ctl_inquiry_std(struct ctl_scsiio *ctsio)
10444{
10445	struct scsi_inquiry_data *inq_ptr;
10446	struct scsi_inquiry *cdb;
10447	struct ctl_softc *ctl_softc;
10448	struct ctl_lun *lun;
10449	char *val;
10450	uint32_t alloc_len, data_len;
10451	ctl_port_type port_type;
10452
10453	ctl_softc = control_softc;
10454
10455	/*
10456	 * Figure out whether we're talking to a Fibre Channel port or not.
10457	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10458	 * SCSI front ends.
10459	 */
10460	port_type = ctl_softc->ctl_ports[
10461	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10462	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10463		port_type = CTL_PORT_SCSI;
10464
10465	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10466	cdb = (struct scsi_inquiry *)ctsio->cdb;
10467	alloc_len = scsi_2btoul(cdb->length);
10468
10469	/*
10470	 * We malloc the full inquiry data size here and fill it
10471	 * in.  If the user only asks for less, we'll give him
10472	 * that much.
10473	 */
10474	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10475	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10476	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10477	ctsio->kern_sg_entries = 0;
10478	ctsio->kern_data_resid = 0;
10479	ctsio->kern_rel_offset = 0;
10480
10481	if (data_len < alloc_len) {
10482		ctsio->residual = alloc_len - data_len;
10483		ctsio->kern_data_len = data_len;
10484		ctsio->kern_total_len = data_len;
10485	} else {
10486		ctsio->residual = 0;
10487		ctsio->kern_data_len = alloc_len;
10488		ctsio->kern_total_len = alloc_len;
10489	}
10490
10491	/*
10492	 * If we have a LUN configured, report it as connected.  Otherwise,
10493	 * report that it is offline or no device is supported, depending
10494	 * on the value of inquiry_pq_no_lun.
10495	 *
10496	 * According to the spec (SPC-4 r34), the peripheral qualifier
10497	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10498	 *
10499	 * "A peripheral device having the specified peripheral device type
10500	 * is not connected to this logical unit. However, the device
10501	 * server is capable of supporting the specified peripheral device
10502	 * type on this logical unit."
10503	 *
10504	 * According to the same spec, the peripheral qualifier
10505	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10506	 *
10507	 * "The device server is not capable of supporting a peripheral
10508	 * device on this logical unit. For this peripheral qualifier the
10509	 * peripheral device type shall be set to 1Fh. All other peripheral
10510	 * device type values are reserved for this peripheral qualifier."
10511	 *
10512	 * Given the text, it would seem that we probably want to report that
10513	 * the LUN is offline here.  There is no LUN connected, but we can
10514	 * support a LUN at the given LUN number.
10515	 *
10516	 * In the real world, though, it sounds like things are a little
10517	 * different:
10518	 *
10519	 * - Linux, when presented with a LUN with the offline peripheral
10520	 *   qualifier, will create an sg driver instance for it.  So when
10521	 *   you attach it to CTL, you wind up with a ton of sg driver
10522	 *   instances.  (One for every LUN that Linux bothered to probe.)
10523	 *   Linux does this despite the fact that it issues a REPORT LUNs
10524	 *   to LUN 0 to get the inventory of supported LUNs.
10525	 *
10526	 * - There is other anecdotal evidence (from Emulex folks) about
10527	 *   arrays that use the offline peripheral qualifier for LUNs that
10528	 *   are on the "passive" path in an active/passive array.
10529	 *
10530	 * So the solution is provide a hopefully reasonable default
10531	 * (return bad/no LUN) and allow the user to change the behavior
10532	 * with a tunable/sysctl variable.
10533	 */
10534	if (lun != NULL)
10535		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10536				  lun->be_lun->lun_type;
10537	else if (ctl_softc->inquiry_pq_no_lun == 0)
10538		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10539	else
10540		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10541
10542	/* RMB in byte 2 is 0 */
10543	inq_ptr->version = SCSI_REV_SPC4;
10544
10545	/*
10546	 * According to SAM-3, even if a device only supports a single
10547	 * level of LUN addressing, it should still set the HISUP bit:
10548	 *
10549	 * 4.9.1 Logical unit numbers overview
10550	 *
10551	 * All logical unit number formats described in this standard are
10552	 * hierarchical in structure even when only a single level in that
10553	 * hierarchy is used. The HISUP bit shall be set to one in the
10554	 * standard INQUIRY data (see SPC-2) when any logical unit number
10555	 * format described in this standard is used.  Non-hierarchical
10556	 * formats are outside the scope of this standard.
10557	 *
10558	 * Therefore we set the HiSup bit here.
10559	 *
10560	 * The reponse format is 2, per SPC-3.
10561	 */
10562	inq_ptr->response_format = SID_HiSup | 2;
10563
10564	inq_ptr->additional_length = data_len -
10565	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10566	CTL_DEBUG_PRINT(("additional_length = %d\n",
10567			 inq_ptr->additional_length));
10568
10569	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10570	/* 16 bit addressing */
10571	if (port_type == CTL_PORT_SCSI)
10572		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10573	/* XXX set the SID_MultiP bit here if we're actually going to
10574	   respond on multiple ports */
10575	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10576
10577	/* 16 bit data bus, synchronous transfers */
10578	if (port_type == CTL_PORT_SCSI)
10579		inq_ptr->flags = SID_WBus16 | SID_Sync;
10580	/*
10581	 * XXX KDM do we want to support tagged queueing on the control
10582	 * device at all?
10583	 */
10584	if ((lun == NULL)
10585	 || (lun->be_lun->lun_type != T_PROCESSOR))
10586		inq_ptr->flags |= SID_CmdQue;
10587	/*
10588	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10589	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10590	 * name and 4 bytes for the revision.
10591	 */
10592	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10593	    "vendor")) == NULL) {
10594		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10595	} else {
10596		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10597		strncpy(inq_ptr->vendor, val,
10598		    min(sizeof(inq_ptr->vendor), strlen(val)));
10599	}
10600	if (lun == NULL) {
10601		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10602		    sizeof(inq_ptr->product));
10603	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10604		switch (lun->be_lun->lun_type) {
10605		case T_DIRECT:
10606			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10607			    sizeof(inq_ptr->product));
10608			break;
10609		case T_PROCESSOR:
10610			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10611			    sizeof(inq_ptr->product));
10612			break;
10613		default:
10614			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10615			    sizeof(inq_ptr->product));
10616			break;
10617		}
10618	} else {
10619		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10620		strncpy(inq_ptr->product, val,
10621		    min(sizeof(inq_ptr->product), strlen(val)));
10622	}
10623
10624	/*
10625	 * XXX make this a macro somewhere so it automatically gets
10626	 * incremented when we make changes.
10627	 */
10628	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10629	    "revision")) == NULL) {
10630		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10631	} else {
10632		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10633		strncpy(inq_ptr->revision, val,
10634		    min(sizeof(inq_ptr->revision), strlen(val)));
10635	}
10636
10637	/*
10638	 * For parallel SCSI, we support double transition and single
10639	 * transition clocking.  We also support QAS (Quick Arbitration
10640	 * and Selection) and Information Unit transfers on both the
10641	 * control and array devices.
10642	 */
10643	if (port_type == CTL_PORT_SCSI)
10644		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10645				    SID_SPI_IUS;
10646
10647	/* SAM-5 (no version claimed) */
10648	scsi_ulto2b(0x00A0, inq_ptr->version1);
10649	/* SPC-4 (no version claimed) */
10650	scsi_ulto2b(0x0460, inq_ptr->version2);
10651	if (port_type == CTL_PORT_FC) {
10652		/* FCP-2 ANSI INCITS.350:2003 */
10653		scsi_ulto2b(0x0917, inq_ptr->version3);
10654	} else if (port_type == CTL_PORT_SCSI) {
10655		/* SPI-4 ANSI INCITS.362:200x */
10656		scsi_ulto2b(0x0B56, inq_ptr->version3);
10657	} else if (port_type == CTL_PORT_ISCSI) {
10658		/* iSCSI (no version claimed) */
10659		scsi_ulto2b(0x0960, inq_ptr->version3);
10660	} else if (port_type == CTL_PORT_SAS) {
10661		/* SAS (no version claimed) */
10662		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10663	}
10664
10665	if (lun == NULL) {
10666		/* SBC-4 (no version claimed) */
10667		scsi_ulto2b(0x0600, inq_ptr->version4);
10668	} else {
10669		switch (lun->be_lun->lun_type) {
10670		case T_DIRECT:
10671			/* SBC-4 (no version claimed) */
10672			scsi_ulto2b(0x0600, inq_ptr->version4);
10673			break;
10674		case T_PROCESSOR:
10675		default:
10676			break;
10677		}
10678	}
10679
10680	ctsio->scsi_status = SCSI_STATUS_OK;
10681	if (ctsio->kern_data_len > 0) {
10682		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10683		ctsio->be_move_done = ctl_config_move_done;
10684		ctl_datamove((union ctl_io *)ctsio);
10685	} else {
10686		ctsio->io_hdr.status = CTL_SUCCESS;
10687		ctl_done((union ctl_io *)ctsio);
10688	}
10689
10690	return (CTL_RETVAL_COMPLETE);
10691}
10692
10693int
10694ctl_inquiry(struct ctl_scsiio *ctsio)
10695{
10696	struct scsi_inquiry *cdb;
10697	int retval;
10698
10699	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10700
10701	cdb = (struct scsi_inquiry *)ctsio->cdb;
10702	if (cdb->byte2 & SI_EVPD)
10703		retval = ctl_inquiry_evpd(ctsio);
10704	else if (cdb->page_code == 0)
10705		retval = ctl_inquiry_std(ctsio);
10706	else {
10707		ctl_set_invalid_field(ctsio,
10708				      /*sks_valid*/ 1,
10709				      /*command*/ 1,
10710				      /*field*/ 2,
10711				      /*bit_valid*/ 0,
10712				      /*bit*/ 0);
10713		ctl_done((union ctl_io *)ctsio);
10714		return (CTL_RETVAL_COMPLETE);
10715	}
10716
10717	return (retval);
10718}
10719
10720/*
10721 * For known CDB types, parse the LBA and length.
10722 */
10723static int
10724ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10725{
10726	if (io->io_hdr.io_type != CTL_IO_SCSI)
10727		return (1);
10728
10729	switch (io->scsiio.cdb[0]) {
10730	case COMPARE_AND_WRITE: {
10731		struct scsi_compare_and_write *cdb;
10732
10733		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10734
10735		*lba = scsi_8btou64(cdb->addr);
10736		*len = cdb->length;
10737		break;
10738	}
10739	case READ_6:
10740	case WRITE_6: {
10741		struct scsi_rw_6 *cdb;
10742
10743		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10744
10745		*lba = scsi_3btoul(cdb->addr);
10746		/* only 5 bits are valid in the most significant address byte */
10747		*lba &= 0x1fffff;
10748		*len = cdb->length;
10749		break;
10750	}
10751	case READ_10:
10752	case WRITE_10: {
10753		struct scsi_rw_10 *cdb;
10754
10755		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10756
10757		*lba = scsi_4btoul(cdb->addr);
10758		*len = scsi_2btoul(cdb->length);
10759		break;
10760	}
10761	case WRITE_VERIFY_10: {
10762		struct scsi_write_verify_10 *cdb;
10763
10764		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10765
10766		*lba = scsi_4btoul(cdb->addr);
10767		*len = scsi_2btoul(cdb->length);
10768		break;
10769	}
10770	case READ_12:
10771	case WRITE_12: {
10772		struct scsi_rw_12 *cdb;
10773
10774		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10775
10776		*lba = scsi_4btoul(cdb->addr);
10777		*len = scsi_4btoul(cdb->length);
10778		break;
10779	}
10780	case WRITE_VERIFY_12: {
10781		struct scsi_write_verify_12 *cdb;
10782
10783		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10784
10785		*lba = scsi_4btoul(cdb->addr);
10786		*len = scsi_4btoul(cdb->length);
10787		break;
10788	}
10789	case READ_16:
10790	case WRITE_16:
10791	case WRITE_ATOMIC_16: {
10792		struct scsi_rw_16 *cdb;
10793
10794		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10795
10796		*lba = scsi_8btou64(cdb->addr);
10797		*len = scsi_4btoul(cdb->length);
10798		break;
10799	}
10800	case WRITE_VERIFY_16: {
10801		struct scsi_write_verify_16 *cdb;
10802
10803		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10804
10805		*lba = scsi_8btou64(cdb->addr);
10806		*len = scsi_4btoul(cdb->length);
10807		break;
10808	}
10809	case WRITE_SAME_10: {
10810		struct scsi_write_same_10 *cdb;
10811
10812		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10813
10814		*lba = scsi_4btoul(cdb->addr);
10815		*len = scsi_2btoul(cdb->length);
10816		break;
10817	}
10818	case WRITE_SAME_16: {
10819		struct scsi_write_same_16 *cdb;
10820
10821		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10822
10823		*lba = scsi_8btou64(cdb->addr);
10824		*len = scsi_4btoul(cdb->length);
10825		break;
10826	}
10827	case VERIFY_10: {
10828		struct scsi_verify_10 *cdb;
10829
10830		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10831
10832		*lba = scsi_4btoul(cdb->addr);
10833		*len = scsi_2btoul(cdb->length);
10834		break;
10835	}
10836	case VERIFY_12: {
10837		struct scsi_verify_12 *cdb;
10838
10839		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10840
10841		*lba = scsi_4btoul(cdb->addr);
10842		*len = scsi_4btoul(cdb->length);
10843		break;
10844	}
10845	case VERIFY_16: {
10846		struct scsi_verify_16 *cdb;
10847
10848		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10849
10850		*lba = scsi_8btou64(cdb->addr);
10851		*len = scsi_4btoul(cdb->length);
10852		break;
10853	}
10854	case UNMAP: {
10855		*lba = 0;
10856		*len = UINT64_MAX;
10857		break;
10858	}
10859	default:
10860		return (1);
10861		break; /* NOTREACHED */
10862	}
10863
10864	return (0);
10865}
10866
10867static ctl_action
10868ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10869{
10870	uint64_t endlba1, endlba2;
10871
10872	endlba1 = lba1 + len1 - 1;
10873	endlba2 = lba2 + len2 - 1;
10874
10875	if ((endlba1 < lba2)
10876	 || (endlba2 < lba1))
10877		return (CTL_ACTION_PASS);
10878	else
10879		return (CTL_ACTION_BLOCK);
10880}
10881
10882static int
10883ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10884{
10885	struct ctl_ptr_len_flags *ptrlen;
10886	struct scsi_unmap_desc *buf, *end, *range;
10887	uint64_t lba;
10888	uint32_t len;
10889
10890	/* If not UNMAP -- go other way. */
10891	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10892	    io->scsiio.cdb[0] != UNMAP)
10893		return (CTL_ACTION_ERROR);
10894
10895	/* If UNMAP without data -- block and wait for data. */
10896	ptrlen = (struct ctl_ptr_len_flags *)
10897	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10898	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10899	    ptrlen->ptr == NULL)
10900		return (CTL_ACTION_BLOCK);
10901
10902	/* UNMAP with data -- check for collision. */
10903	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10904	end = buf + ptrlen->len / sizeof(*buf);
10905	for (range = buf; range < end; range++) {
10906		lba = scsi_8btou64(range->lba);
10907		len = scsi_4btoul(range->length);
10908		if ((lba < lba2 + len2) && (lba + len > lba2))
10909			return (CTL_ACTION_BLOCK);
10910	}
10911	return (CTL_ACTION_PASS);
10912}
10913
10914static ctl_action
10915ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10916{
10917	uint64_t lba1, lba2;
10918	uint64_t len1, len2;
10919	int retval;
10920
10921	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10922		return (CTL_ACTION_ERROR);
10923
10924	retval = ctl_extent_check_unmap(io2, lba1, len1);
10925	if (retval != CTL_ACTION_ERROR)
10926		return (retval);
10927
10928	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10929		return (CTL_ACTION_ERROR);
10930
10931	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10932}
10933
10934static ctl_action
10935ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10936    union ctl_io *ooa_io)
10937{
10938	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10939	ctl_serialize_action *serialize_row;
10940
10941	/*
10942	 * The initiator attempted multiple untagged commands at the same
10943	 * time.  Can't do that.
10944	 */
10945	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10946	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10947	 && ((pending_io->io_hdr.nexus.targ_port ==
10948	      ooa_io->io_hdr.nexus.targ_port)
10949	  && (pending_io->io_hdr.nexus.initid.id ==
10950	      ooa_io->io_hdr.nexus.initid.id))
10951	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10952		return (CTL_ACTION_OVERLAP);
10953
10954	/*
10955	 * The initiator attempted to send multiple tagged commands with
10956	 * the same ID.  (It's fine if different initiators have the same
10957	 * tag ID.)
10958	 *
10959	 * Even if all of those conditions are true, we don't kill the I/O
10960	 * if the command ahead of us has been aborted.  We won't end up
10961	 * sending it to the FETD, and it's perfectly legal to resend a
10962	 * command with the same tag number as long as the previous
10963	 * instance of this tag number has been aborted somehow.
10964	 */
10965	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10966	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10967	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10968	 && ((pending_io->io_hdr.nexus.targ_port ==
10969	      ooa_io->io_hdr.nexus.targ_port)
10970	  && (pending_io->io_hdr.nexus.initid.id ==
10971	      ooa_io->io_hdr.nexus.initid.id))
10972	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10973		return (CTL_ACTION_OVERLAP_TAG);
10974
10975	/*
10976	 * If we get a head of queue tag, SAM-3 says that we should
10977	 * immediately execute it.
10978	 *
10979	 * What happens if this command would normally block for some other
10980	 * reason?  e.g. a request sense with a head of queue tag
10981	 * immediately after a write.  Normally that would block, but this
10982	 * will result in its getting executed immediately...
10983	 *
10984	 * We currently return "pass" instead of "skip", so we'll end up
10985	 * going through the rest of the queue to check for overlapped tags.
10986	 *
10987	 * XXX KDM check for other types of blockage first??
10988	 */
10989	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10990		return (CTL_ACTION_PASS);
10991
10992	/*
10993	 * Ordered tags have to block until all items ahead of them
10994	 * have completed.  If we get called with an ordered tag, we always
10995	 * block, if something else is ahead of us in the queue.
10996	 */
10997	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10998		return (CTL_ACTION_BLOCK);
10999
11000	/*
11001	 * Simple tags get blocked until all head of queue and ordered tags
11002	 * ahead of them have completed.  I'm lumping untagged commands in
11003	 * with simple tags here.  XXX KDM is that the right thing to do?
11004	 */
11005	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11006	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11007	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11008	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11009		return (CTL_ACTION_BLOCK);
11010
11011	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11012	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11013
11014	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11015
11016	switch (serialize_row[pending_entry->seridx]) {
11017	case CTL_SER_BLOCK:
11018		return (CTL_ACTION_BLOCK);
11019	case CTL_SER_EXTENT:
11020		return (ctl_extent_check(pending_io, ooa_io));
11021	case CTL_SER_EXTENTOPT:
11022		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11023		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11024			return (ctl_extent_check(pending_io, ooa_io));
11025		/* FALLTHROUGH */
11026	case CTL_SER_PASS:
11027		return (CTL_ACTION_PASS);
11028	case CTL_SER_BLOCKOPT:
11029		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11030		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11031			return (CTL_ACTION_BLOCK);
11032		return (CTL_ACTION_PASS);
11033	case CTL_SER_SKIP:
11034		return (CTL_ACTION_SKIP);
11035	default:
11036		panic("invalid serialization value %d",
11037		      serialize_row[pending_entry->seridx]);
11038	}
11039
11040	return (CTL_ACTION_ERROR);
11041}
11042
11043/*
11044 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11045 * Assumptions:
11046 * - pending_io is generally either incoming, or on the blocked queue
11047 * - starting I/O is the I/O we want to start the check with.
11048 */
11049static ctl_action
11050ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11051	      union ctl_io *starting_io)
11052{
11053	union ctl_io *ooa_io;
11054	ctl_action action;
11055
11056	mtx_assert(&lun->lun_lock, MA_OWNED);
11057
11058	/*
11059	 * Run back along the OOA queue, starting with the current
11060	 * blocked I/O and going through every I/O before it on the
11061	 * queue.  If starting_io is NULL, we'll just end up returning
11062	 * CTL_ACTION_PASS.
11063	 */
11064	for (ooa_io = starting_io; ooa_io != NULL;
11065	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11066	     ooa_links)){
11067
11068		/*
11069		 * This routine just checks to see whether
11070		 * cur_blocked is blocked by ooa_io, which is ahead
11071		 * of it in the queue.  It doesn't queue/dequeue
11072		 * cur_blocked.
11073		 */
11074		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11075		switch (action) {
11076		case CTL_ACTION_BLOCK:
11077		case CTL_ACTION_OVERLAP:
11078		case CTL_ACTION_OVERLAP_TAG:
11079		case CTL_ACTION_SKIP:
11080		case CTL_ACTION_ERROR:
11081			return (action);
11082			break; /* NOTREACHED */
11083		case CTL_ACTION_PASS:
11084			break;
11085		default:
11086			panic("invalid action %d", action);
11087			break;  /* NOTREACHED */
11088		}
11089	}
11090
11091	return (CTL_ACTION_PASS);
11092}
11093
11094/*
11095 * Assumptions:
11096 * - An I/O has just completed, and has been removed from the per-LUN OOA
11097 *   queue, so some items on the blocked queue may now be unblocked.
11098 */
11099static int
11100ctl_check_blocked(struct ctl_lun *lun)
11101{
11102	union ctl_io *cur_blocked, *next_blocked;
11103
11104	mtx_assert(&lun->lun_lock, MA_OWNED);
11105
11106	/*
11107	 * Run forward from the head of the blocked queue, checking each
11108	 * entry against the I/Os prior to it on the OOA queue to see if
11109	 * there is still any blockage.
11110	 *
11111	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11112	 * with our removing a variable on it while it is traversing the
11113	 * list.
11114	 */
11115	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11116	     cur_blocked != NULL; cur_blocked = next_blocked) {
11117		union ctl_io *prev_ooa;
11118		ctl_action action;
11119
11120		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11121							  blocked_links);
11122
11123		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11124						      ctl_ooaq, ooa_links);
11125
11126		/*
11127		 * If cur_blocked happens to be the first item in the OOA
11128		 * queue now, prev_ooa will be NULL, and the action
11129		 * returned will just be CTL_ACTION_PASS.
11130		 */
11131		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11132
11133		switch (action) {
11134		case CTL_ACTION_BLOCK:
11135			/* Nothing to do here, still blocked */
11136			break;
11137		case CTL_ACTION_OVERLAP:
11138		case CTL_ACTION_OVERLAP_TAG:
11139			/*
11140			 * This shouldn't happen!  In theory we've already
11141			 * checked this command for overlap...
11142			 */
11143			break;
11144		case CTL_ACTION_PASS:
11145		case CTL_ACTION_SKIP: {
11146			struct ctl_softc *softc;
11147			const struct ctl_cmd_entry *entry;
11148			uint32_t initidx;
11149			int isc_retval;
11150
11151			/*
11152			 * The skip case shouldn't happen, this transaction
11153			 * should have never made it onto the blocked queue.
11154			 */
11155			/*
11156			 * This I/O is no longer blocked, we can remove it
11157			 * from the blocked queue.  Since this is a TAILQ
11158			 * (doubly linked list), we can do O(1) removals
11159			 * from any place on the list.
11160			 */
11161			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11162				     blocked_links);
11163			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11164
11165			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11166				/*
11167				 * Need to send IO back to original side to
11168				 * run
11169				 */
11170				union ctl_ha_msg msg_info;
11171
11172				msg_info.hdr.original_sc =
11173					cur_blocked->io_hdr.original_sc;
11174				msg_info.hdr.serializing_sc = cur_blocked;
11175				msg_info.hdr.msg_type = CTL_MSG_R2R;
11176				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11177				     &msg_info, sizeof(msg_info), 0)) >
11178				     CTL_HA_STATUS_SUCCESS) {
11179					printf("CTL:Check Blocked error from "
11180					       "ctl_ha_msg_send %d\n",
11181					       isc_retval);
11182				}
11183				break;
11184			}
11185			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11186			softc = control_softc;
11187
11188			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11189
11190			/*
11191			 * Check this I/O for LUN state changes that may
11192			 * have happened while this command was blocked.
11193			 * The LUN state may have been changed by a command
11194			 * ahead of us in the queue, so we need to re-check
11195			 * for any states that can be caused by SCSI
11196			 * commands.
11197			 */
11198			if (ctl_scsiio_lun_check(softc, lun, entry,
11199						 &cur_blocked->scsiio) == 0) {
11200				cur_blocked->io_hdr.flags |=
11201				                      CTL_FLAG_IS_WAS_ON_RTR;
11202				ctl_enqueue_rtr(cur_blocked);
11203			} else
11204				ctl_done(cur_blocked);
11205			break;
11206		}
11207		default:
11208			/*
11209			 * This probably shouldn't happen -- we shouldn't
11210			 * get CTL_ACTION_ERROR, or anything else.
11211			 */
11212			break;
11213		}
11214	}
11215
11216	return (CTL_RETVAL_COMPLETE);
11217}
11218
11219/*
11220 * This routine (with one exception) checks LUN flags that can be set by
11221 * commands ahead of us in the OOA queue.  These flags have to be checked
11222 * when a command initially comes in, and when we pull a command off the
11223 * blocked queue and are preparing to execute it.  The reason we have to
11224 * check these flags for commands on the blocked queue is that the LUN
11225 * state may have been changed by a command ahead of us while we're on the
11226 * blocked queue.
11227 *
11228 * Ordering is somewhat important with these checks, so please pay
11229 * careful attention to the placement of any new checks.
11230 */
11231static int
11232ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11233    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11234{
11235	int retval;
11236	uint32_t residx;
11237
11238	retval = 0;
11239
11240	mtx_assert(&lun->lun_lock, MA_OWNED);
11241
11242	/*
11243	 * If this shelf is a secondary shelf controller, we have to reject
11244	 * any media access commands.
11245	 */
11246#if 0
11247	/* No longer needed for HA */
11248	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11249	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11250		ctl_set_lun_standby(ctsio);
11251		retval = 1;
11252		goto bailout;
11253	}
11254#endif
11255
11256	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11257		if (lun->flags & CTL_LUN_READONLY) {
11258			ctl_set_sense(ctsio, /*current_error*/ 1,
11259			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11260			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11261			retval = 1;
11262			goto bailout;
11263		}
11264		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11265		    .eca_and_aen & SCP_SWP) != 0) {
11266			ctl_set_sense(ctsio, /*current_error*/ 1,
11267			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11268			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11269			retval = 1;
11270			goto bailout;
11271		}
11272	}
11273
11274	/*
11275	 * Check for a reservation conflict.  If this command isn't allowed
11276	 * even on reserved LUNs, and if this initiator isn't the one who
11277	 * reserved us, reject the command with a reservation conflict.
11278	 */
11279	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11280	if ((lun->flags & CTL_LUN_RESERVED)
11281	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11282		if (lun->res_idx != residx) {
11283			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11284			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11285			retval = 1;
11286			goto bailout;
11287		}
11288	}
11289
11290	if ((lun->flags & CTL_LUN_PR_RESERVED)
11291	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11292		/*
11293		 * if we aren't registered or it's a res holder type
11294		 * reservation and this isn't the res holder then set a
11295		 * conflict.
11296		 * NOTE: Commands which might be allowed on write exclusive
11297		 * type reservations are checked in the particular command
11298		 * for a conflict. Read and SSU are the only ones.
11299		 */
11300		if (lun->pr_keys[residx] == 0
11301		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11302			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11303			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11304			retval = 1;
11305			goto bailout;
11306		}
11307
11308	}
11309
11310	if ((lun->flags & CTL_LUN_OFFLINE)
11311	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11312		ctl_set_lun_not_ready(ctsio);
11313		retval = 1;
11314		goto bailout;
11315	}
11316
11317	/*
11318	 * If the LUN is stopped, see if this particular command is allowed
11319	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11320	 */
11321	if ((lun->flags & CTL_LUN_STOPPED)
11322	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11323		/* "Logical unit not ready, initializing cmd. required" */
11324		ctl_set_lun_stopped(ctsio);
11325		retval = 1;
11326		goto bailout;
11327	}
11328
11329	if ((lun->flags & CTL_LUN_INOPERABLE)
11330	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11331		/* "Medium format corrupted" */
11332		ctl_set_medium_format_corrupted(ctsio);
11333		retval = 1;
11334		goto bailout;
11335	}
11336
11337bailout:
11338	return (retval);
11339
11340}
11341
11342static void
11343ctl_failover_io(union ctl_io *io, int have_lock)
11344{
11345	ctl_set_busy(&io->scsiio);
11346	ctl_done(io);
11347}
11348
11349static void
11350ctl_failover(void)
11351{
11352	struct ctl_lun *lun;
11353	struct ctl_softc *ctl_softc;
11354	union ctl_io *next_io, *pending_io;
11355	union ctl_io *io;
11356	int lun_idx;
11357	int i;
11358
11359	ctl_softc = control_softc;
11360
11361	mtx_lock(&ctl_softc->ctl_lock);
11362	/*
11363	 * Remove any cmds from the other SC from the rtr queue.  These
11364	 * will obviously only be for LUNs for which we're the primary.
11365	 * We can't send status or get/send data for these commands.
11366	 * Since they haven't been executed yet, we can just remove them.
11367	 * We'll either abort them or delete them below, depending on
11368	 * which HA mode we're in.
11369	 */
11370#ifdef notyet
11371	mtx_lock(&ctl_softc->queue_lock);
11372	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11373	     io != NULL; io = next_io) {
11374		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11375		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11376			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11377				      ctl_io_hdr, links);
11378	}
11379	mtx_unlock(&ctl_softc->queue_lock);
11380#endif
11381
11382	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11383		lun = ctl_softc->ctl_luns[lun_idx];
11384		if (lun==NULL)
11385			continue;
11386
11387		/*
11388		 * Processor LUNs are primary on both sides.
11389		 * XXX will this always be true?
11390		 */
11391		if (lun->be_lun->lun_type == T_PROCESSOR)
11392			continue;
11393
11394		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11395		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11396			printf("FAILOVER: primary lun %d\n", lun_idx);
11397		        /*
11398			 * Remove all commands from the other SC. First from the
11399			 * blocked queue then from the ooa queue. Once we have
11400			 * removed them. Call ctl_check_blocked to see if there
11401			 * is anything that can run.
11402			 */
11403			for (io = (union ctl_io *)TAILQ_FIRST(
11404			     &lun->blocked_queue); io != NULL; io = next_io) {
11405
11406		        	next_io = (union ctl_io *)TAILQ_NEXT(
11407				    &io->io_hdr, blocked_links);
11408
11409				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11410					TAILQ_REMOVE(&lun->blocked_queue,
11411						     &io->io_hdr,blocked_links);
11412					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11413					TAILQ_REMOVE(&lun->ooa_queue,
11414						     &io->io_hdr, ooa_links);
11415
11416					ctl_free_io(io);
11417				}
11418			}
11419
11420			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11421	     		     io != NULL; io = next_io) {
11422
11423		        	next_io = (union ctl_io *)TAILQ_NEXT(
11424				    &io->io_hdr, ooa_links);
11425
11426				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11427
11428					TAILQ_REMOVE(&lun->ooa_queue,
11429						&io->io_hdr,
11430					     	ooa_links);
11431
11432					ctl_free_io(io);
11433				}
11434			}
11435			ctl_check_blocked(lun);
11436		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11437			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11438
11439			printf("FAILOVER: primary lun %d\n", lun_idx);
11440			/*
11441			 * Abort all commands from the other SC.  We can't
11442			 * send status back for them now.  These should get
11443			 * cleaned up when they are completed or come out
11444			 * for a datamove operation.
11445			 */
11446			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11447	     		     io != NULL; io = next_io) {
11448		        	next_io = (union ctl_io *)TAILQ_NEXT(
11449					&io->io_hdr, ooa_links);
11450
11451				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11452					io->io_hdr.flags |= CTL_FLAG_ABORT;
11453			}
11454		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11455			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11456
11457			printf("FAILOVER: secondary lun %d\n", lun_idx);
11458
11459			lun->flags |= CTL_LUN_PRIMARY_SC;
11460
11461			/*
11462			 * We send all I/O that was sent to this controller
11463			 * and redirected to the other side back with
11464			 * busy status, and have the initiator retry it.
11465			 * Figuring out how much data has been transferred,
11466			 * etc. and picking up where we left off would be
11467			 * very tricky.
11468			 *
11469			 * XXX KDM need to remove I/O from the blocked
11470			 * queue as well!
11471			 */
11472			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11473			     &lun->ooa_queue); pending_io != NULL;
11474			     pending_io = next_io) {
11475
11476				next_io =  (union ctl_io *)TAILQ_NEXT(
11477					&pending_io->io_hdr, ooa_links);
11478
11479				pending_io->io_hdr.flags &=
11480					~CTL_FLAG_SENT_2OTHER_SC;
11481
11482				if (pending_io->io_hdr.flags &
11483				    CTL_FLAG_IO_ACTIVE) {
11484					pending_io->io_hdr.flags |=
11485						CTL_FLAG_FAILOVER;
11486				} else {
11487					ctl_set_busy(&pending_io->scsiio);
11488					ctl_done(pending_io);
11489				}
11490			}
11491
11492			/*
11493			 * Build Unit Attention
11494			 */
11495			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11496				lun->pending_ua[i] |=
11497				                     CTL_UA_ASYM_ACC_CHANGE;
11498			}
11499		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11500			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11501			printf("FAILOVER: secondary lun %d\n", lun_idx);
11502			/*
11503			 * if the first io on the OOA is not on the RtR queue
11504			 * add it.
11505			 */
11506			lun->flags |= CTL_LUN_PRIMARY_SC;
11507
11508			pending_io = (union ctl_io *)TAILQ_FIRST(
11509			    &lun->ooa_queue);
11510			if (pending_io==NULL) {
11511				printf("Nothing on OOA queue\n");
11512				continue;
11513			}
11514
11515			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11516			if ((pending_io->io_hdr.flags &
11517			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11518				pending_io->io_hdr.flags |=
11519				    CTL_FLAG_IS_WAS_ON_RTR;
11520				ctl_enqueue_rtr(pending_io);
11521			}
11522#if 0
11523			else
11524			{
11525				printf("Tag 0x%04x is running\n",
11526				      pending_io->scsiio.tag_num);
11527			}
11528#endif
11529
11530			next_io = (union ctl_io *)TAILQ_NEXT(
11531			    &pending_io->io_hdr, ooa_links);
11532			for (pending_io=next_io; pending_io != NULL;
11533			     pending_io = next_io) {
11534				pending_io->io_hdr.flags &=
11535				    ~CTL_FLAG_SENT_2OTHER_SC;
11536				next_io = (union ctl_io *)TAILQ_NEXT(
11537					&pending_io->io_hdr, ooa_links);
11538				if (pending_io->io_hdr.flags &
11539				    CTL_FLAG_IS_WAS_ON_RTR) {
11540#if 0
11541				        printf("Tag 0x%04x is running\n",
11542				      		pending_io->scsiio.tag_num);
11543#endif
11544					continue;
11545				}
11546
11547				switch (ctl_check_ooa(lun, pending_io,
11548			            (union ctl_io *)TAILQ_PREV(
11549				    &pending_io->io_hdr, ctl_ooaq,
11550				    ooa_links))) {
11551
11552				case CTL_ACTION_BLOCK:
11553					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11554							  &pending_io->io_hdr,
11555							  blocked_links);
11556					pending_io->io_hdr.flags |=
11557					    CTL_FLAG_BLOCKED;
11558					break;
11559				case CTL_ACTION_PASS:
11560				case CTL_ACTION_SKIP:
11561					pending_io->io_hdr.flags |=
11562					    CTL_FLAG_IS_WAS_ON_RTR;
11563					ctl_enqueue_rtr(pending_io);
11564					break;
11565				case CTL_ACTION_OVERLAP:
11566					ctl_set_overlapped_cmd(
11567					    (struct ctl_scsiio *)pending_io);
11568					ctl_done(pending_io);
11569					break;
11570				case CTL_ACTION_OVERLAP_TAG:
11571					ctl_set_overlapped_tag(
11572					    (struct ctl_scsiio *)pending_io,
11573					    pending_io->scsiio.tag_num & 0xff);
11574					ctl_done(pending_io);
11575					break;
11576				case CTL_ACTION_ERROR:
11577				default:
11578					ctl_set_internal_failure(
11579						(struct ctl_scsiio *)pending_io,
11580						0,  // sks_valid
11581						0); //retry count
11582					ctl_done(pending_io);
11583					break;
11584				}
11585			}
11586
11587			/*
11588			 * Build Unit Attention
11589			 */
11590			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11591				lun->pending_ua[i] |=
11592				                     CTL_UA_ASYM_ACC_CHANGE;
11593			}
11594		} else {
11595			panic("Unhandled HA mode failover, LUN flags = %#x, "
11596			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11597		}
11598	}
11599	ctl_pause_rtr = 0;
11600	mtx_unlock(&ctl_softc->ctl_lock);
11601}
11602
11603static int
11604ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11605{
11606	struct ctl_lun *lun;
11607	const struct ctl_cmd_entry *entry;
11608	uint32_t initidx, targ_lun;
11609	int retval;
11610
11611	retval = 0;
11612
11613	lun = NULL;
11614
11615	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11616	if ((targ_lun < CTL_MAX_LUNS)
11617	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11618		lun = ctl_softc->ctl_luns[targ_lun];
11619		/*
11620		 * If the LUN is invalid, pretend that it doesn't exist.
11621		 * It will go away as soon as all pending I/O has been
11622		 * completed.
11623		 */
11624		if (lun->flags & CTL_LUN_DISABLED) {
11625			lun = NULL;
11626		} else {
11627			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11628			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11629				lun->be_lun;
11630			if (lun->be_lun->lun_type == T_PROCESSOR) {
11631				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11632			}
11633
11634			/*
11635			 * Every I/O goes into the OOA queue for a
11636			 * particular LUN, and stays there until completion.
11637			 */
11638			mtx_lock(&lun->lun_lock);
11639			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11640			    ooa_links);
11641		}
11642	} else {
11643		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11644		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11645	}
11646
11647	/* Get command entry and return error if it is unsuppotyed. */
11648	entry = ctl_validate_command(ctsio);
11649	if (entry == NULL) {
11650		if (lun)
11651			mtx_unlock(&lun->lun_lock);
11652		return (retval);
11653	}
11654
11655	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11656	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11657
11658	/*
11659	 * Check to see whether we can send this command to LUNs that don't
11660	 * exist.  This should pretty much only be the case for inquiry
11661	 * and request sense.  Further checks, below, really require having
11662	 * a LUN, so we can't really check the command anymore.  Just put
11663	 * it on the rtr queue.
11664	 */
11665	if (lun == NULL) {
11666		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11667			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11668			ctl_enqueue_rtr((union ctl_io *)ctsio);
11669			return (retval);
11670		}
11671
11672		ctl_set_unsupported_lun(ctsio);
11673		ctl_done((union ctl_io *)ctsio);
11674		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11675		return (retval);
11676	} else {
11677		/*
11678		 * Make sure we support this particular command on this LUN.
11679		 * e.g., we don't support writes to the control LUN.
11680		 */
11681		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11682			mtx_unlock(&lun->lun_lock);
11683			ctl_set_invalid_opcode(ctsio);
11684			ctl_done((union ctl_io *)ctsio);
11685			return (retval);
11686		}
11687	}
11688
11689	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11690
11691#ifdef CTL_WITH_CA
11692	/*
11693	 * If we've got a request sense, it'll clear the contingent
11694	 * allegiance condition.  Otherwise, if we have a CA condition for
11695	 * this initiator, clear it, because it sent down a command other
11696	 * than request sense.
11697	 */
11698	if ((ctsio->cdb[0] != REQUEST_SENSE)
11699	 && (ctl_is_set(lun->have_ca, initidx)))
11700		ctl_clear_mask(lun->have_ca, initidx);
11701#endif
11702
11703	/*
11704	 * If the command has this flag set, it handles its own unit
11705	 * attention reporting, we shouldn't do anything.  Otherwise we
11706	 * check for any pending unit attentions, and send them back to the
11707	 * initiator.  We only do this when a command initially comes in,
11708	 * not when we pull it off the blocked queue.
11709	 *
11710	 * According to SAM-3, section 5.3.2, the order that things get
11711	 * presented back to the host is basically unit attentions caused
11712	 * by some sort of reset event, busy status, reservation conflicts
11713	 * or task set full, and finally any other status.
11714	 *
11715	 * One issue here is that some of the unit attentions we report
11716	 * don't fall into the "reset" category (e.g. "reported luns data
11717	 * has changed").  So reporting it here, before the reservation
11718	 * check, may be technically wrong.  I guess the only thing to do
11719	 * would be to check for and report the reset events here, and then
11720	 * check for the other unit attention types after we check for a
11721	 * reservation conflict.
11722	 *
11723	 * XXX KDM need to fix this
11724	 */
11725	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11726		ctl_ua_type ua_type;
11727
11728		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11729			scsi_sense_data_type sense_format;
11730
11731			if (lun != NULL)
11732				sense_format = (lun->flags &
11733				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11734				    SSD_TYPE_FIXED;
11735			else
11736				sense_format = SSD_TYPE_FIXED;
11737
11738			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11739			    &ctsio->sense_data, sense_format);
11740			if (ua_type != CTL_UA_NONE) {
11741				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11742				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11743						       CTL_AUTOSENSE;
11744				ctsio->sense_len = SSD_FULL_SIZE;
11745				mtx_unlock(&lun->lun_lock);
11746				ctl_done((union ctl_io *)ctsio);
11747				return (retval);
11748			}
11749		}
11750	}
11751
11752
11753	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11754		mtx_unlock(&lun->lun_lock);
11755		ctl_done((union ctl_io *)ctsio);
11756		return (retval);
11757	}
11758
11759	/*
11760	 * XXX CHD this is where we want to send IO to other side if
11761	 * this LUN is secondary on this SC. We will need to make a copy
11762	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11763	 * the copy we send as FROM_OTHER.
11764	 * We also need to stuff the address of the original IO so we can
11765	 * find it easily. Something similar will need be done on the other
11766	 * side so when we are done we can find the copy.
11767	 */
11768	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11769		union ctl_ha_msg msg_info;
11770		int isc_retval;
11771
11772		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11773
11774		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11775		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11776#if 0
11777		printf("1. ctsio %p\n", ctsio);
11778#endif
11779		msg_info.hdr.serializing_sc = NULL;
11780		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11781		msg_info.scsi.tag_num = ctsio->tag_num;
11782		msg_info.scsi.tag_type = ctsio->tag_type;
11783		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11784
11785		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11786
11787		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11788		    (void *)&msg_info, sizeof(msg_info), 0)) >
11789		    CTL_HA_STATUS_SUCCESS) {
11790			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11791			       isc_retval);
11792			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11793		} else {
11794#if 0
11795			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11796#endif
11797		}
11798
11799		/*
11800		 * XXX KDM this I/O is off the incoming queue, but hasn't
11801		 * been inserted on any other queue.  We may need to come
11802		 * up with a holding queue while we wait for serialization
11803		 * so that we have an idea of what we're waiting for from
11804		 * the other side.
11805		 */
11806		mtx_unlock(&lun->lun_lock);
11807		return (retval);
11808	}
11809
11810	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11811			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11812			      ctl_ooaq, ooa_links))) {
11813	case CTL_ACTION_BLOCK:
11814		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11815		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11816				  blocked_links);
11817		mtx_unlock(&lun->lun_lock);
11818		return (retval);
11819	case CTL_ACTION_PASS:
11820	case CTL_ACTION_SKIP:
11821		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11822		mtx_unlock(&lun->lun_lock);
11823		ctl_enqueue_rtr((union ctl_io *)ctsio);
11824		break;
11825	case CTL_ACTION_OVERLAP:
11826		mtx_unlock(&lun->lun_lock);
11827		ctl_set_overlapped_cmd(ctsio);
11828		ctl_done((union ctl_io *)ctsio);
11829		break;
11830	case CTL_ACTION_OVERLAP_TAG:
11831		mtx_unlock(&lun->lun_lock);
11832		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11833		ctl_done((union ctl_io *)ctsio);
11834		break;
11835	case CTL_ACTION_ERROR:
11836	default:
11837		mtx_unlock(&lun->lun_lock);
11838		ctl_set_internal_failure(ctsio,
11839					 /*sks_valid*/ 0,
11840					 /*retry_count*/ 0);
11841		ctl_done((union ctl_io *)ctsio);
11842		break;
11843	}
11844	return (retval);
11845}
11846
11847const struct ctl_cmd_entry *
11848ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11849{
11850	const struct ctl_cmd_entry *entry;
11851	int service_action;
11852
11853	entry = &ctl_cmd_table[ctsio->cdb[0]];
11854	if (sa)
11855		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11856	if (entry->flags & CTL_CMD_FLAG_SA5) {
11857		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11858		entry = &((const struct ctl_cmd_entry *)
11859		    entry->execute)[service_action];
11860	}
11861	return (entry);
11862}
11863
11864const struct ctl_cmd_entry *
11865ctl_validate_command(struct ctl_scsiio *ctsio)
11866{
11867	const struct ctl_cmd_entry *entry;
11868	int i, sa;
11869	uint8_t diff;
11870
11871	entry = ctl_get_cmd_entry(ctsio, &sa);
11872	if (entry->execute == NULL) {
11873		if (sa)
11874			ctl_set_invalid_field(ctsio,
11875					      /*sks_valid*/ 1,
11876					      /*command*/ 1,
11877					      /*field*/ 1,
11878					      /*bit_valid*/ 1,
11879					      /*bit*/ 4);
11880		else
11881			ctl_set_invalid_opcode(ctsio);
11882		ctl_done((union ctl_io *)ctsio);
11883		return (NULL);
11884	}
11885	KASSERT(entry->length > 0,
11886	    ("Not defined length for command 0x%02x/0x%02x",
11887	     ctsio->cdb[0], ctsio->cdb[1]));
11888	for (i = 1; i < entry->length; i++) {
11889		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11890		if (diff == 0)
11891			continue;
11892		ctl_set_invalid_field(ctsio,
11893				      /*sks_valid*/ 1,
11894				      /*command*/ 1,
11895				      /*field*/ i,
11896				      /*bit_valid*/ 1,
11897				      /*bit*/ fls(diff) - 1);
11898		ctl_done((union ctl_io *)ctsio);
11899		return (NULL);
11900	}
11901	return (entry);
11902}
11903
11904static int
11905ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11906{
11907
11908	switch (lun_type) {
11909	case T_PROCESSOR:
11910		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11911		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11912			return (0);
11913		break;
11914	case T_DIRECT:
11915		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11916		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11917			return (0);
11918		break;
11919	default:
11920		return (0);
11921	}
11922	return (1);
11923}
11924
11925static int
11926ctl_scsiio(struct ctl_scsiio *ctsio)
11927{
11928	int retval;
11929	const struct ctl_cmd_entry *entry;
11930
11931	retval = CTL_RETVAL_COMPLETE;
11932
11933	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11934
11935	entry = ctl_get_cmd_entry(ctsio, NULL);
11936
11937	/*
11938	 * If this I/O has been aborted, just send it straight to
11939	 * ctl_done() without executing it.
11940	 */
11941	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11942		ctl_done((union ctl_io *)ctsio);
11943		goto bailout;
11944	}
11945
11946	/*
11947	 * All the checks should have been handled by ctl_scsiio_precheck().
11948	 * We should be clear now to just execute the I/O.
11949	 */
11950	retval = entry->execute(ctsio);
11951
11952bailout:
11953	return (retval);
11954}
11955
11956/*
11957 * Since we only implement one target right now, a bus reset simply resets
11958 * our single target.
11959 */
11960static int
11961ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11962{
11963	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11964}
11965
11966static int
11967ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11968		 ctl_ua_type ua_type)
11969{
11970	struct ctl_lun *lun;
11971	int retval;
11972
11973	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11974		union ctl_ha_msg msg_info;
11975
11976		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11977		msg_info.hdr.nexus = io->io_hdr.nexus;
11978		if (ua_type==CTL_UA_TARG_RESET)
11979			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11980		else
11981			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11982		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11983		msg_info.hdr.original_sc = NULL;
11984		msg_info.hdr.serializing_sc = NULL;
11985		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11986		    (void *)&msg_info, sizeof(msg_info), 0)) {
11987		}
11988	}
11989	retval = 0;
11990
11991	mtx_lock(&ctl_softc->ctl_lock);
11992	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11993		retval += ctl_lun_reset(lun, io, ua_type);
11994	mtx_unlock(&ctl_softc->ctl_lock);
11995
11996	return (retval);
11997}
11998
11999/*
12000 * The LUN should always be set.  The I/O is optional, and is used to
12001 * distinguish between I/Os sent by this initiator, and by other
12002 * initiators.  We set unit attention for initiators other than this one.
12003 * SAM-3 is vague on this point.  It does say that a unit attention should
12004 * be established for other initiators when a LUN is reset (see section
12005 * 5.7.3), but it doesn't specifically say that the unit attention should
12006 * be established for this particular initiator when a LUN is reset.  Here
12007 * is the relevant text, from SAM-3 rev 8:
12008 *
12009 * 5.7.2 When a SCSI initiator port aborts its own tasks
12010 *
12011 * When a SCSI initiator port causes its own task(s) to be aborted, no
12012 * notification that the task(s) have been aborted shall be returned to
12013 * the SCSI initiator port other than the completion response for the
12014 * command or task management function action that caused the task(s) to
12015 * be aborted and notification(s) associated with related effects of the
12016 * action (e.g., a reset unit attention condition).
12017 *
12018 * XXX KDM for now, we're setting unit attention for all initiators.
12019 */
12020static int
12021ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12022{
12023	union ctl_io *xio;
12024#if 0
12025	uint32_t initindex;
12026#endif
12027	int i;
12028
12029	mtx_lock(&lun->lun_lock);
12030	/*
12031	 * Run through the OOA queue and abort each I/O.
12032	 */
12033#if 0
12034	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12035#endif
12036	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12037	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12038		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12039	}
12040
12041	/*
12042	 * This version sets unit attention for every
12043	 */
12044#if 0
12045	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12046	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12047		if (initindex == i)
12048			continue;
12049		lun->pending_ua[i] |= ua_type;
12050	}
12051#endif
12052
12053	/*
12054	 * A reset (any kind, really) clears reservations established with
12055	 * RESERVE/RELEASE.  It does not clear reservations established
12056	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12057	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12058	 * reservations made with the RESERVE/RELEASE commands, because
12059	 * those commands are obsolete in SPC-3.
12060	 */
12061	lun->flags &= ~CTL_LUN_RESERVED;
12062
12063	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12064#ifdef CTL_WITH_CA
12065		ctl_clear_mask(lun->have_ca, i);
12066#endif
12067		lun->pending_ua[i] |= ua_type;
12068	}
12069	mtx_unlock(&lun->lun_lock);
12070
12071	return (0);
12072}
12073
12074static void
12075ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12076    int other_sc)
12077{
12078	union ctl_io *xio;
12079
12080	mtx_assert(&lun->lun_lock, MA_OWNED);
12081
12082	/*
12083	 * Run through the OOA queue and attempt to find the given I/O.
12084	 * The target port, initiator ID, tag type and tag number have to
12085	 * match the values that we got from the initiator.  If we have an
12086	 * untagged command to abort, simply abort the first untagged command
12087	 * we come to.  We only allow one untagged command at a time of course.
12088	 */
12089	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12090	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12091
12092		if ((targ_port == UINT32_MAX ||
12093		     targ_port == xio->io_hdr.nexus.targ_port) &&
12094		    (init_id == UINT32_MAX ||
12095		     init_id == xio->io_hdr.nexus.initid.id)) {
12096			if (targ_port != xio->io_hdr.nexus.targ_port ||
12097			    init_id != xio->io_hdr.nexus.initid.id)
12098				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12099			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12100			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12101				union ctl_ha_msg msg_info;
12102
12103				msg_info.hdr.nexus = xio->io_hdr.nexus;
12104				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12105				msg_info.task.tag_num = xio->scsiio.tag_num;
12106				msg_info.task.tag_type = xio->scsiio.tag_type;
12107				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12108				msg_info.hdr.original_sc = NULL;
12109				msg_info.hdr.serializing_sc = NULL;
12110				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12111				    (void *)&msg_info, sizeof(msg_info), 0);
12112			}
12113		}
12114	}
12115}
12116
12117static int
12118ctl_abort_task_set(union ctl_io *io)
12119{
12120	struct ctl_softc *softc = control_softc;
12121	struct ctl_lun *lun;
12122	uint32_t targ_lun;
12123
12124	/*
12125	 * Look up the LUN.
12126	 */
12127	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12128	mtx_lock(&softc->ctl_lock);
12129	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12130		lun = softc->ctl_luns[targ_lun];
12131	else {
12132		mtx_unlock(&softc->ctl_lock);
12133		return (1);
12134	}
12135
12136	mtx_lock(&lun->lun_lock);
12137	mtx_unlock(&softc->ctl_lock);
12138	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12139		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12140		    io->io_hdr.nexus.initid.id,
12141		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12142	} else { /* CTL_TASK_CLEAR_TASK_SET */
12143		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12144		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12145	}
12146	mtx_unlock(&lun->lun_lock);
12147	return (0);
12148}
12149
12150static int
12151ctl_i_t_nexus_reset(union ctl_io *io)
12152{
12153	struct ctl_softc *softc = control_softc;
12154	struct ctl_lun *lun;
12155	uint32_t initindex, residx;
12156
12157	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12158	residx = ctl_get_resindex(&io->io_hdr.nexus);
12159	mtx_lock(&softc->ctl_lock);
12160	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12161		mtx_lock(&lun->lun_lock);
12162		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12163		    io->io_hdr.nexus.initid.id,
12164		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12165#ifdef CTL_WITH_CA
12166		ctl_clear_mask(lun->have_ca, initindex);
12167#endif
12168		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12169			lun->flags &= ~CTL_LUN_RESERVED;
12170		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12171		mtx_unlock(&lun->lun_lock);
12172	}
12173	mtx_unlock(&softc->ctl_lock);
12174	return (0);
12175}
12176
12177static int
12178ctl_abort_task(union ctl_io *io)
12179{
12180	union ctl_io *xio;
12181	struct ctl_lun *lun;
12182	struct ctl_softc *ctl_softc;
12183#if 0
12184	struct sbuf sb;
12185	char printbuf[128];
12186#endif
12187	int found;
12188	uint32_t targ_lun;
12189
12190	ctl_softc = control_softc;
12191	found = 0;
12192
12193	/*
12194	 * Look up the LUN.
12195	 */
12196	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12197	mtx_lock(&ctl_softc->ctl_lock);
12198	if ((targ_lun < CTL_MAX_LUNS)
12199	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12200		lun = ctl_softc->ctl_luns[targ_lun];
12201	else {
12202		mtx_unlock(&ctl_softc->ctl_lock);
12203		return (1);
12204	}
12205
12206#if 0
12207	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12208	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12209#endif
12210
12211	mtx_lock(&lun->lun_lock);
12212	mtx_unlock(&ctl_softc->ctl_lock);
12213	/*
12214	 * Run through the OOA queue and attempt to find the given I/O.
12215	 * The target port, initiator ID, tag type and tag number have to
12216	 * match the values that we got from the initiator.  If we have an
12217	 * untagged command to abort, simply abort the first untagged command
12218	 * we come to.  We only allow one untagged command at a time of course.
12219	 */
12220#if 0
12221	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12222#endif
12223	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12224	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12225#if 0
12226		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12227
12228		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12229			    lun->lun, xio->scsiio.tag_num,
12230			    xio->scsiio.tag_type,
12231			    (xio->io_hdr.blocked_links.tqe_prev
12232			    == NULL) ? "" : " BLOCKED",
12233			    (xio->io_hdr.flags &
12234			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12235			    (xio->io_hdr.flags &
12236			    CTL_FLAG_ABORT) ? " ABORT" : "",
12237			    (xio->io_hdr.flags &
12238			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12239		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12240		sbuf_finish(&sb);
12241		printf("%s\n", sbuf_data(&sb));
12242#endif
12243
12244		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12245		 && (xio->io_hdr.nexus.initid.id ==
12246		     io->io_hdr.nexus.initid.id)) {
12247			/*
12248			 * If the abort says that the task is untagged, the
12249			 * task in the queue must be untagged.  Otherwise,
12250			 * we just check to see whether the tag numbers
12251			 * match.  This is because the QLogic firmware
12252			 * doesn't pass back the tag type in an abort
12253			 * request.
12254			 */
12255#if 0
12256			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12257			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12258			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12259#endif
12260			/*
12261			 * XXX KDM we've got problems with FC, because it
12262			 * doesn't send down a tag type with aborts.  So we
12263			 * can only really go by the tag number...
12264			 * This may cause problems with parallel SCSI.
12265			 * Need to figure that out!!
12266			 */
12267			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12268				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12269				found = 1;
12270				if ((io->io_hdr.flags &
12271				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12272				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12273					union ctl_ha_msg msg_info;
12274
12275					io->io_hdr.flags |=
12276					                CTL_FLAG_SENT_2OTHER_SC;
12277					msg_info.hdr.nexus = io->io_hdr.nexus;
12278					msg_info.task.task_action =
12279						CTL_TASK_ABORT_TASK;
12280					msg_info.task.tag_num =
12281						io->taskio.tag_num;
12282					msg_info.task.tag_type =
12283						io->taskio.tag_type;
12284					msg_info.hdr.msg_type =
12285						CTL_MSG_MANAGE_TASKS;
12286					msg_info.hdr.original_sc = NULL;
12287					msg_info.hdr.serializing_sc = NULL;
12288#if 0
12289					printf("Sent Abort to other side\n");
12290#endif
12291					if (CTL_HA_STATUS_SUCCESS !=
12292					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12293		    				(void *)&msg_info,
12294						sizeof(msg_info), 0)) {
12295					}
12296				}
12297#if 0
12298				printf("ctl_abort_task: found I/O to abort\n");
12299#endif
12300				break;
12301			}
12302		}
12303	}
12304	mtx_unlock(&lun->lun_lock);
12305
12306	if (found == 0) {
12307		/*
12308		 * This isn't really an error.  It's entirely possible for
12309		 * the abort and command completion to cross on the wire.
12310		 * This is more of an informative/diagnostic error.
12311		 */
12312#if 0
12313		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12314		       "%d:%d:%d:%d tag %d type %d\n",
12315		       io->io_hdr.nexus.initid.id,
12316		       io->io_hdr.nexus.targ_port,
12317		       io->io_hdr.nexus.targ_target.id,
12318		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12319		       io->taskio.tag_type);
12320#endif
12321	}
12322	return (0);
12323}
12324
12325static void
12326ctl_run_task(union ctl_io *io)
12327{
12328	struct ctl_softc *ctl_softc = control_softc;
12329	int retval = 1;
12330	const char *task_desc;
12331
12332	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12333
12334	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12335	    ("ctl_run_task: Unextected io_type %d\n",
12336	     io->io_hdr.io_type));
12337
12338	task_desc = ctl_scsi_task_string(&io->taskio);
12339	if (task_desc != NULL) {
12340#ifdef NEEDTOPORT
12341		csevent_log(CSC_CTL | CSC_SHELF_SW |
12342			    CTL_TASK_REPORT,
12343			    csevent_LogType_Trace,
12344			    csevent_Severity_Information,
12345			    csevent_AlertLevel_Green,
12346			    csevent_FRU_Firmware,
12347			    csevent_FRU_Unknown,
12348			    "CTL: received task: %s",task_desc);
12349#endif
12350	} else {
12351#ifdef NEEDTOPORT
12352		csevent_log(CSC_CTL | CSC_SHELF_SW |
12353			    CTL_TASK_REPORT,
12354			    csevent_LogType_Trace,
12355			    csevent_Severity_Information,
12356			    csevent_AlertLevel_Green,
12357			    csevent_FRU_Firmware,
12358			    csevent_FRU_Unknown,
12359			    "CTL: received unknown task "
12360			    "type: %d (%#x)",
12361			    io->taskio.task_action,
12362			    io->taskio.task_action);
12363#endif
12364	}
12365	switch (io->taskio.task_action) {
12366	case CTL_TASK_ABORT_TASK:
12367		retval = ctl_abort_task(io);
12368		break;
12369	case CTL_TASK_ABORT_TASK_SET:
12370	case CTL_TASK_CLEAR_TASK_SET:
12371		retval = ctl_abort_task_set(io);
12372		break;
12373	case CTL_TASK_CLEAR_ACA:
12374		break;
12375	case CTL_TASK_I_T_NEXUS_RESET:
12376		retval = ctl_i_t_nexus_reset(io);
12377		break;
12378	case CTL_TASK_LUN_RESET: {
12379		struct ctl_lun *lun;
12380		uint32_t targ_lun;
12381
12382		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12383		mtx_lock(&ctl_softc->ctl_lock);
12384		if ((targ_lun < CTL_MAX_LUNS)
12385		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12386			lun = ctl_softc->ctl_luns[targ_lun];
12387		else {
12388			mtx_unlock(&ctl_softc->ctl_lock);
12389			retval = 1;
12390			break;
12391		}
12392
12393		if (!(io->io_hdr.flags &
12394		    CTL_FLAG_FROM_OTHER_SC)) {
12395			union ctl_ha_msg msg_info;
12396
12397			io->io_hdr.flags |=
12398				CTL_FLAG_SENT_2OTHER_SC;
12399			msg_info.hdr.msg_type =
12400				CTL_MSG_MANAGE_TASKS;
12401			msg_info.hdr.nexus = io->io_hdr.nexus;
12402			msg_info.task.task_action =
12403				CTL_TASK_LUN_RESET;
12404			msg_info.hdr.original_sc = NULL;
12405			msg_info.hdr.serializing_sc = NULL;
12406			if (CTL_HA_STATUS_SUCCESS !=
12407			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12408			    (void *)&msg_info,
12409			    sizeof(msg_info), 0)) {
12410			}
12411		}
12412
12413		retval = ctl_lun_reset(lun, io,
12414				       CTL_UA_LUN_RESET);
12415		mtx_unlock(&ctl_softc->ctl_lock);
12416		break;
12417	}
12418	case CTL_TASK_TARGET_RESET:
12419		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12420		break;
12421	case CTL_TASK_BUS_RESET:
12422		retval = ctl_bus_reset(ctl_softc, io);
12423		break;
12424	case CTL_TASK_PORT_LOGIN:
12425		break;
12426	case CTL_TASK_PORT_LOGOUT:
12427		break;
12428	default:
12429		printf("ctl_run_task: got unknown task management event %d\n",
12430		       io->taskio.task_action);
12431		break;
12432	}
12433	if (retval == 0)
12434		io->io_hdr.status = CTL_SUCCESS;
12435	else
12436		io->io_hdr.status = CTL_ERROR;
12437	ctl_done(io);
12438}
12439
12440/*
12441 * For HA operation.  Handle commands that come in from the other
12442 * controller.
12443 */
12444static void
12445ctl_handle_isc(union ctl_io *io)
12446{
12447	int free_io;
12448	struct ctl_lun *lun;
12449	struct ctl_softc *ctl_softc;
12450	uint32_t targ_lun;
12451
12452	ctl_softc = control_softc;
12453
12454	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12455	lun = ctl_softc->ctl_luns[targ_lun];
12456
12457	switch (io->io_hdr.msg_type) {
12458	case CTL_MSG_SERIALIZE:
12459		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12460		break;
12461	case CTL_MSG_R2R: {
12462		const struct ctl_cmd_entry *entry;
12463
12464		/*
12465		 * This is only used in SER_ONLY mode.
12466		 */
12467		free_io = 0;
12468		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12469		mtx_lock(&lun->lun_lock);
12470		if (ctl_scsiio_lun_check(ctl_softc, lun,
12471		    entry, (struct ctl_scsiio *)io) != 0) {
12472			mtx_unlock(&lun->lun_lock);
12473			ctl_done(io);
12474			break;
12475		}
12476		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12477		mtx_unlock(&lun->lun_lock);
12478		ctl_enqueue_rtr(io);
12479		break;
12480	}
12481	case CTL_MSG_FINISH_IO:
12482		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12483			free_io = 0;
12484			ctl_done(io);
12485		} else {
12486			free_io = 1;
12487			mtx_lock(&lun->lun_lock);
12488			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12489				     ooa_links);
12490			ctl_check_blocked(lun);
12491			mtx_unlock(&lun->lun_lock);
12492		}
12493		break;
12494	case CTL_MSG_PERS_ACTION:
12495		ctl_hndl_per_res_out_on_other_sc(
12496			(union ctl_ha_msg *)&io->presio.pr_msg);
12497		free_io = 1;
12498		break;
12499	case CTL_MSG_BAD_JUJU:
12500		free_io = 0;
12501		ctl_done(io);
12502		break;
12503	case CTL_MSG_DATAMOVE:
12504		/* Only used in XFER mode */
12505		free_io = 0;
12506		ctl_datamove_remote(io);
12507		break;
12508	case CTL_MSG_DATAMOVE_DONE:
12509		/* Only used in XFER mode */
12510		free_io = 0;
12511		io->scsiio.be_move_done(io);
12512		break;
12513	default:
12514		free_io = 1;
12515		printf("%s: Invalid message type %d\n",
12516		       __func__, io->io_hdr.msg_type);
12517		break;
12518	}
12519	if (free_io)
12520		ctl_free_io(io);
12521
12522}
12523
12524
12525/*
12526 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12527 * there is no match.
12528 */
12529static ctl_lun_error_pattern
12530ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12531{
12532	const struct ctl_cmd_entry *entry;
12533	ctl_lun_error_pattern filtered_pattern, pattern;
12534
12535	pattern = desc->error_pattern;
12536
12537	/*
12538	 * XXX KDM we need more data passed into this function to match a
12539	 * custom pattern, and we actually need to implement custom pattern
12540	 * matching.
12541	 */
12542	if (pattern & CTL_LUN_PAT_CMD)
12543		return (CTL_LUN_PAT_CMD);
12544
12545	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12546		return (CTL_LUN_PAT_ANY);
12547
12548	entry = ctl_get_cmd_entry(ctsio, NULL);
12549
12550	filtered_pattern = entry->pattern & pattern;
12551
12552	/*
12553	 * If the user requested specific flags in the pattern (e.g.
12554	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12555	 * flags.
12556	 *
12557	 * If the user did not specify any flags, it doesn't matter whether
12558	 * or not the command supports the flags.
12559	 */
12560	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12561	     (pattern & ~CTL_LUN_PAT_MASK))
12562		return (CTL_LUN_PAT_NONE);
12563
12564	/*
12565	 * If the user asked for a range check, see if the requested LBA
12566	 * range overlaps with this command's LBA range.
12567	 */
12568	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12569		uint64_t lba1;
12570		uint64_t len1;
12571		ctl_action action;
12572		int retval;
12573
12574		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12575		if (retval != 0)
12576			return (CTL_LUN_PAT_NONE);
12577
12578		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12579					      desc->lba_range.len);
12580		/*
12581		 * A "pass" means that the LBA ranges don't overlap, so
12582		 * this doesn't match the user's range criteria.
12583		 */
12584		if (action == CTL_ACTION_PASS)
12585			return (CTL_LUN_PAT_NONE);
12586	}
12587
12588	return (filtered_pattern);
12589}
12590
12591static void
12592ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12593{
12594	struct ctl_error_desc *desc, *desc2;
12595
12596	mtx_assert(&lun->lun_lock, MA_OWNED);
12597
12598	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12599		ctl_lun_error_pattern pattern;
12600		/*
12601		 * Check to see whether this particular command matches
12602		 * the pattern in the descriptor.
12603		 */
12604		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12605		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12606			continue;
12607
12608		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12609		case CTL_LUN_INJ_ABORTED:
12610			ctl_set_aborted(&io->scsiio);
12611			break;
12612		case CTL_LUN_INJ_MEDIUM_ERR:
12613			ctl_set_medium_error(&io->scsiio);
12614			break;
12615		case CTL_LUN_INJ_UA:
12616			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12617			 * OCCURRED */
12618			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12619			break;
12620		case CTL_LUN_INJ_CUSTOM:
12621			/*
12622			 * We're assuming the user knows what he is doing.
12623			 * Just copy the sense information without doing
12624			 * checks.
12625			 */
12626			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12627			      ctl_min(sizeof(desc->custom_sense),
12628				      sizeof(io->scsiio.sense_data)));
12629			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12630			io->scsiio.sense_len = SSD_FULL_SIZE;
12631			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12632			break;
12633		case CTL_LUN_INJ_NONE:
12634		default:
12635			/*
12636			 * If this is an error injection type we don't know
12637			 * about, clear the continuous flag (if it is set)
12638			 * so it will get deleted below.
12639			 */
12640			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12641			break;
12642		}
12643		/*
12644		 * By default, each error injection action is a one-shot
12645		 */
12646		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12647			continue;
12648
12649		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12650
12651		free(desc, M_CTL);
12652	}
12653}
12654
12655#ifdef CTL_IO_DELAY
12656static void
12657ctl_datamove_timer_wakeup(void *arg)
12658{
12659	union ctl_io *io;
12660
12661	io = (union ctl_io *)arg;
12662
12663	ctl_datamove(io);
12664}
12665#endif /* CTL_IO_DELAY */
12666
12667void
12668ctl_datamove(union ctl_io *io)
12669{
12670	void (*fe_datamove)(union ctl_io *io);
12671
12672	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12673
12674	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12675
12676#ifdef CTL_TIME_IO
12677	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12678		char str[256];
12679		char path_str[64];
12680		struct sbuf sb;
12681
12682		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12683		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12684
12685		sbuf_cat(&sb, path_str);
12686		switch (io->io_hdr.io_type) {
12687		case CTL_IO_SCSI:
12688			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12689			sbuf_printf(&sb, "\n");
12690			sbuf_cat(&sb, path_str);
12691			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12692				    io->scsiio.tag_num, io->scsiio.tag_type);
12693			break;
12694		case CTL_IO_TASK:
12695			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12696				    "Tag Type: %d\n", io->taskio.task_action,
12697				    io->taskio.tag_num, io->taskio.tag_type);
12698			break;
12699		default:
12700			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12701			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12702			break;
12703		}
12704		sbuf_cat(&sb, path_str);
12705		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12706			    (intmax_t)time_uptime - io->io_hdr.start_time);
12707		sbuf_finish(&sb);
12708		printf("%s", sbuf_data(&sb));
12709	}
12710#endif /* CTL_TIME_IO */
12711
12712#ifdef CTL_IO_DELAY
12713	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12714		struct ctl_lun *lun;
12715
12716		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12717
12718		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12719	} else {
12720		struct ctl_lun *lun;
12721
12722		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12723		if ((lun != NULL)
12724		 && (lun->delay_info.datamove_delay > 0)) {
12725			struct callout *callout;
12726
12727			callout = (struct callout *)&io->io_hdr.timer_bytes;
12728			callout_init(callout, /*mpsafe*/ 1);
12729			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12730			callout_reset(callout,
12731				      lun->delay_info.datamove_delay * hz,
12732				      ctl_datamove_timer_wakeup, io);
12733			if (lun->delay_info.datamove_type ==
12734			    CTL_DELAY_TYPE_ONESHOT)
12735				lun->delay_info.datamove_delay = 0;
12736			return;
12737		}
12738	}
12739#endif
12740
12741	/*
12742	 * This command has been aborted.  Set the port status, so we fail
12743	 * the data move.
12744	 */
12745	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12746		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12747		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12748		       io->io_hdr.nexus.targ_port,
12749		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12750		       io->io_hdr.nexus.targ_lun);
12751		io->io_hdr.port_status = 31337;
12752		/*
12753		 * Note that the backend, in this case, will get the
12754		 * callback in its context.  In other cases it may get
12755		 * called in the frontend's interrupt thread context.
12756		 */
12757		io->scsiio.be_move_done(io);
12758		return;
12759	}
12760
12761	/*
12762	 * If we're in XFER mode and this I/O is from the other shelf
12763	 * controller, we need to send the DMA to the other side to
12764	 * actually transfer the data to/from the host.  In serialize only
12765	 * mode the transfer happens below CTL and ctl_datamove() is only
12766	 * called on the machine that originally received the I/O.
12767	 */
12768	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12769	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12770		union ctl_ha_msg msg;
12771		uint32_t sg_entries_sent;
12772		int do_sg_copy;
12773		int i;
12774
12775		memset(&msg, 0, sizeof(msg));
12776		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12777		msg.hdr.original_sc = io->io_hdr.original_sc;
12778		msg.hdr.serializing_sc = io;
12779		msg.hdr.nexus = io->io_hdr.nexus;
12780		msg.dt.flags = io->io_hdr.flags;
12781		/*
12782		 * We convert everything into a S/G list here.  We can't
12783		 * pass by reference, only by value between controllers.
12784		 * So we can't pass a pointer to the S/G list, only as many
12785		 * S/G entries as we can fit in here.  If it's possible for
12786		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12787		 * then we need to break this up into multiple transfers.
12788		 */
12789		if (io->scsiio.kern_sg_entries == 0) {
12790			msg.dt.kern_sg_entries = 1;
12791			/*
12792			 * If this is in cached memory, flush the cache
12793			 * before we send the DMA request to the other
12794			 * controller.  We want to do this in either the
12795			 * read or the write case.  The read case is
12796			 * straightforward.  In the write case, we want to
12797			 * make sure nothing is in the local cache that
12798			 * could overwrite the DMAed data.
12799			 */
12800			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12801				/*
12802				 * XXX KDM use bus_dmamap_sync() here.
12803				 */
12804			}
12805
12806			/*
12807			 * Convert to a physical address if this is a
12808			 * virtual address.
12809			 */
12810			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12811				msg.dt.sg_list[0].addr =
12812					io->scsiio.kern_data_ptr;
12813			} else {
12814				/*
12815				 * XXX KDM use busdma here!
12816				 */
12817#if 0
12818				msg.dt.sg_list[0].addr = (void *)
12819					vtophys(io->scsiio.kern_data_ptr);
12820#endif
12821			}
12822
12823			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12824			do_sg_copy = 0;
12825		} else {
12826			struct ctl_sg_entry *sgl;
12827
12828			do_sg_copy = 1;
12829			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12830			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12831			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12832				/*
12833				 * XXX KDM use bus_dmamap_sync() here.
12834				 */
12835			}
12836		}
12837
12838		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12839		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12840		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12841		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12842		msg.dt.sg_sequence = 0;
12843
12844		/*
12845		 * Loop until we've sent all of the S/G entries.  On the
12846		 * other end, we'll recompose these S/G entries into one
12847		 * contiguous list before passing it to the
12848		 */
12849		for (sg_entries_sent = 0; sg_entries_sent <
12850		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12851			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12852				sizeof(msg.dt.sg_list[0])),
12853				msg.dt.kern_sg_entries - sg_entries_sent);
12854
12855			if (do_sg_copy != 0) {
12856				struct ctl_sg_entry *sgl;
12857				int j;
12858
12859				sgl = (struct ctl_sg_entry *)
12860					io->scsiio.kern_data_ptr;
12861				/*
12862				 * If this is in cached memory, flush the cache
12863				 * before we send the DMA request to the other
12864				 * controller.  We want to do this in either
12865				 * the * read or the write case.  The read
12866				 * case is straightforward.  In the write
12867				 * case, we want to make sure nothing is
12868				 * in the local cache that could overwrite
12869				 * the DMAed data.
12870				 */
12871
12872				for (i = sg_entries_sent, j = 0;
12873				     i < msg.dt.cur_sg_entries; i++, j++) {
12874					if ((io->io_hdr.flags &
12875					     CTL_FLAG_NO_DATASYNC) == 0) {
12876						/*
12877						 * XXX KDM use bus_dmamap_sync()
12878						 */
12879					}
12880					if ((io->io_hdr.flags &
12881					     CTL_FLAG_BUS_ADDR) == 0) {
12882						/*
12883						 * XXX KDM use busdma.
12884						 */
12885#if 0
12886						msg.dt.sg_list[j].addr =(void *)
12887						       vtophys(sgl[i].addr);
12888#endif
12889					} else {
12890						msg.dt.sg_list[j].addr =
12891							sgl[i].addr;
12892					}
12893					msg.dt.sg_list[j].len = sgl[i].len;
12894				}
12895			}
12896
12897			sg_entries_sent += msg.dt.cur_sg_entries;
12898			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12899				msg.dt.sg_last = 1;
12900			else
12901				msg.dt.sg_last = 0;
12902
12903			/*
12904			 * XXX KDM drop and reacquire the lock here?
12905			 */
12906			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12907			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12908				/*
12909				 * XXX do something here.
12910				 */
12911			}
12912
12913			msg.dt.sent_sg_entries = sg_entries_sent;
12914		}
12915		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12916		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12917			ctl_failover_io(io, /*have_lock*/ 0);
12918
12919	} else {
12920
12921		/*
12922		 * Lookup the fe_datamove() function for this particular
12923		 * front end.
12924		 */
12925		fe_datamove =
12926		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12927
12928		fe_datamove(io);
12929	}
12930}
12931
12932static void
12933ctl_send_datamove_done(union ctl_io *io, int have_lock)
12934{
12935	union ctl_ha_msg msg;
12936	int isc_status;
12937
12938	memset(&msg, 0, sizeof(msg));
12939
12940	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12941	msg.hdr.original_sc = io;
12942	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12943	msg.hdr.nexus = io->io_hdr.nexus;
12944	msg.hdr.status = io->io_hdr.status;
12945	msg.scsi.tag_num = io->scsiio.tag_num;
12946	msg.scsi.tag_type = io->scsiio.tag_type;
12947	msg.scsi.scsi_status = io->scsiio.scsi_status;
12948	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12949	       sizeof(io->scsiio.sense_data));
12950	msg.scsi.sense_len = io->scsiio.sense_len;
12951	msg.scsi.sense_residual = io->scsiio.sense_residual;
12952	msg.scsi.fetd_status = io->io_hdr.port_status;
12953	msg.scsi.residual = io->scsiio.residual;
12954	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12955
12956	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12957		ctl_failover_io(io, /*have_lock*/ have_lock);
12958		return;
12959	}
12960
12961	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12962	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12963		/* XXX do something if this fails */
12964	}
12965
12966}
12967
12968/*
12969 * The DMA to the remote side is done, now we need to tell the other side
12970 * we're done so it can continue with its data movement.
12971 */
12972static void
12973ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12974{
12975	union ctl_io *io;
12976
12977	io = rq->context;
12978
12979	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12980		printf("%s: ISC DMA write failed with error %d", __func__,
12981		       rq->ret);
12982		ctl_set_internal_failure(&io->scsiio,
12983					 /*sks_valid*/ 1,
12984					 /*retry_count*/ rq->ret);
12985	}
12986
12987	ctl_dt_req_free(rq);
12988
12989	/*
12990	 * In this case, we had to malloc the memory locally.  Free it.
12991	 */
12992	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12993		int i;
12994		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12995			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12996	}
12997	/*
12998	 * The data is in local and remote memory, so now we need to send
12999	 * status (good or back) back to the other side.
13000	 */
13001	ctl_send_datamove_done(io, /*have_lock*/ 0);
13002}
13003
13004/*
13005 * We've moved the data from the host/controller into local memory.  Now we
13006 * need to push it over to the remote controller's memory.
13007 */
13008static int
13009ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13010{
13011	int retval;
13012
13013	retval = 0;
13014
13015	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13016					  ctl_datamove_remote_write_cb);
13017
13018	return (retval);
13019}
13020
13021static void
13022ctl_datamove_remote_write(union ctl_io *io)
13023{
13024	int retval;
13025	void (*fe_datamove)(union ctl_io *io);
13026
13027	/*
13028	 * - Get the data from the host/HBA into local memory.
13029	 * - DMA memory from the local controller to the remote controller.
13030	 * - Send status back to the remote controller.
13031	 */
13032
13033	retval = ctl_datamove_remote_sgl_setup(io);
13034	if (retval != 0)
13035		return;
13036
13037	/* Switch the pointer over so the FETD knows what to do */
13038	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13039
13040	/*
13041	 * Use a custom move done callback, since we need to send completion
13042	 * back to the other controller, not to the backend on this side.
13043	 */
13044	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13045
13046	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13047
13048	fe_datamove(io);
13049
13050	return;
13051
13052}
13053
13054static int
13055ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13056{
13057#if 0
13058	char str[256];
13059	char path_str[64];
13060	struct sbuf sb;
13061#endif
13062
13063	/*
13064	 * In this case, we had to malloc the memory locally.  Free it.
13065	 */
13066	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13067		int i;
13068		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13069			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13070	}
13071
13072#if 0
13073	scsi_path_string(io, path_str, sizeof(path_str));
13074	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13075	sbuf_cat(&sb, path_str);
13076	scsi_command_string(&io->scsiio, NULL, &sb);
13077	sbuf_printf(&sb, "\n");
13078	sbuf_cat(&sb, path_str);
13079	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13080		    io->scsiio.tag_num, io->scsiio.tag_type);
13081	sbuf_cat(&sb, path_str);
13082	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13083		    io->io_hdr.flags, io->io_hdr.status);
13084	sbuf_finish(&sb);
13085	printk("%s", sbuf_data(&sb));
13086#endif
13087
13088
13089	/*
13090	 * The read is done, now we need to send status (good or bad) back
13091	 * to the other side.
13092	 */
13093	ctl_send_datamove_done(io, /*have_lock*/ 0);
13094
13095	return (0);
13096}
13097
13098static void
13099ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13100{
13101	union ctl_io *io;
13102	void (*fe_datamove)(union ctl_io *io);
13103
13104	io = rq->context;
13105
13106	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13107		printf("%s: ISC DMA read failed with error %d", __func__,
13108		       rq->ret);
13109		ctl_set_internal_failure(&io->scsiio,
13110					 /*sks_valid*/ 1,
13111					 /*retry_count*/ rq->ret);
13112	}
13113
13114	ctl_dt_req_free(rq);
13115
13116	/* Switch the pointer over so the FETD knows what to do */
13117	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13118
13119	/*
13120	 * Use a custom move done callback, since we need to send completion
13121	 * back to the other controller, not to the backend on this side.
13122	 */
13123	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13124
13125	/* XXX KDM add checks like the ones in ctl_datamove? */
13126
13127	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13128
13129	fe_datamove(io);
13130}
13131
13132static int
13133ctl_datamove_remote_sgl_setup(union ctl_io *io)
13134{
13135	struct ctl_sg_entry *local_sglist, *remote_sglist;
13136	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13137	struct ctl_softc *softc;
13138	int retval;
13139	int i;
13140
13141	retval = 0;
13142	softc = control_softc;
13143
13144	local_sglist = io->io_hdr.local_sglist;
13145	local_dma_sglist = io->io_hdr.local_dma_sglist;
13146	remote_sglist = io->io_hdr.remote_sglist;
13147	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13148
13149	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13150		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13151			local_sglist[i].len = remote_sglist[i].len;
13152
13153			/*
13154			 * XXX Detect the situation where the RS-level I/O
13155			 * redirector on the other side has already read the
13156			 * data off of the AOR RS on this side, and
13157			 * transferred it to remote (mirror) memory on the
13158			 * other side.  Since we already have the data in
13159			 * memory here, we just need to use it.
13160			 *
13161			 * XXX KDM this can probably be removed once we
13162			 * get the cache device code in and take the
13163			 * current AOR implementation out.
13164			 */
13165#ifdef NEEDTOPORT
13166			if ((remote_sglist[i].addr >=
13167			     (void *)vtophys(softc->mirr->addr))
13168			 && (remote_sglist[i].addr <
13169			     ((void *)vtophys(softc->mirr->addr) +
13170			     CacheMirrorOffset))) {
13171				local_sglist[i].addr = remote_sglist[i].addr -
13172					CacheMirrorOffset;
13173				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13174				     CTL_FLAG_DATA_IN)
13175					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13176			} else {
13177				local_sglist[i].addr = remote_sglist[i].addr +
13178					CacheMirrorOffset;
13179			}
13180#endif
13181#if 0
13182			printf("%s: local %p, remote %p, len %d\n",
13183			       __func__, local_sglist[i].addr,
13184			       remote_sglist[i].addr, local_sglist[i].len);
13185#endif
13186		}
13187	} else {
13188		uint32_t len_to_go;
13189
13190		/*
13191		 * In this case, we don't have automatically allocated
13192		 * memory for this I/O on this controller.  This typically
13193		 * happens with internal CTL I/O -- e.g. inquiry, mode
13194		 * sense, etc.  Anything coming from RAIDCore will have
13195		 * a mirror area available.
13196		 */
13197		len_to_go = io->scsiio.kern_data_len;
13198
13199		/*
13200		 * Clear the no datasync flag, we have to use malloced
13201		 * buffers.
13202		 */
13203		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13204
13205		/*
13206		 * The difficult thing here is that the size of the various
13207		 * S/G segments may be different than the size from the
13208		 * remote controller.  That'll make it harder when DMAing
13209		 * the data back to the other side.
13210		 */
13211		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13212		     sizeof(io->io_hdr.remote_sglist[0])) &&
13213		     (len_to_go > 0); i++) {
13214			local_sglist[i].len = ctl_min(len_to_go, 131072);
13215			CTL_SIZE_8B(local_dma_sglist[i].len,
13216				    local_sglist[i].len);
13217			local_sglist[i].addr =
13218				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13219
13220			local_dma_sglist[i].addr = local_sglist[i].addr;
13221
13222			if (local_sglist[i].addr == NULL) {
13223				int j;
13224
13225				printf("malloc failed for %zd bytes!",
13226				       local_dma_sglist[i].len);
13227				for (j = 0; j < i; j++) {
13228					free(local_sglist[j].addr, M_CTL);
13229				}
13230				ctl_set_internal_failure(&io->scsiio,
13231							 /*sks_valid*/ 1,
13232							 /*retry_count*/ 4857);
13233				retval = 1;
13234				goto bailout_error;
13235
13236			}
13237			/* XXX KDM do we need a sync here? */
13238
13239			len_to_go -= local_sglist[i].len;
13240		}
13241		/*
13242		 * Reset the number of S/G entries accordingly.  The
13243		 * original number of S/G entries is available in
13244		 * rem_sg_entries.
13245		 */
13246		io->scsiio.kern_sg_entries = i;
13247
13248#if 0
13249		printf("%s: kern_sg_entries = %d\n", __func__,
13250		       io->scsiio.kern_sg_entries);
13251		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13252			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13253			       local_sglist[i].addr, local_sglist[i].len,
13254			       local_dma_sglist[i].len);
13255#endif
13256	}
13257
13258
13259	return (retval);
13260
13261bailout_error:
13262
13263	ctl_send_datamove_done(io, /*have_lock*/ 0);
13264
13265	return (retval);
13266}
13267
13268static int
13269ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13270			 ctl_ha_dt_cb callback)
13271{
13272	struct ctl_ha_dt_req *rq;
13273	struct ctl_sg_entry *remote_sglist, *local_sglist;
13274	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13275	uint32_t local_used, remote_used, total_used;
13276	int retval;
13277	int i, j;
13278
13279	retval = 0;
13280
13281	rq = ctl_dt_req_alloc();
13282
13283	/*
13284	 * If we failed to allocate the request, and if the DMA didn't fail
13285	 * anyway, set busy status.  This is just a resource allocation
13286	 * failure.
13287	 */
13288	if ((rq == NULL)
13289	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13290		ctl_set_busy(&io->scsiio);
13291
13292	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13293
13294		if (rq != NULL)
13295			ctl_dt_req_free(rq);
13296
13297		/*
13298		 * The data move failed.  We need to return status back
13299		 * to the other controller.  No point in trying to DMA
13300		 * data to the remote controller.
13301		 */
13302
13303		ctl_send_datamove_done(io, /*have_lock*/ 0);
13304
13305		retval = 1;
13306
13307		goto bailout;
13308	}
13309
13310	local_sglist = io->io_hdr.local_sglist;
13311	local_dma_sglist = io->io_hdr.local_dma_sglist;
13312	remote_sglist = io->io_hdr.remote_sglist;
13313	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13314	local_used = 0;
13315	remote_used = 0;
13316	total_used = 0;
13317
13318	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13319		rq->ret = CTL_HA_STATUS_SUCCESS;
13320		rq->context = io;
13321		callback(rq);
13322		goto bailout;
13323	}
13324
13325	/*
13326	 * Pull/push the data over the wire from/to the other controller.
13327	 * This takes into account the possibility that the local and
13328	 * remote sglists may not be identical in terms of the size of
13329	 * the elements and the number of elements.
13330	 *
13331	 * One fundamental assumption here is that the length allocated for
13332	 * both the local and remote sglists is identical.  Otherwise, we've
13333	 * essentially got a coding error of some sort.
13334	 */
13335	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13336		int isc_ret;
13337		uint32_t cur_len, dma_length;
13338		uint8_t *tmp_ptr;
13339
13340		rq->id = CTL_HA_DATA_CTL;
13341		rq->command = command;
13342		rq->context = io;
13343
13344		/*
13345		 * Both pointers should be aligned.  But it is possible
13346		 * that the allocation length is not.  They should both
13347		 * also have enough slack left over at the end, though,
13348		 * to round up to the next 8 byte boundary.
13349		 */
13350		cur_len = ctl_min(local_sglist[i].len - local_used,
13351				  remote_sglist[j].len - remote_used);
13352
13353		/*
13354		 * In this case, we have a size issue and need to decrease
13355		 * the size, except in the case where we actually have less
13356		 * than 8 bytes left.  In that case, we need to increase
13357		 * the DMA length to get the last bit.
13358		 */
13359		if ((cur_len & 0x7) != 0) {
13360			if (cur_len > 0x7) {
13361				cur_len = cur_len - (cur_len & 0x7);
13362				dma_length = cur_len;
13363			} else {
13364				CTL_SIZE_8B(dma_length, cur_len);
13365			}
13366
13367		} else
13368			dma_length = cur_len;
13369
13370		/*
13371		 * If we had to allocate memory for this I/O, instead of using
13372		 * the non-cached mirror memory, we'll need to flush the cache
13373		 * before trying to DMA to the other controller.
13374		 *
13375		 * We could end up doing this multiple times for the same
13376		 * segment if we have a larger local segment than remote
13377		 * segment.  That shouldn't be an issue.
13378		 */
13379		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13380			/*
13381			 * XXX KDM use bus_dmamap_sync() here.
13382			 */
13383		}
13384
13385		rq->size = dma_length;
13386
13387		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13388		tmp_ptr += local_used;
13389
13390		/* Use physical addresses when talking to ISC hardware */
13391		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13392			/* XXX KDM use busdma */
13393#if 0
13394			rq->local = vtophys(tmp_ptr);
13395#endif
13396		} else
13397			rq->local = tmp_ptr;
13398
13399		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13400		tmp_ptr += remote_used;
13401		rq->remote = tmp_ptr;
13402
13403		rq->callback = NULL;
13404
13405		local_used += cur_len;
13406		if (local_used >= local_sglist[i].len) {
13407			i++;
13408			local_used = 0;
13409		}
13410
13411		remote_used += cur_len;
13412		if (remote_used >= remote_sglist[j].len) {
13413			j++;
13414			remote_used = 0;
13415		}
13416		total_used += cur_len;
13417
13418		if (total_used >= io->scsiio.kern_data_len)
13419			rq->callback = callback;
13420
13421		if ((rq->size & 0x7) != 0) {
13422			printf("%s: warning: size %d is not on 8b boundary\n",
13423			       __func__, rq->size);
13424		}
13425		if (((uintptr_t)rq->local & 0x7) != 0) {
13426			printf("%s: warning: local %p not on 8b boundary\n",
13427			       __func__, rq->local);
13428		}
13429		if (((uintptr_t)rq->remote & 0x7) != 0) {
13430			printf("%s: warning: remote %p not on 8b boundary\n",
13431			       __func__, rq->local);
13432		}
13433#if 0
13434		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13435		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13436		       rq->local, rq->remote, rq->size);
13437#endif
13438
13439		isc_ret = ctl_dt_single(rq);
13440		if (isc_ret == CTL_HA_STATUS_WAIT)
13441			continue;
13442
13443		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13444			rq->ret = CTL_HA_STATUS_SUCCESS;
13445		} else {
13446			rq->ret = isc_ret;
13447		}
13448		callback(rq);
13449		goto bailout;
13450	}
13451
13452bailout:
13453	return (retval);
13454
13455}
13456
13457static void
13458ctl_datamove_remote_read(union ctl_io *io)
13459{
13460	int retval;
13461	int i;
13462
13463	/*
13464	 * This will send an error to the other controller in the case of a
13465	 * failure.
13466	 */
13467	retval = ctl_datamove_remote_sgl_setup(io);
13468	if (retval != 0)
13469		return;
13470
13471	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13472					  ctl_datamove_remote_read_cb);
13473	if ((retval != 0)
13474	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13475		/*
13476		 * Make sure we free memory if there was an error..  The
13477		 * ctl_datamove_remote_xfer() function will send the
13478		 * datamove done message, or call the callback with an
13479		 * error if there is a problem.
13480		 */
13481		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13482			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13483	}
13484
13485	return;
13486}
13487
13488/*
13489 * Process a datamove request from the other controller.  This is used for
13490 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13491 * first.  Once that is complete, the data gets DMAed into the remote
13492 * controller's memory.  For reads, we DMA from the remote controller's
13493 * memory into our memory first, and then move it out to the FETD.
13494 */
13495static void
13496ctl_datamove_remote(union ctl_io *io)
13497{
13498	struct ctl_softc *softc;
13499
13500	softc = control_softc;
13501
13502	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13503
13504	/*
13505	 * Note that we look for an aborted I/O here, but don't do some of
13506	 * the other checks that ctl_datamove() normally does.
13507	 * We don't need to run the datamove delay code, since that should
13508	 * have been done if need be on the other controller.
13509	 */
13510	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13511		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13512		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13513		       io->io_hdr.nexus.targ_port,
13514		       io->io_hdr.nexus.targ_target.id,
13515		       io->io_hdr.nexus.targ_lun);
13516		io->io_hdr.port_status = 31338;
13517		ctl_send_datamove_done(io, /*have_lock*/ 0);
13518		return;
13519	}
13520
13521	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13522		ctl_datamove_remote_write(io);
13523	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13524		ctl_datamove_remote_read(io);
13525	} else {
13526		union ctl_ha_msg msg;
13527		struct scsi_sense_data *sense;
13528		uint8_t sks[3];
13529		int retry_count;
13530
13531		memset(&msg, 0, sizeof(msg));
13532
13533		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13534		msg.hdr.status = CTL_SCSI_ERROR;
13535		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13536
13537		retry_count = 4243;
13538
13539		sense = &msg.scsi.sense_data;
13540		sks[0] = SSD_SCS_VALID;
13541		sks[1] = (retry_count >> 8) & 0xff;
13542		sks[2] = retry_count & 0xff;
13543
13544		/* "Internal target failure" */
13545		scsi_set_sense_data(sense,
13546				    /*sense_format*/ SSD_TYPE_NONE,
13547				    /*current_error*/ 1,
13548				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13549				    /*asc*/ 0x44,
13550				    /*ascq*/ 0x00,
13551				    /*type*/ SSD_ELEM_SKS,
13552				    /*size*/ sizeof(sks),
13553				    /*data*/ sks,
13554				    SSD_ELEM_NONE);
13555
13556		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13557		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13558			ctl_failover_io(io, /*have_lock*/ 1);
13559			return;
13560		}
13561
13562		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13563		    CTL_HA_STATUS_SUCCESS) {
13564			/* XXX KDM what to do if this fails? */
13565		}
13566		return;
13567	}
13568
13569}
13570
13571static int
13572ctl_process_done(union ctl_io *io)
13573{
13574	struct ctl_lun *lun;
13575	struct ctl_softc *ctl_softc;
13576	void (*fe_done)(union ctl_io *io);
13577	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13578
13579	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13580
13581	fe_done =
13582	    control_softc->ctl_ports[targ_port]->fe_done;
13583
13584#ifdef CTL_TIME_IO
13585	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13586		char str[256];
13587		char path_str[64];
13588		struct sbuf sb;
13589
13590		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13591		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13592
13593		sbuf_cat(&sb, path_str);
13594		switch (io->io_hdr.io_type) {
13595		case CTL_IO_SCSI:
13596			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13597			sbuf_printf(&sb, "\n");
13598			sbuf_cat(&sb, path_str);
13599			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13600				    io->scsiio.tag_num, io->scsiio.tag_type);
13601			break;
13602		case CTL_IO_TASK:
13603			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13604				    "Tag Type: %d\n", io->taskio.task_action,
13605				    io->taskio.tag_num, io->taskio.tag_type);
13606			break;
13607		default:
13608			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13609			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13610			break;
13611		}
13612		sbuf_cat(&sb, path_str);
13613		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13614			    (intmax_t)time_uptime - io->io_hdr.start_time);
13615		sbuf_finish(&sb);
13616		printf("%s", sbuf_data(&sb));
13617	}
13618#endif /* CTL_TIME_IO */
13619
13620	switch (io->io_hdr.io_type) {
13621	case CTL_IO_SCSI:
13622		break;
13623	case CTL_IO_TASK:
13624		if (bootverbose || verbose > 0)
13625			ctl_io_error_print(io, NULL);
13626		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13627			ctl_free_io(io);
13628		else
13629			fe_done(io);
13630		return (CTL_RETVAL_COMPLETE);
13631		break;
13632	default:
13633		printf("ctl_process_done: invalid io type %d\n",
13634		       io->io_hdr.io_type);
13635		panic("ctl_process_done: invalid io type %d\n",
13636		      io->io_hdr.io_type);
13637		break; /* NOTREACHED */
13638	}
13639
13640	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13641	if (lun == NULL) {
13642		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13643				 io->io_hdr.nexus.targ_mapped_lun));
13644		fe_done(io);
13645		goto bailout;
13646	}
13647	ctl_softc = lun->ctl_softc;
13648
13649	mtx_lock(&lun->lun_lock);
13650
13651	/*
13652	 * Check to see if we have any errors to inject here.  We only
13653	 * inject errors for commands that don't already have errors set.
13654	 */
13655	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13656	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13657		ctl_inject_error(lun, io);
13658
13659	/*
13660	 * XXX KDM how do we treat commands that aren't completed
13661	 * successfully?
13662	 *
13663	 * XXX KDM should we also track I/O latency?
13664	 */
13665	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13666	    io->io_hdr.io_type == CTL_IO_SCSI) {
13667#ifdef CTL_TIME_IO
13668		struct bintime cur_bt;
13669#endif
13670		int type;
13671
13672		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13673		    CTL_FLAG_DATA_IN)
13674			type = CTL_STATS_READ;
13675		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13676		    CTL_FLAG_DATA_OUT)
13677			type = CTL_STATS_WRITE;
13678		else
13679			type = CTL_STATS_NO_IO;
13680
13681		lun->stats.ports[targ_port].bytes[type] +=
13682		    io->scsiio.kern_total_len;
13683		lun->stats.ports[targ_port].operations[type]++;
13684#ifdef CTL_TIME_IO
13685		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13686		   &io->io_hdr.dma_bt);
13687		lun->stats.ports[targ_port].num_dmas[type] +=
13688		    io->io_hdr.num_dmas;
13689		getbintime(&cur_bt);
13690		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13691		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13692#endif
13693	}
13694
13695	/*
13696	 * Remove this from the OOA queue.
13697	 */
13698	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13699
13700	/*
13701	 * Run through the blocked queue on this LUN and see if anything
13702	 * has become unblocked, now that this transaction is done.
13703	 */
13704	ctl_check_blocked(lun);
13705
13706	/*
13707	 * If the LUN has been invalidated, free it if there is nothing
13708	 * left on its OOA queue.
13709	 */
13710	if ((lun->flags & CTL_LUN_INVALID)
13711	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13712		mtx_unlock(&lun->lun_lock);
13713		mtx_lock(&ctl_softc->ctl_lock);
13714		ctl_free_lun(lun);
13715		mtx_unlock(&ctl_softc->ctl_lock);
13716	} else
13717		mtx_unlock(&lun->lun_lock);
13718
13719	/*
13720	 * If this command has been aborted, make sure we set the status
13721	 * properly.  The FETD is responsible for freeing the I/O and doing
13722	 * whatever it needs to do to clean up its state.
13723	 */
13724	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13725		ctl_set_task_aborted(&io->scsiio);
13726
13727	/*
13728	 * We print out status for every task management command.  For SCSI
13729	 * commands, we filter out any unit attention errors; they happen
13730	 * on every boot, and would clutter up the log.  Note:  task
13731	 * management commands aren't printed here, they are printed above,
13732	 * since they should never even make it down here.
13733	 */
13734	switch (io->io_hdr.io_type) {
13735	case CTL_IO_SCSI: {
13736		int error_code, sense_key, asc, ascq;
13737
13738		sense_key = 0;
13739
13740		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13741		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13742			/*
13743			 * Since this is just for printing, no need to
13744			 * show errors here.
13745			 */
13746			scsi_extract_sense_len(&io->scsiio.sense_data,
13747					       io->scsiio.sense_len,
13748					       &error_code,
13749					       &sense_key,
13750					       &asc,
13751					       &ascq,
13752					       /*show_errors*/ 0);
13753		}
13754
13755		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13756		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13757		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13758		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13759
13760			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13761				ctl_softc->skipped_prints++;
13762			} else {
13763				uint32_t skipped_prints;
13764
13765				skipped_prints = ctl_softc->skipped_prints;
13766
13767				ctl_softc->skipped_prints = 0;
13768				ctl_softc->last_print_jiffies = time_uptime;
13769
13770				if (skipped_prints > 0) {
13771#ifdef NEEDTOPORT
13772					csevent_log(CSC_CTL | CSC_SHELF_SW |
13773					    CTL_ERROR_REPORT,
13774					    csevent_LogType_Trace,
13775					    csevent_Severity_Information,
13776					    csevent_AlertLevel_Green,
13777					    csevent_FRU_Firmware,
13778					    csevent_FRU_Unknown,
13779					    "High CTL error volume, %d prints "
13780					    "skipped", skipped_prints);
13781#endif
13782				}
13783				if (bootverbose || verbose > 0)
13784					ctl_io_error_print(io, NULL);
13785			}
13786		}
13787		break;
13788	}
13789	case CTL_IO_TASK:
13790		if (bootverbose || verbose > 0)
13791			ctl_io_error_print(io, NULL);
13792		break;
13793	default:
13794		break;
13795	}
13796
13797	/*
13798	 * Tell the FETD or the other shelf controller we're done with this
13799	 * command.  Note that only SCSI commands get to this point.  Task
13800	 * management commands are completed above.
13801	 *
13802	 * We only send status to the other controller if we're in XFER
13803	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13804	 * received the I/O (from CTL's perspective), and so the status is
13805	 * generated there.
13806	 *
13807	 * XXX KDM if we hold the lock here, we could cause a deadlock
13808	 * if the frontend comes back in in this context to queue
13809	 * something.
13810	 */
13811	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13812	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13813		union ctl_ha_msg msg;
13814
13815		memset(&msg, 0, sizeof(msg));
13816		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13817		msg.hdr.original_sc = io->io_hdr.original_sc;
13818		msg.hdr.nexus = io->io_hdr.nexus;
13819		msg.hdr.status = io->io_hdr.status;
13820		msg.scsi.scsi_status = io->scsiio.scsi_status;
13821		msg.scsi.tag_num = io->scsiio.tag_num;
13822		msg.scsi.tag_type = io->scsiio.tag_type;
13823		msg.scsi.sense_len = io->scsiio.sense_len;
13824		msg.scsi.sense_residual = io->scsiio.sense_residual;
13825		msg.scsi.residual = io->scsiio.residual;
13826		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13827		       sizeof(io->scsiio.sense_data));
13828		/*
13829		 * We copy this whether or not this is an I/O-related
13830		 * command.  Otherwise, we'd have to go and check to see
13831		 * whether it's a read/write command, and it really isn't
13832		 * worth it.
13833		 */
13834		memcpy(&msg.scsi.lbalen,
13835		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13836		       sizeof(msg.scsi.lbalen));
13837
13838		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13839				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13840			/* XXX do something here */
13841		}
13842
13843		ctl_free_io(io);
13844	} else
13845		fe_done(io);
13846
13847bailout:
13848
13849	return (CTL_RETVAL_COMPLETE);
13850}
13851
13852#ifdef CTL_WITH_CA
13853/*
13854 * Front end should call this if it doesn't do autosense.  When the request
13855 * sense comes back in from the initiator, we'll dequeue this and send it.
13856 */
13857int
13858ctl_queue_sense(union ctl_io *io)
13859{
13860	struct ctl_lun *lun;
13861	struct ctl_softc *ctl_softc;
13862	uint32_t initidx, targ_lun;
13863
13864	ctl_softc = control_softc;
13865
13866	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13867
13868	/*
13869	 * LUN lookup will likely move to the ctl_work_thread() once we
13870	 * have our new queueing infrastructure (that doesn't put things on
13871	 * a per-LUN queue initially).  That is so that we can handle
13872	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13873	 * can't deal with that right now.
13874	 */
13875	mtx_lock(&ctl_softc->ctl_lock);
13876
13877	/*
13878	 * If we don't have a LUN for this, just toss the sense
13879	 * information.
13880	 */
13881	targ_lun = io->io_hdr.nexus.targ_lun;
13882	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13883	if ((targ_lun < CTL_MAX_LUNS)
13884	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13885		lun = ctl_softc->ctl_luns[targ_lun];
13886	else
13887		goto bailout;
13888
13889	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13890
13891	mtx_lock(&lun->lun_lock);
13892	/*
13893	 * Already have CA set for this LUN...toss the sense information.
13894	 */
13895	if (ctl_is_set(lun->have_ca, initidx)) {
13896		mtx_unlock(&lun->lun_lock);
13897		goto bailout;
13898	}
13899
13900	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13901	       ctl_min(sizeof(lun->pending_sense[initidx]),
13902	       sizeof(io->scsiio.sense_data)));
13903	ctl_set_mask(lun->have_ca, initidx);
13904	mtx_unlock(&lun->lun_lock);
13905
13906bailout:
13907	mtx_unlock(&ctl_softc->ctl_lock);
13908
13909	ctl_free_io(io);
13910
13911	return (CTL_RETVAL_COMPLETE);
13912}
13913#endif
13914
13915/*
13916 * Primary command inlet from frontend ports.  All SCSI and task I/O
13917 * requests must go through this function.
13918 */
13919int
13920ctl_queue(union ctl_io *io)
13921{
13922	struct ctl_softc *ctl_softc;
13923
13924	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13925
13926	ctl_softc = control_softc;
13927
13928#ifdef CTL_TIME_IO
13929	io->io_hdr.start_time = time_uptime;
13930	getbintime(&io->io_hdr.start_bt);
13931#endif /* CTL_TIME_IO */
13932
13933	/* Map FE-specific LUN ID into global one. */
13934	io->io_hdr.nexus.targ_mapped_lun =
13935	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13936
13937	switch (io->io_hdr.io_type) {
13938	case CTL_IO_SCSI:
13939	case CTL_IO_TASK:
13940		ctl_enqueue_incoming(io);
13941		break;
13942	default:
13943		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13944		return (EINVAL);
13945	}
13946
13947	return (CTL_RETVAL_COMPLETE);
13948}
13949
13950#ifdef CTL_IO_DELAY
13951static void
13952ctl_done_timer_wakeup(void *arg)
13953{
13954	union ctl_io *io;
13955
13956	io = (union ctl_io *)arg;
13957	ctl_done(io);
13958}
13959#endif /* CTL_IO_DELAY */
13960
13961void
13962ctl_done(union ctl_io *io)
13963{
13964	struct ctl_softc *ctl_softc;
13965
13966	ctl_softc = control_softc;
13967
13968	/*
13969	 * Enable this to catch duplicate completion issues.
13970	 */
13971#if 0
13972	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13973		printf("%s: type %d msg %d cdb %x iptl: "
13974		       "%d:%d:%d:%d tag 0x%04x "
13975		       "flag %#x status %x\n",
13976			__func__,
13977			io->io_hdr.io_type,
13978			io->io_hdr.msg_type,
13979			io->scsiio.cdb[0],
13980			io->io_hdr.nexus.initid.id,
13981			io->io_hdr.nexus.targ_port,
13982			io->io_hdr.nexus.targ_target.id,
13983			io->io_hdr.nexus.targ_lun,
13984			(io->io_hdr.io_type ==
13985			CTL_IO_TASK) ?
13986			io->taskio.tag_num :
13987			io->scsiio.tag_num,
13988		        io->io_hdr.flags,
13989			io->io_hdr.status);
13990	} else
13991		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13992#endif
13993
13994	/*
13995	 * This is an internal copy of an I/O, and should not go through
13996	 * the normal done processing logic.
13997	 */
13998	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13999		return;
14000
14001	/*
14002	 * We need to send a msg to the serializing shelf to finish the IO
14003	 * as well.  We don't send a finish message to the other shelf if
14004	 * this is a task management command.  Task management commands
14005	 * aren't serialized in the OOA queue, but rather just executed on
14006	 * both shelf controllers for commands that originated on that
14007	 * controller.
14008	 */
14009	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14010	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14011		union ctl_ha_msg msg_io;
14012
14013		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14014		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14015		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14016		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14017		}
14018		/* continue on to finish IO */
14019	}
14020#ifdef CTL_IO_DELAY
14021	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14022		struct ctl_lun *lun;
14023
14024		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14025
14026		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14027	} else {
14028		struct ctl_lun *lun;
14029
14030		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14031
14032		if ((lun != NULL)
14033		 && (lun->delay_info.done_delay > 0)) {
14034			struct callout *callout;
14035
14036			callout = (struct callout *)&io->io_hdr.timer_bytes;
14037			callout_init(callout, /*mpsafe*/ 1);
14038			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14039			callout_reset(callout,
14040				      lun->delay_info.done_delay * hz,
14041				      ctl_done_timer_wakeup, io);
14042			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14043				lun->delay_info.done_delay = 0;
14044			return;
14045		}
14046	}
14047#endif /* CTL_IO_DELAY */
14048
14049	ctl_enqueue_done(io);
14050}
14051
14052int
14053ctl_isc(struct ctl_scsiio *ctsio)
14054{
14055	struct ctl_lun *lun;
14056	int retval;
14057
14058	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14059
14060	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14061
14062	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14063
14064	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14065
14066	return (retval);
14067}
14068
14069
14070static void
14071ctl_work_thread(void *arg)
14072{
14073	struct ctl_thread *thr = (struct ctl_thread *)arg;
14074	struct ctl_softc *softc = thr->ctl_softc;
14075	union ctl_io *io;
14076	int retval;
14077
14078	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14079
14080	for (;;) {
14081		retval = 0;
14082
14083		/*
14084		 * We handle the queues in this order:
14085		 * - ISC
14086		 * - done queue (to free up resources, unblock other commands)
14087		 * - RtR queue
14088		 * - incoming queue
14089		 *
14090		 * If those queues are empty, we break out of the loop and
14091		 * go to sleep.
14092		 */
14093		mtx_lock(&thr->queue_lock);
14094		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14095		if (io != NULL) {
14096			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14097			mtx_unlock(&thr->queue_lock);
14098			ctl_handle_isc(io);
14099			continue;
14100		}
14101		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14102		if (io != NULL) {
14103			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14104			/* clear any blocked commands, call fe_done */
14105			mtx_unlock(&thr->queue_lock);
14106			retval = ctl_process_done(io);
14107			continue;
14108		}
14109		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14110		if (io != NULL) {
14111			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14112			mtx_unlock(&thr->queue_lock);
14113			if (io->io_hdr.io_type == CTL_IO_TASK)
14114				ctl_run_task(io);
14115			else
14116				ctl_scsiio_precheck(softc, &io->scsiio);
14117			continue;
14118		}
14119		if (!ctl_pause_rtr) {
14120			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14121			if (io != NULL) {
14122				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14123				mtx_unlock(&thr->queue_lock);
14124				retval = ctl_scsiio(&io->scsiio);
14125				if (retval != CTL_RETVAL_COMPLETE)
14126					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14127				continue;
14128			}
14129		}
14130
14131		/* Sleep until we have something to do. */
14132		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14133	}
14134}
14135
14136static void
14137ctl_lun_thread(void *arg)
14138{
14139	struct ctl_softc *softc = (struct ctl_softc *)arg;
14140	struct ctl_be_lun *be_lun;
14141	int retval;
14142
14143	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14144
14145	for (;;) {
14146		retval = 0;
14147		mtx_lock(&softc->ctl_lock);
14148		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14149		if (be_lun != NULL) {
14150			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14151			mtx_unlock(&softc->ctl_lock);
14152			ctl_create_lun(be_lun);
14153			continue;
14154		}
14155
14156		/* Sleep until we have something to do. */
14157		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14158		    PDROP | PRIBIO, "-", 0);
14159	}
14160}
14161
14162static void
14163ctl_enqueue_incoming(union ctl_io *io)
14164{
14165	struct ctl_softc *softc = control_softc;
14166	struct ctl_thread *thr;
14167	u_int idx;
14168
14169	idx = (io->io_hdr.nexus.targ_port * 127 +
14170	       io->io_hdr.nexus.initid.id) % worker_threads;
14171	thr = &softc->threads[idx];
14172	mtx_lock(&thr->queue_lock);
14173	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14174	mtx_unlock(&thr->queue_lock);
14175	wakeup(thr);
14176}
14177
14178static void
14179ctl_enqueue_rtr(union ctl_io *io)
14180{
14181	struct ctl_softc *softc = control_softc;
14182	struct ctl_thread *thr;
14183
14184	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14185	mtx_lock(&thr->queue_lock);
14186	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14187	mtx_unlock(&thr->queue_lock);
14188	wakeup(thr);
14189}
14190
14191static void
14192ctl_enqueue_done(union ctl_io *io)
14193{
14194	struct ctl_softc *softc = control_softc;
14195	struct ctl_thread *thr;
14196
14197	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14198	mtx_lock(&thr->queue_lock);
14199	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14200	mtx_unlock(&thr->queue_lock);
14201	wakeup(thr);
14202}
14203
14204static void
14205ctl_enqueue_isc(union ctl_io *io)
14206{
14207	struct ctl_softc *softc = control_softc;
14208	struct ctl_thread *thr;
14209
14210	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14211	mtx_lock(&thr->queue_lock);
14212	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14213	mtx_unlock(&thr->queue_lock);
14214	wakeup(thr);
14215}
14216
14217/* Initialization and failover */
14218
14219void
14220ctl_init_isc_msg(void)
14221{
14222	printf("CTL: Still calling this thing\n");
14223}
14224
14225/*
14226 * Init component
14227 * 	Initializes component into configuration defined by bootMode
14228 *	(see hasc-sv.c)
14229 *  	returns hasc_Status:
14230 * 		OK
14231 *		ERROR - fatal error
14232 */
14233static ctl_ha_comp_status
14234ctl_isc_init(struct ctl_ha_component *c)
14235{
14236	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14237
14238	c->status = ret;
14239	return ret;
14240}
14241
14242/* Start component
14243 * 	Starts component in state requested. If component starts successfully,
14244 *	it must set its own state to the requestrd state
14245 *	When requested state is HASC_STATE_HA, the component may refine it
14246 * 	by adding _SLAVE or _MASTER flags.
14247 *	Currently allowed state transitions are:
14248 *	UNKNOWN->HA		- initial startup
14249 *	UNKNOWN->SINGLE - initial startup when no parter detected
14250 *	HA->SINGLE		- failover
14251 * returns ctl_ha_comp_status:
14252 * 		OK	- component successfully started in requested state
14253 *		FAILED  - could not start the requested state, failover may
14254 * 			  be possible
14255 *		ERROR	- fatal error detected, no future startup possible
14256 */
14257static ctl_ha_comp_status
14258ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14259{
14260	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14261
14262	printf("%s: go\n", __func__);
14263
14264	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14265	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14266		ctl_is_single = 0;
14267		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14268		    != CTL_HA_STATUS_SUCCESS) {
14269			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14270			ret = CTL_HA_COMP_STATUS_ERROR;
14271		}
14272	} else if (CTL_HA_STATE_IS_HA(c->state)
14273		&& CTL_HA_STATE_IS_SINGLE(state)){
14274		// HA->SINGLE transition
14275	        ctl_failover();
14276		ctl_is_single = 1;
14277	} else {
14278		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14279		       c->state, state);
14280		ret = CTL_HA_COMP_STATUS_ERROR;
14281	}
14282	if (CTL_HA_STATE_IS_SINGLE(state))
14283		ctl_is_single = 1;
14284
14285	c->state = state;
14286	c->status = ret;
14287	return ret;
14288}
14289
14290/*
14291 * Quiesce component
14292 * The component must clear any error conditions (set status to OK) and
14293 * prepare itself to another Start call
14294 * returns ctl_ha_comp_status:
14295 * 	OK
14296 *	ERROR
14297 */
14298static ctl_ha_comp_status
14299ctl_isc_quiesce(struct ctl_ha_component *c)
14300{
14301	int ret = CTL_HA_COMP_STATUS_OK;
14302
14303	ctl_pause_rtr = 1;
14304	c->status = ret;
14305	return ret;
14306}
14307
14308struct ctl_ha_component ctl_ha_component_ctlisc =
14309{
14310	.name = "CTL ISC",
14311	.state = CTL_HA_STATE_UNKNOWN,
14312	.init = ctl_isc_init,
14313	.start = ctl_isc_start,
14314	.quiesce = ctl_isc_quiesce
14315};
14316
14317/*
14318 *  vim: ts=8
14319 */
14320