ctl.c revision 272597
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 272597 2014-10-06 07:01:32Z 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*/0,
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->per_res[idx].registered == 0)
2994						continue;
2995					printf("  LUN %d port %d iid %d key "
2996					       "%#jx\n", i, j, k,
2997					       (uintmax_t)scsi_8btou64(
2998					       lun->per_res[idx].res_key.key));
2999				}
3000			}
3001		}
3002		printf("CTL Persistent Reservation information end\n");
3003		printf("CTL Ports:\n");
3004		STAILQ_FOREACH(port, &softc->port_list, links) {
3005			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3006			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3007			       port->frontend->name, port->port_type,
3008			       port->physical_port, port->virtual_port,
3009			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3010			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3011				if (port->wwpn_iid[j].in_use == 0 &&
3012				    port->wwpn_iid[j].wwpn == 0 &&
3013				    port->wwpn_iid[j].name == NULL)
3014					continue;
3015
3016				printf("    iid %u use %d WWPN %#jx '%s'\n",
3017				    j, port->wwpn_iid[j].in_use,
3018				    (uintmax_t)port->wwpn_iid[j].wwpn,
3019				    port->wwpn_iid[j].name);
3020			}
3021		}
3022		printf("CTL Port information end\n");
3023		mtx_unlock(&softc->ctl_lock);
3024		/*
3025		 * XXX KDM calling this without a lock.  We'd likely want
3026		 * to drop the lock before calling the frontend's dump
3027		 * routine anyway.
3028		 */
3029		printf("CTL Frontends:\n");
3030		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3031			printf("  Frontend '%s'\n", fe->name);
3032			if (fe->fe_dump != NULL)
3033				fe->fe_dump();
3034		}
3035		printf("CTL Frontend information end\n");
3036		break;
3037	}
3038	case CTL_LUN_REQ: {
3039		struct ctl_lun_req *lun_req;
3040		struct ctl_backend_driver *backend;
3041
3042		lun_req = (struct ctl_lun_req *)addr;
3043
3044		backend = ctl_backend_find(lun_req->backend);
3045		if (backend == NULL) {
3046			lun_req->status = CTL_LUN_ERROR;
3047			snprintf(lun_req->error_str,
3048				 sizeof(lun_req->error_str),
3049				 "Backend \"%s\" not found.",
3050				 lun_req->backend);
3051			break;
3052		}
3053		if (lun_req->num_be_args > 0) {
3054			lun_req->kern_be_args = ctl_copyin_args(
3055				lun_req->num_be_args,
3056				lun_req->be_args,
3057				lun_req->error_str,
3058				sizeof(lun_req->error_str));
3059			if (lun_req->kern_be_args == NULL) {
3060				lun_req->status = CTL_LUN_ERROR;
3061				break;
3062			}
3063		}
3064
3065		retval = backend->ioctl(dev, cmd, addr, flag, td);
3066
3067		if (lun_req->num_be_args > 0) {
3068			ctl_copyout_args(lun_req->num_be_args,
3069				      lun_req->kern_be_args);
3070			ctl_free_args(lun_req->num_be_args,
3071				      lun_req->kern_be_args);
3072		}
3073		break;
3074	}
3075	case CTL_LUN_LIST: {
3076		struct sbuf *sb;
3077		struct ctl_lun *lun;
3078		struct ctl_lun_list *list;
3079		struct ctl_option *opt;
3080
3081		list = (struct ctl_lun_list *)addr;
3082
3083		/*
3084		 * Allocate a fixed length sbuf here, based on the length
3085		 * of the user's buffer.  We could allocate an auto-extending
3086		 * buffer, and then tell the user how much larger our
3087		 * amount of data is than his buffer, but that presents
3088		 * some problems:
3089		 *
3090		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3091		 *     we can't hold a lock while calling them with an
3092		 *     auto-extending buffer.
3093 		 *
3094		 * 2.  There is not currently a LUN reference counting
3095		 *     mechanism, outside of outstanding transactions on
3096		 *     the LUN's OOA queue.  So a LUN could go away on us
3097		 *     while we're getting the LUN number, backend-specific
3098		 *     information, etc.  Thus, given the way things
3099		 *     currently work, we need to hold the CTL lock while
3100		 *     grabbing LUN information.
3101		 *
3102		 * So, from the user's standpoint, the best thing to do is
3103		 * allocate what he thinks is a reasonable buffer length,
3104		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3105		 * double the buffer length and try again.  (And repeat
3106		 * that until he succeeds.)
3107		 */
3108		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3109		if (sb == NULL) {
3110			list->status = CTL_LUN_LIST_ERROR;
3111			snprintf(list->error_str, sizeof(list->error_str),
3112				 "Unable to allocate %d bytes for LUN list",
3113				 list->alloc_len);
3114			break;
3115		}
3116
3117		sbuf_printf(sb, "<ctllunlist>\n");
3118
3119		mtx_lock(&softc->ctl_lock);
3120		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3121			mtx_lock(&lun->lun_lock);
3122			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3123					     (uintmax_t)lun->lun);
3124
3125			/*
3126			 * Bail out as soon as we see that we've overfilled
3127			 * the buffer.
3128			 */
3129			if (retval != 0)
3130				break;
3131
3132			retval = sbuf_printf(sb, "\t<backend_type>%s"
3133					     "</backend_type>\n",
3134					     (lun->backend == NULL) ?  "none" :
3135					     lun->backend->name);
3136
3137			if (retval != 0)
3138				break;
3139
3140			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3141					     lun->be_lun->lun_type);
3142
3143			if (retval != 0)
3144				break;
3145
3146			if (lun->backend == NULL) {
3147				retval = sbuf_printf(sb, "</lun>\n");
3148				if (retval != 0)
3149					break;
3150				continue;
3151			}
3152
3153			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3154					     (lun->be_lun->maxlba > 0) ?
3155					     lun->be_lun->maxlba + 1 : 0);
3156
3157			if (retval != 0)
3158				break;
3159
3160			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3161					     lun->be_lun->blocksize);
3162
3163			if (retval != 0)
3164				break;
3165
3166			retval = sbuf_printf(sb, "\t<serial_number>");
3167
3168			if (retval != 0)
3169				break;
3170
3171			retval = ctl_sbuf_printf_esc(sb,
3172						     lun->be_lun->serial_num);
3173
3174			if (retval != 0)
3175				break;
3176
3177			retval = sbuf_printf(sb, "</serial_number>\n");
3178
3179			if (retval != 0)
3180				break;
3181
3182			retval = sbuf_printf(sb, "\t<device_id>");
3183
3184			if (retval != 0)
3185				break;
3186
3187			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3188
3189			if (retval != 0)
3190				break;
3191
3192			retval = sbuf_printf(sb, "</device_id>\n");
3193
3194			if (retval != 0)
3195				break;
3196
3197			if (lun->backend->lun_info != NULL) {
3198				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3199				if (retval != 0)
3200					break;
3201			}
3202			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3203				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3204				    opt->name, opt->value, opt->name);
3205				if (retval != 0)
3206					break;
3207			}
3208
3209			retval = sbuf_printf(sb, "</lun>\n");
3210
3211			if (retval != 0)
3212				break;
3213			mtx_unlock(&lun->lun_lock);
3214		}
3215		if (lun != NULL)
3216			mtx_unlock(&lun->lun_lock);
3217		mtx_unlock(&softc->ctl_lock);
3218
3219		if ((retval != 0)
3220		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3221			retval = 0;
3222			sbuf_delete(sb);
3223			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3224			snprintf(list->error_str, sizeof(list->error_str),
3225				 "Out of space, %d bytes is too small",
3226				 list->alloc_len);
3227			break;
3228		}
3229
3230		sbuf_finish(sb);
3231
3232		retval = copyout(sbuf_data(sb), list->lun_xml,
3233				 sbuf_len(sb) + 1);
3234
3235		list->fill_len = sbuf_len(sb) + 1;
3236		list->status = CTL_LUN_LIST_OK;
3237		sbuf_delete(sb);
3238		break;
3239	}
3240	case CTL_ISCSI: {
3241		struct ctl_iscsi *ci;
3242		struct ctl_frontend *fe;
3243
3244		ci = (struct ctl_iscsi *)addr;
3245
3246		fe = ctl_frontend_find("iscsi");
3247		if (fe == NULL) {
3248			ci->status = CTL_ISCSI_ERROR;
3249			snprintf(ci->error_str, sizeof(ci->error_str),
3250			    "Frontend \"iscsi\" not found.");
3251			break;
3252		}
3253
3254		retval = fe->ioctl(dev, cmd, addr, flag, td);
3255		break;
3256	}
3257	case CTL_PORT_REQ: {
3258		struct ctl_req *req;
3259		struct ctl_frontend *fe;
3260
3261		req = (struct ctl_req *)addr;
3262
3263		fe = ctl_frontend_find(req->driver);
3264		if (fe == NULL) {
3265			req->status = CTL_LUN_ERROR;
3266			snprintf(req->error_str, sizeof(req->error_str),
3267			    "Frontend \"%s\" not found.", req->driver);
3268			break;
3269		}
3270		if (req->num_args > 0) {
3271			req->kern_args = ctl_copyin_args(req->num_args,
3272			    req->args, req->error_str, sizeof(req->error_str));
3273			if (req->kern_args == NULL) {
3274				req->status = CTL_LUN_ERROR;
3275				break;
3276			}
3277		}
3278
3279		retval = fe->ioctl(dev, cmd, addr, flag, td);
3280
3281		if (req->num_args > 0) {
3282			ctl_copyout_args(req->num_args, req->kern_args);
3283			ctl_free_args(req->num_args, req->kern_args);
3284		}
3285		break;
3286	}
3287	case CTL_PORT_LIST: {
3288		struct sbuf *sb;
3289		struct ctl_port *port;
3290		struct ctl_lun_list *list;
3291		struct ctl_option *opt;
3292
3293		list = (struct ctl_lun_list *)addr;
3294
3295		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3296		if (sb == NULL) {
3297			list->status = CTL_LUN_LIST_ERROR;
3298			snprintf(list->error_str, sizeof(list->error_str),
3299				 "Unable to allocate %d bytes for LUN list",
3300				 list->alloc_len);
3301			break;
3302		}
3303
3304		sbuf_printf(sb, "<ctlportlist>\n");
3305
3306		mtx_lock(&softc->ctl_lock);
3307		STAILQ_FOREACH(port, &softc->port_list, links) {
3308			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3309					     (uintmax_t)port->targ_port);
3310
3311			/*
3312			 * Bail out as soon as we see that we've overfilled
3313			 * the buffer.
3314			 */
3315			if (retval != 0)
3316				break;
3317
3318			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3319			    "</frontend_type>\n", port->frontend->name);
3320			if (retval != 0)
3321				break;
3322
3323			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3324					     port->port_type);
3325			if (retval != 0)
3326				break;
3327
3328			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3329			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3330			if (retval != 0)
3331				break;
3332
3333			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3334			    port->port_name);
3335			if (retval != 0)
3336				break;
3337
3338			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3339			    port->physical_port);
3340			if (retval != 0)
3341				break;
3342
3343			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3344			    port->virtual_port);
3345			if (retval != 0)
3346				break;
3347
3348			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3349			    (uintmax_t)port->wwnn);
3350			if (retval != 0)
3351				break;
3352
3353			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3354			    (uintmax_t)port->wwpn);
3355			if (retval != 0)
3356				break;
3357
3358			if (port->port_info != NULL) {
3359				retval = port->port_info(port->onoff_arg, sb);
3360				if (retval != 0)
3361					break;
3362			}
3363			STAILQ_FOREACH(opt, &port->options, links) {
3364				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3365				    opt->name, opt->value, opt->name);
3366				if (retval != 0)
3367					break;
3368			}
3369
3370			retval = sbuf_printf(sb, "</targ_port>\n");
3371			if (retval != 0)
3372				break;
3373		}
3374		mtx_unlock(&softc->ctl_lock);
3375
3376		if ((retval != 0)
3377		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3378			retval = 0;
3379			sbuf_delete(sb);
3380			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3381			snprintf(list->error_str, sizeof(list->error_str),
3382				 "Out of space, %d bytes is too small",
3383				 list->alloc_len);
3384			break;
3385		}
3386
3387		sbuf_finish(sb);
3388
3389		retval = copyout(sbuf_data(sb), list->lun_xml,
3390				 sbuf_len(sb) + 1);
3391
3392		list->fill_len = sbuf_len(sb) + 1;
3393		list->status = CTL_LUN_LIST_OK;
3394		sbuf_delete(sb);
3395		break;
3396	}
3397	default: {
3398		/* XXX KDM should we fix this? */
3399#if 0
3400		struct ctl_backend_driver *backend;
3401		unsigned int type;
3402		int found;
3403
3404		found = 0;
3405
3406		/*
3407		 * We encode the backend type as the ioctl type for backend
3408		 * ioctls.  So parse it out here, and then search for a
3409		 * backend of this type.
3410		 */
3411		type = _IOC_TYPE(cmd);
3412
3413		STAILQ_FOREACH(backend, &softc->be_list, links) {
3414			if (backend->type == type) {
3415				found = 1;
3416				break;
3417			}
3418		}
3419		if (found == 0) {
3420			printf("ctl: unknown ioctl command %#lx or backend "
3421			       "%d\n", cmd, type);
3422			retval = EINVAL;
3423			break;
3424		}
3425		retval = backend->ioctl(dev, cmd, addr, flag, td);
3426#endif
3427		retval = ENOTTY;
3428		break;
3429	}
3430	}
3431	return (retval);
3432}
3433
3434uint32_t
3435ctl_get_initindex(struct ctl_nexus *nexus)
3436{
3437	if (nexus->targ_port < CTL_MAX_PORTS)
3438		return (nexus->initid.id +
3439			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3440	else
3441		return (nexus->initid.id +
3442		       ((nexus->targ_port - CTL_MAX_PORTS) *
3443			CTL_MAX_INIT_PER_PORT));
3444}
3445
3446uint32_t
3447ctl_get_resindex(struct ctl_nexus *nexus)
3448{
3449	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3450}
3451
3452uint32_t
3453ctl_port_idx(int port_num)
3454{
3455	if (port_num < CTL_MAX_PORTS)
3456		return(port_num);
3457	else
3458		return(port_num - CTL_MAX_PORTS);
3459}
3460
3461static uint32_t
3462ctl_map_lun(int port_num, uint32_t lun_id)
3463{
3464	struct ctl_port *port;
3465
3466	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3467	if (port == NULL)
3468		return (UINT32_MAX);
3469	if (port->lun_map == NULL)
3470		return (lun_id);
3471	return (port->lun_map(port->targ_lun_arg, lun_id));
3472}
3473
3474static uint32_t
3475ctl_map_lun_back(int port_num, uint32_t lun_id)
3476{
3477	struct ctl_port *port;
3478	uint32_t i;
3479
3480	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3481	if (port->lun_map == NULL)
3482		return (lun_id);
3483	for (i = 0; i < CTL_MAX_LUNS; i++) {
3484		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3485			return (i);
3486	}
3487	return (UINT32_MAX);
3488}
3489
3490/*
3491 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3492 * that are a power of 2.
3493 */
3494int
3495ctl_ffz(uint32_t *mask, uint32_t size)
3496{
3497	uint32_t num_chunks, num_pieces;
3498	int i, j;
3499
3500	num_chunks = (size >> 5);
3501	if (num_chunks == 0)
3502		num_chunks++;
3503	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3504
3505	for (i = 0; i < num_chunks; i++) {
3506		for (j = 0; j < num_pieces; j++) {
3507			if ((mask[i] & (1 << j)) == 0)
3508				return ((i << 5) + j);
3509		}
3510	}
3511
3512	return (-1);
3513}
3514
3515int
3516ctl_set_mask(uint32_t *mask, uint32_t bit)
3517{
3518	uint32_t chunk, piece;
3519
3520	chunk = bit >> 5;
3521	piece = bit % (sizeof(uint32_t) * 8);
3522
3523	if ((mask[chunk] & (1 << piece)) != 0)
3524		return (-1);
3525	else
3526		mask[chunk] |= (1 << piece);
3527
3528	return (0);
3529}
3530
3531int
3532ctl_clear_mask(uint32_t *mask, uint32_t bit)
3533{
3534	uint32_t chunk, piece;
3535
3536	chunk = bit >> 5;
3537	piece = bit % (sizeof(uint32_t) * 8);
3538
3539	if ((mask[chunk] & (1 << piece)) == 0)
3540		return (-1);
3541	else
3542		mask[chunk] &= ~(1 << piece);
3543
3544	return (0);
3545}
3546
3547int
3548ctl_is_set(uint32_t *mask, uint32_t bit)
3549{
3550	uint32_t chunk, piece;
3551
3552	chunk = bit >> 5;
3553	piece = bit % (sizeof(uint32_t) * 8);
3554
3555	if ((mask[chunk] & (1 << piece)) == 0)
3556		return (0);
3557	else
3558		return (1);
3559}
3560
3561#ifdef unused
3562/*
3563 * The bus, target and lun are optional, they can be filled in later.
3564 * can_wait is used to determine whether we can wait on the malloc or not.
3565 */
3566union ctl_io*
3567ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3568	      uint32_t targ_lun, int can_wait)
3569{
3570	union ctl_io *io;
3571
3572	if (can_wait)
3573		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3574	else
3575		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3576
3577	if (io != NULL) {
3578		io->io_hdr.io_type = io_type;
3579		io->io_hdr.targ_port = targ_port;
3580		/*
3581		 * XXX KDM this needs to change/go away.  We need to move
3582		 * to a preallocated pool of ctl_scsiio structures.
3583		 */
3584		io->io_hdr.nexus.targ_target.id = targ_target;
3585		io->io_hdr.nexus.targ_lun = targ_lun;
3586	}
3587
3588	return (io);
3589}
3590
3591void
3592ctl_kfree_io(union ctl_io *io)
3593{
3594	free(io, M_CTL);
3595}
3596#endif /* unused */
3597
3598/*
3599 * ctl_softc, pool_type, total_ctl_io are passed in.
3600 * npool is passed out.
3601 */
3602int
3603ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3604		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3605{
3606	uint32_t i;
3607	union ctl_io *cur_io, *next_io;
3608	struct ctl_io_pool *pool;
3609	int retval;
3610
3611	retval = 0;
3612
3613	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3614					    M_NOWAIT | M_ZERO);
3615	if (pool == NULL) {
3616		retval = ENOMEM;
3617		goto bailout;
3618	}
3619
3620	pool->type = pool_type;
3621	pool->ctl_softc = ctl_softc;
3622
3623	mtx_lock(&ctl_softc->pool_lock);
3624	pool->id = ctl_softc->cur_pool_id++;
3625	mtx_unlock(&ctl_softc->pool_lock);
3626
3627	pool->flags = CTL_POOL_FLAG_NONE;
3628	pool->refcount = 1;		/* Reference for validity. */
3629	STAILQ_INIT(&pool->free_queue);
3630
3631	/*
3632	 * XXX KDM other options here:
3633	 * - allocate a page at a time
3634	 * - allocate one big chunk of memory.
3635	 * Page allocation might work well, but would take a little more
3636	 * tracking.
3637	 */
3638	for (i = 0; i < total_ctl_io; i++) {
3639		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3640						M_NOWAIT);
3641		if (cur_io == NULL) {
3642			retval = ENOMEM;
3643			break;
3644		}
3645		cur_io->io_hdr.pool = pool;
3646		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3647		pool->total_ctl_io++;
3648		pool->free_ctl_io++;
3649	}
3650
3651	if (retval != 0) {
3652		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3653		     cur_io != NULL; cur_io = next_io) {
3654			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3655							      links);
3656			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3657				      ctl_io_hdr, links);
3658			free(cur_io, M_CTLIO);
3659		}
3660
3661		free(pool, M_CTL);
3662		goto bailout;
3663	}
3664	mtx_lock(&ctl_softc->pool_lock);
3665	ctl_softc->num_pools++;
3666	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3667	/*
3668	 * Increment our usage count if this is an external consumer, so we
3669	 * can't get unloaded until the external consumer (most likely a
3670	 * FETD) unloads and frees his pool.
3671	 *
3672	 * XXX KDM will this increment the caller's module use count, or
3673	 * mine?
3674	 */
3675#if 0
3676	if ((pool_type != CTL_POOL_EMERGENCY)
3677	 && (pool_type != CTL_POOL_INTERNAL)
3678	 && (pool_type != CTL_POOL_4OTHERSC))
3679		MOD_INC_USE_COUNT;
3680#endif
3681
3682	mtx_unlock(&ctl_softc->pool_lock);
3683
3684	*npool = pool;
3685
3686bailout:
3687
3688	return (retval);
3689}
3690
3691static int
3692ctl_pool_acquire(struct ctl_io_pool *pool)
3693{
3694
3695	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3696
3697	if (pool->flags & CTL_POOL_FLAG_INVALID)
3698		return (EINVAL);
3699
3700	pool->refcount++;
3701
3702	return (0);
3703}
3704
3705static void
3706ctl_pool_release(struct ctl_io_pool *pool)
3707{
3708	struct ctl_softc *ctl_softc = pool->ctl_softc;
3709	union ctl_io *io;
3710
3711	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3712
3713	if (--pool->refcount != 0)
3714		return;
3715
3716	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3717		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3718			      links);
3719		free(io, M_CTLIO);
3720	}
3721
3722	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3723	ctl_softc->num_pools--;
3724
3725	/*
3726	 * XXX KDM will this decrement the caller's usage count or mine?
3727	 */
3728#if 0
3729	if ((pool->type != CTL_POOL_EMERGENCY)
3730	 && (pool->type != CTL_POOL_INTERNAL)
3731	 && (pool->type != CTL_POOL_4OTHERSC))
3732		MOD_DEC_USE_COUNT;
3733#endif
3734
3735	free(pool, M_CTL);
3736}
3737
3738void
3739ctl_pool_free(struct ctl_io_pool *pool)
3740{
3741	struct ctl_softc *ctl_softc;
3742
3743	if (pool == NULL)
3744		return;
3745
3746	ctl_softc = pool->ctl_softc;
3747	mtx_lock(&ctl_softc->pool_lock);
3748	pool->flags |= CTL_POOL_FLAG_INVALID;
3749	ctl_pool_release(pool);
3750	mtx_unlock(&ctl_softc->pool_lock);
3751}
3752
3753/*
3754 * This routine does not block (except for spinlocks of course).
3755 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3756 * possible.
3757 */
3758union ctl_io *
3759ctl_alloc_io(void *pool_ref)
3760{
3761	union ctl_io *io;
3762	struct ctl_softc *ctl_softc;
3763	struct ctl_io_pool *pool, *npool;
3764	struct ctl_io_pool *emergency_pool;
3765
3766	pool = (struct ctl_io_pool *)pool_ref;
3767
3768	if (pool == NULL) {
3769		printf("%s: pool is NULL\n", __func__);
3770		return (NULL);
3771	}
3772
3773	emergency_pool = NULL;
3774
3775	ctl_softc = pool->ctl_softc;
3776
3777	mtx_lock(&ctl_softc->pool_lock);
3778	/*
3779	 * First, try to get the io structure from the user's pool.
3780	 */
3781	if (ctl_pool_acquire(pool) == 0) {
3782		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3783		if (io != NULL) {
3784			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3785			pool->total_allocated++;
3786			pool->free_ctl_io--;
3787			mtx_unlock(&ctl_softc->pool_lock);
3788			return (io);
3789		} else
3790			ctl_pool_release(pool);
3791	}
3792	/*
3793	 * If he doesn't have any io structures left, search for an
3794	 * emergency pool and grab one from there.
3795	 */
3796	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3797		if (npool->type != CTL_POOL_EMERGENCY)
3798			continue;
3799
3800		if (ctl_pool_acquire(npool) != 0)
3801			continue;
3802
3803		emergency_pool = npool;
3804
3805		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3806		if (io != NULL) {
3807			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3808			npool->total_allocated++;
3809			npool->free_ctl_io--;
3810			mtx_unlock(&ctl_softc->pool_lock);
3811			return (io);
3812		} else
3813			ctl_pool_release(npool);
3814	}
3815
3816	/* Drop the spinlock before we malloc */
3817	mtx_unlock(&ctl_softc->pool_lock);
3818
3819	/*
3820	 * The emergency pool (if it exists) didn't have one, so try an
3821	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3822	 */
3823	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3824	if (io != NULL) {
3825		/*
3826		 * If the emergency pool exists but is empty, add this
3827		 * ctl_io to its list when it gets freed.
3828		 */
3829		if (emergency_pool != NULL) {
3830			mtx_lock(&ctl_softc->pool_lock);
3831			if (ctl_pool_acquire(emergency_pool) == 0) {
3832				io->io_hdr.pool = emergency_pool;
3833				emergency_pool->total_ctl_io++;
3834				/*
3835				 * Need to bump this, otherwise
3836				 * total_allocated and total_freed won't
3837				 * match when we no longer have anything
3838				 * outstanding.
3839				 */
3840				emergency_pool->total_allocated++;
3841			}
3842			mtx_unlock(&ctl_softc->pool_lock);
3843		} else
3844			io->io_hdr.pool = NULL;
3845	}
3846
3847	return (io);
3848}
3849
3850void
3851ctl_free_io(union ctl_io *io)
3852{
3853	if (io == NULL)
3854		return;
3855
3856	/*
3857	 * If this ctl_io has a pool, return it to that pool.
3858	 */
3859	if (io->io_hdr.pool != NULL) {
3860		struct ctl_io_pool *pool;
3861
3862		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3863		mtx_lock(&pool->ctl_softc->pool_lock);
3864		io->io_hdr.io_type = 0xff;
3865		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3866		pool->total_freed++;
3867		pool->free_ctl_io++;
3868		ctl_pool_release(pool);
3869		mtx_unlock(&pool->ctl_softc->pool_lock);
3870	} else {
3871		/*
3872		 * Otherwise, just free it.  We probably malloced it and
3873		 * the emergency pool wasn't available.
3874		 */
3875		free(io, M_CTLIO);
3876	}
3877
3878}
3879
3880void
3881ctl_zero_io(union ctl_io *io)
3882{
3883	void *pool_ref;
3884
3885	if (io == NULL)
3886		return;
3887
3888	/*
3889	 * May need to preserve linked list pointers at some point too.
3890	 */
3891	pool_ref = io->io_hdr.pool;
3892
3893	memset(io, 0, sizeof(*io));
3894
3895	io->io_hdr.pool = pool_ref;
3896}
3897
3898/*
3899 * This routine is currently used for internal copies of ctl_ios that need
3900 * to persist for some reason after we've already returned status to the
3901 * FETD.  (Thus the flag set.)
3902 *
3903 * XXX XXX
3904 * Note that this makes a blind copy of all fields in the ctl_io, except
3905 * for the pool reference.  This includes any memory that has been
3906 * allocated!  That memory will no longer be valid after done has been
3907 * called, so this would be VERY DANGEROUS for command that actually does
3908 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3909 * start and stop commands, which don't transfer any data, so this is not a
3910 * problem.  If it is used for anything else, the caller would also need to
3911 * allocate data buffer space and this routine would need to be modified to
3912 * copy the data buffer(s) as well.
3913 */
3914void
3915ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3916{
3917	void *pool_ref;
3918
3919	if ((src == NULL)
3920	 || (dest == NULL))
3921		return;
3922
3923	/*
3924	 * May need to preserve linked list pointers at some point too.
3925	 */
3926	pool_ref = dest->io_hdr.pool;
3927
3928	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3929
3930	dest->io_hdr.pool = pool_ref;
3931	/*
3932	 * We need to know that this is an internal copy, and doesn't need
3933	 * to get passed back to the FETD that allocated it.
3934	 */
3935	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3936}
3937
3938#ifdef NEEDTOPORT
3939static void
3940ctl_update_power_subpage(struct copan_power_subpage *page)
3941{
3942	int num_luns, num_partitions, config_type;
3943	struct ctl_softc *softc;
3944	cs_BOOL_t aor_present, shelf_50pct_power;
3945	cs_raidset_personality_t rs_type;
3946	int max_active_luns;
3947
3948	softc = control_softc;
3949
3950	/* subtract out the processor LUN */
3951	num_luns = softc->num_luns - 1;
3952	/*
3953	 * Default to 7 LUNs active, which was the only number we allowed
3954	 * in the past.
3955	 */
3956	max_active_luns = 7;
3957
3958	num_partitions = config_GetRsPartitionInfo();
3959	config_type = config_GetConfigType();
3960	shelf_50pct_power = config_GetShelfPowerMode();
3961	aor_present = config_IsAorRsPresent();
3962
3963	rs_type = ddb_GetRsRaidType(1);
3964	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3965	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3966		EPRINT(0, "Unsupported RS type %d!", rs_type);
3967	}
3968
3969
3970	page->total_luns = num_luns;
3971
3972	switch (config_type) {
3973	case 40:
3974		/*
3975		 * In a 40 drive configuration, it doesn't matter what DC
3976		 * cards we have, whether we have AOR enabled or not,
3977		 * partitioning or not, or what type of RAIDset we have.
3978		 * In that scenario, we can power up every LUN we present
3979		 * to the user.
3980		 */
3981		max_active_luns = num_luns;
3982
3983		break;
3984	case 64:
3985		if (shelf_50pct_power == CS_FALSE) {
3986			/* 25% power */
3987			if (aor_present == CS_TRUE) {
3988				if (rs_type ==
3989				     CS_RAIDSET_PERSONALITY_RAID5) {
3990					max_active_luns = 7;
3991				} else if (rs_type ==
3992					 CS_RAIDSET_PERSONALITY_RAID1){
3993					max_active_luns = 14;
3994				} else {
3995					/* XXX KDM now what?? */
3996				}
3997			} else {
3998				if (rs_type ==
3999				     CS_RAIDSET_PERSONALITY_RAID5) {
4000					max_active_luns = 8;
4001				} else if (rs_type ==
4002					 CS_RAIDSET_PERSONALITY_RAID1){
4003					max_active_luns = 16;
4004				} else {
4005					/* XXX KDM now what?? */
4006				}
4007			}
4008		} else {
4009			/* 50% power */
4010			/*
4011			 * With 50% power in a 64 drive configuration, we
4012			 * can power all LUNs we present.
4013			 */
4014			max_active_luns = num_luns;
4015		}
4016		break;
4017	case 112:
4018		if (shelf_50pct_power == CS_FALSE) {
4019			/* 25% power */
4020			if (aor_present == CS_TRUE) {
4021				if (rs_type ==
4022				     CS_RAIDSET_PERSONALITY_RAID5) {
4023					max_active_luns = 7;
4024				} else if (rs_type ==
4025					 CS_RAIDSET_PERSONALITY_RAID1){
4026					max_active_luns = 14;
4027				} else {
4028					/* XXX KDM now what?? */
4029				}
4030			} else {
4031				if (rs_type ==
4032				     CS_RAIDSET_PERSONALITY_RAID5) {
4033					max_active_luns = 8;
4034				} else if (rs_type ==
4035					 CS_RAIDSET_PERSONALITY_RAID1){
4036					max_active_luns = 16;
4037				} else {
4038					/* XXX KDM now what?? */
4039				}
4040			}
4041		} else {
4042			/* 50% power */
4043			if (aor_present == CS_TRUE) {
4044				if (rs_type ==
4045				     CS_RAIDSET_PERSONALITY_RAID5) {
4046					max_active_luns = 14;
4047				} else if (rs_type ==
4048					 CS_RAIDSET_PERSONALITY_RAID1){
4049					/*
4050					 * We're assuming here that disk
4051					 * caching is enabled, and so we're
4052					 * able to power up half of each
4053					 * LUN, and cache all writes.
4054					 */
4055					max_active_luns = num_luns;
4056				} else {
4057					/* XXX KDM now what?? */
4058				}
4059			} else {
4060				if (rs_type ==
4061				     CS_RAIDSET_PERSONALITY_RAID5) {
4062					max_active_luns = 15;
4063				} else if (rs_type ==
4064					 CS_RAIDSET_PERSONALITY_RAID1){
4065					max_active_luns = 30;
4066				} else {
4067					/* XXX KDM now what?? */
4068				}
4069			}
4070		}
4071		break;
4072	default:
4073		/*
4074		 * In this case, we have an unknown configuration, so we
4075		 * just use the default from above.
4076		 */
4077		break;
4078	}
4079
4080	page->max_active_luns = max_active_luns;
4081#if 0
4082	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4083	       page->total_luns, page->max_active_luns);
4084#endif
4085}
4086#endif /* NEEDTOPORT */
4087
4088/*
4089 * This routine could be used in the future to load default and/or saved
4090 * mode page parameters for a particuar lun.
4091 */
4092static int
4093ctl_init_page_index(struct ctl_lun *lun)
4094{
4095	int i;
4096	struct ctl_page_index *page_index;
4097	struct ctl_softc *softc;
4098	const char *value;
4099
4100	memcpy(&lun->mode_pages.index, page_index_template,
4101	       sizeof(page_index_template));
4102
4103	softc = lun->ctl_softc;
4104
4105	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4106
4107		page_index = &lun->mode_pages.index[i];
4108		/*
4109		 * If this is a disk-only mode page, there's no point in
4110		 * setting it up.  For some pages, we have to have some
4111		 * basic information about the disk in order to calculate the
4112		 * mode page data.
4113		 */
4114		if ((lun->be_lun->lun_type != T_DIRECT)
4115		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4116			continue;
4117
4118		switch (page_index->page_code & SMPH_PC_MASK) {
4119		case SMS_FORMAT_DEVICE_PAGE: {
4120			struct scsi_format_page *format_page;
4121
4122			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4123				panic("subpage is incorrect!");
4124
4125			/*
4126			 * Sectors per track are set above.  Bytes per
4127			 * sector need to be set here on a per-LUN basis.
4128			 */
4129			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4130			       &format_page_default,
4131			       sizeof(format_page_default));
4132			memcpy(&lun->mode_pages.format_page[
4133			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4134			       sizeof(format_page_changeable));
4135			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4136			       &format_page_default,
4137			       sizeof(format_page_default));
4138			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4139			       &format_page_default,
4140			       sizeof(format_page_default));
4141
4142			format_page = &lun->mode_pages.format_page[
4143				CTL_PAGE_CURRENT];
4144			scsi_ulto2b(lun->be_lun->blocksize,
4145				    format_page->bytes_per_sector);
4146
4147			format_page = &lun->mode_pages.format_page[
4148				CTL_PAGE_DEFAULT];
4149			scsi_ulto2b(lun->be_lun->blocksize,
4150				    format_page->bytes_per_sector);
4151
4152			format_page = &lun->mode_pages.format_page[
4153				CTL_PAGE_SAVED];
4154			scsi_ulto2b(lun->be_lun->blocksize,
4155				    format_page->bytes_per_sector);
4156
4157			page_index->page_data =
4158				(uint8_t *)lun->mode_pages.format_page;
4159			break;
4160		}
4161		case SMS_RIGID_DISK_PAGE: {
4162			struct scsi_rigid_disk_page *rigid_disk_page;
4163			uint32_t sectors_per_cylinder;
4164			uint64_t cylinders;
4165#ifndef	__XSCALE__
4166			int shift;
4167#endif /* !__XSCALE__ */
4168
4169			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4170				panic("invalid subpage value %d",
4171				      page_index->subpage);
4172
4173			/*
4174			 * Rotation rate and sectors per track are set
4175			 * above.  We calculate the cylinders here based on
4176			 * capacity.  Due to the number of heads and
4177			 * sectors per track we're using, smaller arrays
4178			 * may turn out to have 0 cylinders.  Linux and
4179			 * FreeBSD don't pay attention to these mode pages
4180			 * to figure out capacity, but Solaris does.  It
4181			 * seems to deal with 0 cylinders just fine, and
4182			 * works out a fake geometry based on the capacity.
4183			 */
4184			memcpy(&lun->mode_pages.rigid_disk_page[
4185			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4186			       sizeof(rigid_disk_page_default));
4187			memcpy(&lun->mode_pages.rigid_disk_page[
4188			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4189			       sizeof(rigid_disk_page_changeable));
4190			memcpy(&lun->mode_pages.rigid_disk_page[
4191			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4192			       sizeof(rigid_disk_page_default));
4193			memcpy(&lun->mode_pages.rigid_disk_page[
4194			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4195			       sizeof(rigid_disk_page_default));
4196
4197			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4198				CTL_DEFAULT_HEADS;
4199
4200			/*
4201			 * The divide method here will be more accurate,
4202			 * probably, but results in floating point being
4203			 * used in the kernel on i386 (__udivdi3()).  On the
4204			 * XScale, though, __udivdi3() is implemented in
4205			 * software.
4206			 *
4207			 * The shift method for cylinder calculation is
4208			 * accurate if sectors_per_cylinder is a power of
4209			 * 2.  Otherwise it might be slightly off -- you
4210			 * might have a bit of a truncation problem.
4211			 */
4212#ifdef	__XSCALE__
4213			cylinders = (lun->be_lun->maxlba + 1) /
4214				sectors_per_cylinder;
4215#else
4216			for (shift = 31; shift > 0; shift--) {
4217				if (sectors_per_cylinder & (1 << shift))
4218					break;
4219			}
4220			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4221#endif
4222
4223			/*
4224			 * We've basically got 3 bytes, or 24 bits for the
4225			 * cylinder size in the mode page.  If we're over,
4226			 * just round down to 2^24.
4227			 */
4228			if (cylinders > 0xffffff)
4229				cylinders = 0xffffff;
4230
4231			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4232				CTL_PAGE_CURRENT];
4233			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4234
4235			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4236				CTL_PAGE_DEFAULT];
4237			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4238
4239			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4240				CTL_PAGE_SAVED];
4241			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4242
4243			page_index->page_data =
4244				(uint8_t *)lun->mode_pages.rigid_disk_page;
4245			break;
4246		}
4247		case SMS_CACHING_PAGE: {
4248			struct scsi_caching_page *caching_page;
4249
4250			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4251				panic("invalid subpage value %d",
4252				      page_index->subpage);
4253			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4254			       &caching_page_default,
4255			       sizeof(caching_page_default));
4256			memcpy(&lun->mode_pages.caching_page[
4257			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4258			       sizeof(caching_page_changeable));
4259			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4260			       &caching_page_default,
4261			       sizeof(caching_page_default));
4262			caching_page = &lun->mode_pages.caching_page[
4263			    CTL_PAGE_SAVED];
4264			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4265			if (value != NULL && strcmp(value, "off") == 0)
4266				caching_page->flags1 &= ~SCP_WCE;
4267			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4268			if (value != NULL && strcmp(value, "off") == 0)
4269				caching_page->flags1 |= SCP_RCD;
4270			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4271			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4272			       sizeof(caching_page_default));
4273			page_index->page_data =
4274				(uint8_t *)lun->mode_pages.caching_page;
4275			break;
4276		}
4277		case SMS_CONTROL_MODE_PAGE: {
4278			struct scsi_control_page *control_page;
4279
4280			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4281				panic("invalid subpage value %d",
4282				      page_index->subpage);
4283
4284			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4285			       &control_page_default,
4286			       sizeof(control_page_default));
4287			memcpy(&lun->mode_pages.control_page[
4288			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4289			       sizeof(control_page_changeable));
4290			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4291			       &control_page_default,
4292			       sizeof(control_page_default));
4293			control_page = &lun->mode_pages.control_page[
4294			    CTL_PAGE_SAVED];
4295			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4296			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4297				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4298				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4299			}
4300			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4301			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4302			       sizeof(control_page_default));
4303			page_index->page_data =
4304				(uint8_t *)lun->mode_pages.control_page;
4305			break;
4306
4307		}
4308		case SMS_VENDOR_SPECIFIC_PAGE:{
4309			switch (page_index->subpage) {
4310			case PWR_SUBPAGE_CODE: {
4311				struct copan_power_subpage *current_page,
4312							   *saved_page;
4313
4314				memcpy(&lun->mode_pages.power_subpage[
4315				       CTL_PAGE_CURRENT],
4316				       &power_page_default,
4317				       sizeof(power_page_default));
4318				memcpy(&lun->mode_pages.power_subpage[
4319				       CTL_PAGE_CHANGEABLE],
4320				       &power_page_changeable,
4321				       sizeof(power_page_changeable));
4322				memcpy(&lun->mode_pages.power_subpage[
4323				       CTL_PAGE_DEFAULT],
4324				       &power_page_default,
4325				       sizeof(power_page_default));
4326				memcpy(&lun->mode_pages.power_subpage[
4327				       CTL_PAGE_SAVED],
4328				       &power_page_default,
4329				       sizeof(power_page_default));
4330				page_index->page_data =
4331				    (uint8_t *)lun->mode_pages.power_subpage;
4332
4333				current_page = (struct copan_power_subpage *)
4334					(page_index->page_data +
4335					 (page_index->page_len *
4336					  CTL_PAGE_CURRENT));
4337			        saved_page = (struct copan_power_subpage *)
4338				        (page_index->page_data +
4339					 (page_index->page_len *
4340					  CTL_PAGE_SAVED));
4341				break;
4342			}
4343			case APS_SUBPAGE_CODE: {
4344				struct copan_aps_subpage *current_page,
4345							 *saved_page;
4346
4347				// This gets set multiple times but
4348				// it should always be the same. It's
4349				// only done during init so who cares.
4350				index_to_aps_page = i;
4351
4352				memcpy(&lun->mode_pages.aps_subpage[
4353				       CTL_PAGE_CURRENT],
4354				       &aps_page_default,
4355				       sizeof(aps_page_default));
4356				memcpy(&lun->mode_pages.aps_subpage[
4357				       CTL_PAGE_CHANGEABLE],
4358				       &aps_page_changeable,
4359				       sizeof(aps_page_changeable));
4360				memcpy(&lun->mode_pages.aps_subpage[
4361				       CTL_PAGE_DEFAULT],
4362				       &aps_page_default,
4363				       sizeof(aps_page_default));
4364				memcpy(&lun->mode_pages.aps_subpage[
4365				       CTL_PAGE_SAVED],
4366				       &aps_page_default,
4367				       sizeof(aps_page_default));
4368				page_index->page_data =
4369					(uint8_t *)lun->mode_pages.aps_subpage;
4370
4371				current_page = (struct copan_aps_subpage *)
4372					(page_index->page_data +
4373					 (page_index->page_len *
4374					  CTL_PAGE_CURRENT));
4375				saved_page = (struct copan_aps_subpage *)
4376					(page_index->page_data +
4377					 (page_index->page_len *
4378					  CTL_PAGE_SAVED));
4379				break;
4380			}
4381			case DBGCNF_SUBPAGE_CODE: {
4382				struct copan_debugconf_subpage *current_page,
4383							       *saved_page;
4384
4385				memcpy(&lun->mode_pages.debugconf_subpage[
4386				       CTL_PAGE_CURRENT],
4387				       &debugconf_page_default,
4388				       sizeof(debugconf_page_default));
4389				memcpy(&lun->mode_pages.debugconf_subpage[
4390				       CTL_PAGE_CHANGEABLE],
4391				       &debugconf_page_changeable,
4392				       sizeof(debugconf_page_changeable));
4393				memcpy(&lun->mode_pages.debugconf_subpage[
4394				       CTL_PAGE_DEFAULT],
4395				       &debugconf_page_default,
4396				       sizeof(debugconf_page_default));
4397				memcpy(&lun->mode_pages.debugconf_subpage[
4398				       CTL_PAGE_SAVED],
4399				       &debugconf_page_default,
4400				       sizeof(debugconf_page_default));
4401				page_index->page_data =
4402					(uint8_t *)lun->mode_pages.debugconf_subpage;
4403
4404				current_page = (struct copan_debugconf_subpage *)
4405					(page_index->page_data +
4406					 (page_index->page_len *
4407					  CTL_PAGE_CURRENT));
4408				saved_page = (struct copan_debugconf_subpage *)
4409					(page_index->page_data +
4410					 (page_index->page_len *
4411					  CTL_PAGE_SAVED));
4412				break;
4413			}
4414			default:
4415				panic("invalid subpage value %d",
4416				      page_index->subpage);
4417				break;
4418			}
4419   			break;
4420		}
4421		default:
4422			panic("invalid page value %d",
4423			      page_index->page_code & SMPH_PC_MASK);
4424			break;
4425    	}
4426	}
4427
4428	return (CTL_RETVAL_COMPLETE);
4429}
4430
4431/*
4432 * LUN allocation.
4433 *
4434 * Requirements:
4435 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4436 *   wants us to allocate the LUN and he can block.
4437 * - ctl_softc is always set
4438 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4439 *
4440 * Returns 0 for success, non-zero (errno) for failure.
4441 */
4442static int
4443ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4444	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4445{
4446	struct ctl_lun *nlun, *lun;
4447	struct ctl_port *port;
4448	struct scsi_vpd_id_descriptor *desc;
4449	struct scsi_vpd_id_t10 *t10id;
4450	const char *eui, *naa, *scsiname, *vendor;
4451	int lun_number, i, lun_malloced;
4452	int devidlen, idlen1, idlen2 = 0, len;
4453
4454	if (be_lun == NULL)
4455		return (EINVAL);
4456
4457	/*
4458	 * We currently only support Direct Access or Processor LUN types.
4459	 */
4460	switch (be_lun->lun_type) {
4461	case T_DIRECT:
4462		break;
4463	case T_PROCESSOR:
4464		break;
4465	case T_SEQUENTIAL:
4466	case T_CHANGER:
4467	default:
4468		be_lun->lun_config_status(be_lun->be_lun,
4469					  CTL_LUN_CONFIG_FAILURE);
4470		break;
4471	}
4472	if (ctl_lun == NULL) {
4473		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4474		lun_malloced = 1;
4475	} else {
4476		lun_malloced = 0;
4477		lun = ctl_lun;
4478	}
4479
4480	memset(lun, 0, sizeof(*lun));
4481	if (lun_malloced)
4482		lun->flags = CTL_LUN_MALLOCED;
4483
4484	/* Generate LUN ID. */
4485	devidlen = max(CTL_DEVID_MIN_LEN,
4486	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4487	idlen1 = sizeof(*t10id) + devidlen;
4488	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4489	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4490	if (scsiname != NULL) {
4491		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4492		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4493	}
4494	eui = ctl_get_opt(&be_lun->options, "eui");
4495	if (eui != NULL) {
4496		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4497	}
4498	naa = ctl_get_opt(&be_lun->options, "naa");
4499	if (naa != NULL) {
4500		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4501	}
4502	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4503	    M_CTL, M_WAITOK | M_ZERO);
4504	lun->lun_devid->len = len;
4505	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4506	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4507	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4508	desc->length = idlen1;
4509	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4510	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4511	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4512		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4513	} else {
4514		strncpy(t10id->vendor, vendor,
4515		    min(sizeof(t10id->vendor), strlen(vendor)));
4516	}
4517	strncpy((char *)t10id->vendor_spec_id,
4518	    (char *)be_lun->device_id, devidlen);
4519	if (scsiname != NULL) {
4520		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4521		    desc->length);
4522		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4523		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4524		    SVPD_ID_TYPE_SCSI_NAME;
4525		desc->length = idlen2;
4526		strlcpy(desc->identifier, scsiname, idlen2);
4527	}
4528	if (eui != NULL) {
4529		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4530		    desc->length);
4531		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4532		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4533		    SVPD_ID_TYPE_EUI64;
4534		desc->length = 8;
4535		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4536	}
4537	if (naa != NULL) {
4538		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4539		    desc->length);
4540		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4541		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4542		    SVPD_ID_TYPE_NAA;
4543		desc->length = 8;
4544		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4545	}
4546
4547	mtx_lock(&ctl_softc->ctl_lock);
4548	/*
4549	 * See if the caller requested a particular LUN number.  If so, see
4550	 * if it is available.  Otherwise, allocate the first available LUN.
4551	 */
4552	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4553		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4554		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4555			mtx_unlock(&ctl_softc->ctl_lock);
4556			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4557				printf("ctl: requested LUN ID %d is higher "
4558				       "than CTL_MAX_LUNS - 1 (%d)\n",
4559				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4560			} else {
4561				/*
4562				 * XXX KDM return an error, or just assign
4563				 * another LUN ID in this case??
4564				 */
4565				printf("ctl: requested LUN ID %d is already "
4566				       "in use\n", be_lun->req_lun_id);
4567			}
4568			if (lun->flags & CTL_LUN_MALLOCED)
4569				free(lun, M_CTL);
4570			be_lun->lun_config_status(be_lun->be_lun,
4571						  CTL_LUN_CONFIG_FAILURE);
4572			return (ENOSPC);
4573		}
4574		lun_number = be_lun->req_lun_id;
4575	} else {
4576		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4577		if (lun_number == -1) {
4578			mtx_unlock(&ctl_softc->ctl_lock);
4579			printf("ctl: can't allocate LUN on target %ju, out of "
4580			       "LUNs\n", (uintmax_t)target_id.id);
4581			if (lun->flags & CTL_LUN_MALLOCED)
4582				free(lun, M_CTL);
4583			be_lun->lun_config_status(be_lun->be_lun,
4584						  CTL_LUN_CONFIG_FAILURE);
4585			return (ENOSPC);
4586		}
4587	}
4588	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4589
4590	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4591	lun->target = target_id;
4592	lun->lun = lun_number;
4593	lun->be_lun = be_lun;
4594	/*
4595	 * The processor LUN is always enabled.  Disk LUNs come on line
4596	 * disabled, and must be enabled by the backend.
4597	 */
4598	lun->flags |= CTL_LUN_DISABLED;
4599	lun->backend = be_lun->be;
4600	be_lun->ctl_lun = lun;
4601	be_lun->lun_id = lun_number;
4602	atomic_add_int(&be_lun->be->num_luns, 1);
4603	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4604		lun->flags |= CTL_LUN_STOPPED;
4605
4606	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4607		lun->flags |= CTL_LUN_INOPERABLE;
4608
4609	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4610		lun->flags |= CTL_LUN_PRIMARY_SC;
4611
4612	lun->ctl_softc = ctl_softc;
4613	TAILQ_INIT(&lun->ooa_queue);
4614	TAILQ_INIT(&lun->blocked_queue);
4615	STAILQ_INIT(&lun->error_list);
4616	ctl_tpc_lun_init(lun);
4617
4618	/*
4619	 * Initialize the mode page index.
4620	 */
4621	ctl_init_page_index(lun);
4622
4623	/*
4624	 * Set the poweron UA for all initiators on this LUN only.
4625	 */
4626	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4627		lun->pending_ua[i] = CTL_UA_POWERON;
4628
4629	/*
4630	 * Now, before we insert this lun on the lun list, set the lun
4631	 * inventory changed UA for all other luns.
4632	 */
4633	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4634		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4635			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4636		}
4637	}
4638
4639	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4640
4641	ctl_softc->ctl_luns[lun_number] = lun;
4642
4643	ctl_softc->num_luns++;
4644
4645	/* Setup statistics gathering */
4646	lun->stats.device_type = be_lun->lun_type;
4647	lun->stats.lun_number = lun_number;
4648	if (lun->stats.device_type == T_DIRECT)
4649		lun->stats.blocksize = be_lun->blocksize;
4650	else
4651		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4652	for (i = 0;i < CTL_MAX_PORTS;i++)
4653		lun->stats.ports[i].targ_port = i;
4654
4655	mtx_unlock(&ctl_softc->ctl_lock);
4656
4657	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4658
4659	/*
4660	 * Run through each registered FETD and bring it online if it isn't
4661	 * already.  Enable the target ID if it hasn't been enabled, and
4662	 * enable this particular LUN.
4663	 */
4664	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4665		int retval;
4666
4667		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4668		if (retval != 0) {
4669			printf("ctl_alloc_lun: FETD %s port %d returned error "
4670			       "%d for lun_enable on target %ju lun %d\n",
4671			       port->port_name, port->targ_port, retval,
4672			       (uintmax_t)target_id.id, lun_number);
4673		} else
4674			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4675	}
4676	return (0);
4677}
4678
4679/*
4680 * Delete a LUN.
4681 * Assumptions:
4682 * - LUN has already been marked invalid and any pending I/O has been taken
4683 *   care of.
4684 */
4685static int
4686ctl_free_lun(struct ctl_lun *lun)
4687{
4688	struct ctl_softc *softc;
4689#if 0
4690	struct ctl_port *port;
4691#endif
4692	struct ctl_lun *nlun;
4693	int i;
4694
4695	softc = lun->ctl_softc;
4696
4697	mtx_assert(&softc->ctl_lock, MA_OWNED);
4698
4699	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4700
4701	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4702
4703	softc->ctl_luns[lun->lun] = NULL;
4704
4705	if (!TAILQ_EMPTY(&lun->ooa_queue))
4706		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4707
4708	softc->num_luns--;
4709
4710	/*
4711	 * XXX KDM this scheme only works for a single target/multiple LUN
4712	 * setup.  It needs to be revamped for a multiple target scheme.
4713	 *
4714	 * XXX KDM this results in port->lun_disable() getting called twice,
4715	 * once when ctl_disable_lun() is called, and a second time here.
4716	 * We really need to re-think the LUN disable semantics.  There
4717	 * should probably be several steps/levels to LUN removal:
4718	 *  - disable
4719	 *  - invalidate
4720	 *  - free
4721 	 *
4722	 * Right now we only have a disable method when communicating to
4723	 * the front end ports, at least for individual LUNs.
4724	 */
4725#if 0
4726	STAILQ_FOREACH(port, &softc->port_list, links) {
4727		int retval;
4728
4729		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4730					 lun->lun);
4731		if (retval != 0) {
4732			printf("ctl_free_lun: FETD %s port %d returned error "
4733			       "%d for lun_disable on target %ju lun %jd\n",
4734			       port->port_name, port->targ_port, retval,
4735			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4736		}
4737
4738		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4739			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4740
4741			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4742			if (retval != 0) {
4743				printf("ctl_free_lun: FETD %s port %d "
4744				       "returned error %d for targ_disable on "
4745				       "target %ju\n", port->port_name,
4746				       port->targ_port, retval,
4747				       (uintmax_t)lun->target.id);
4748			} else
4749				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4750
4751			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4752				continue;
4753
4754#if 0
4755			port->port_offline(port->onoff_arg);
4756			port->status &= ~CTL_PORT_STATUS_ONLINE;
4757#endif
4758		}
4759	}
4760#endif
4761
4762	/*
4763	 * Tell the backend to free resources, if this LUN has a backend.
4764	 */
4765	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4766	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4767
4768	ctl_tpc_lun_shutdown(lun);
4769	mtx_destroy(&lun->lun_lock);
4770	free(lun->lun_devid, M_CTL);
4771	if (lun->flags & CTL_LUN_MALLOCED)
4772		free(lun, M_CTL);
4773
4774	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4775		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4776			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4777		}
4778	}
4779
4780	return (0);
4781}
4782
4783static void
4784ctl_create_lun(struct ctl_be_lun *be_lun)
4785{
4786	struct ctl_softc *ctl_softc;
4787
4788	ctl_softc = control_softc;
4789
4790	/*
4791	 * ctl_alloc_lun() should handle all potential failure cases.
4792	 */
4793	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4794}
4795
4796int
4797ctl_add_lun(struct ctl_be_lun *be_lun)
4798{
4799	struct ctl_softc *ctl_softc = control_softc;
4800
4801	mtx_lock(&ctl_softc->ctl_lock);
4802	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4803	mtx_unlock(&ctl_softc->ctl_lock);
4804	wakeup(&ctl_softc->pending_lun_queue);
4805
4806	return (0);
4807}
4808
4809int
4810ctl_enable_lun(struct ctl_be_lun *be_lun)
4811{
4812	struct ctl_softc *ctl_softc;
4813	struct ctl_port *port, *nport;
4814	struct ctl_lun *lun;
4815	int retval;
4816
4817	ctl_softc = control_softc;
4818
4819	lun = (struct ctl_lun *)be_lun->ctl_lun;
4820
4821	mtx_lock(&ctl_softc->ctl_lock);
4822	mtx_lock(&lun->lun_lock);
4823	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4824		/*
4825		 * eh?  Why did we get called if the LUN is already
4826		 * enabled?
4827		 */
4828		mtx_unlock(&lun->lun_lock);
4829		mtx_unlock(&ctl_softc->ctl_lock);
4830		return (0);
4831	}
4832	lun->flags &= ~CTL_LUN_DISABLED;
4833	mtx_unlock(&lun->lun_lock);
4834
4835	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4836		nport = STAILQ_NEXT(port, links);
4837
4838		/*
4839		 * Drop the lock while we call the FETD's enable routine.
4840		 * This can lead to a callback into CTL (at least in the
4841		 * case of the internal initiator frontend.
4842		 */
4843		mtx_unlock(&ctl_softc->ctl_lock);
4844		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4845		mtx_lock(&ctl_softc->ctl_lock);
4846		if (retval != 0) {
4847			printf("%s: FETD %s port %d returned error "
4848			       "%d for lun_enable on target %ju lun %jd\n",
4849			       __func__, port->port_name, port->targ_port, retval,
4850			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4851		}
4852#if 0
4853		 else {
4854            /* NOTE:  TODO:  why does lun enable affect port status? */
4855			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4856		}
4857#endif
4858	}
4859
4860	mtx_unlock(&ctl_softc->ctl_lock);
4861
4862	return (0);
4863}
4864
4865int
4866ctl_disable_lun(struct ctl_be_lun *be_lun)
4867{
4868	struct ctl_softc *ctl_softc;
4869	struct ctl_port *port;
4870	struct ctl_lun *lun;
4871	int retval;
4872
4873	ctl_softc = control_softc;
4874
4875	lun = (struct ctl_lun *)be_lun->ctl_lun;
4876
4877	mtx_lock(&ctl_softc->ctl_lock);
4878	mtx_lock(&lun->lun_lock);
4879	if (lun->flags & CTL_LUN_DISABLED) {
4880		mtx_unlock(&lun->lun_lock);
4881		mtx_unlock(&ctl_softc->ctl_lock);
4882		return (0);
4883	}
4884	lun->flags |= CTL_LUN_DISABLED;
4885	mtx_unlock(&lun->lun_lock);
4886
4887	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4888		mtx_unlock(&ctl_softc->ctl_lock);
4889		/*
4890		 * Drop the lock before we call the frontend's disable
4891		 * routine, to avoid lock order reversals.
4892		 *
4893		 * XXX KDM what happens if the frontend list changes while
4894		 * we're traversing it?  It's unlikely, but should be handled.
4895		 */
4896		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4897					 lun->lun);
4898		mtx_lock(&ctl_softc->ctl_lock);
4899		if (retval != 0) {
4900			printf("ctl_alloc_lun: FETD %s port %d returned error "
4901			       "%d for lun_disable on target %ju lun %jd\n",
4902			       port->port_name, port->targ_port, retval,
4903			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4904		}
4905	}
4906
4907	mtx_unlock(&ctl_softc->ctl_lock);
4908
4909	return (0);
4910}
4911
4912int
4913ctl_start_lun(struct ctl_be_lun *be_lun)
4914{
4915	struct ctl_softc *ctl_softc;
4916	struct ctl_lun *lun;
4917
4918	ctl_softc = control_softc;
4919
4920	lun = (struct ctl_lun *)be_lun->ctl_lun;
4921
4922	mtx_lock(&lun->lun_lock);
4923	lun->flags &= ~CTL_LUN_STOPPED;
4924	mtx_unlock(&lun->lun_lock);
4925
4926	return (0);
4927}
4928
4929int
4930ctl_stop_lun(struct ctl_be_lun *be_lun)
4931{
4932	struct ctl_softc *ctl_softc;
4933	struct ctl_lun *lun;
4934
4935	ctl_softc = control_softc;
4936
4937	lun = (struct ctl_lun *)be_lun->ctl_lun;
4938
4939	mtx_lock(&lun->lun_lock);
4940	lun->flags |= CTL_LUN_STOPPED;
4941	mtx_unlock(&lun->lun_lock);
4942
4943	return (0);
4944}
4945
4946int
4947ctl_lun_offline(struct ctl_be_lun *be_lun)
4948{
4949	struct ctl_softc *ctl_softc;
4950	struct ctl_lun *lun;
4951
4952	ctl_softc = control_softc;
4953
4954	lun = (struct ctl_lun *)be_lun->ctl_lun;
4955
4956	mtx_lock(&lun->lun_lock);
4957	lun->flags |= CTL_LUN_OFFLINE;
4958	mtx_unlock(&lun->lun_lock);
4959
4960	return (0);
4961}
4962
4963int
4964ctl_lun_online(struct ctl_be_lun *be_lun)
4965{
4966	struct ctl_softc *ctl_softc;
4967	struct ctl_lun *lun;
4968
4969	ctl_softc = control_softc;
4970
4971	lun = (struct ctl_lun *)be_lun->ctl_lun;
4972
4973	mtx_lock(&lun->lun_lock);
4974	lun->flags &= ~CTL_LUN_OFFLINE;
4975	mtx_unlock(&lun->lun_lock);
4976
4977	return (0);
4978}
4979
4980int
4981ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4982{
4983	struct ctl_softc *ctl_softc;
4984	struct ctl_lun *lun;
4985
4986	ctl_softc = control_softc;
4987
4988	lun = (struct ctl_lun *)be_lun->ctl_lun;
4989
4990	mtx_lock(&lun->lun_lock);
4991
4992	/*
4993	 * The LUN needs to be disabled before it can be marked invalid.
4994	 */
4995	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4996		mtx_unlock(&lun->lun_lock);
4997		return (-1);
4998	}
4999	/*
5000	 * Mark the LUN invalid.
5001	 */
5002	lun->flags |= CTL_LUN_INVALID;
5003
5004	/*
5005	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5006	 * If we have something in the OOA queue, we'll free it when the
5007	 * last I/O completes.
5008	 */
5009	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5010		mtx_unlock(&lun->lun_lock);
5011		mtx_lock(&ctl_softc->ctl_lock);
5012		ctl_free_lun(lun);
5013		mtx_unlock(&ctl_softc->ctl_lock);
5014	} else
5015		mtx_unlock(&lun->lun_lock);
5016
5017	return (0);
5018}
5019
5020int
5021ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5022{
5023	struct ctl_softc *ctl_softc;
5024	struct ctl_lun *lun;
5025
5026	ctl_softc = control_softc;
5027	lun = (struct ctl_lun *)be_lun->ctl_lun;
5028
5029	mtx_lock(&lun->lun_lock);
5030	lun->flags |= CTL_LUN_INOPERABLE;
5031	mtx_unlock(&lun->lun_lock);
5032
5033	return (0);
5034}
5035
5036int
5037ctl_lun_operable(struct ctl_be_lun *be_lun)
5038{
5039	struct ctl_softc *ctl_softc;
5040	struct ctl_lun *lun;
5041
5042	ctl_softc = control_softc;
5043	lun = (struct ctl_lun *)be_lun->ctl_lun;
5044
5045	mtx_lock(&lun->lun_lock);
5046	lun->flags &= ~CTL_LUN_INOPERABLE;
5047	mtx_unlock(&lun->lun_lock);
5048
5049	return (0);
5050}
5051
5052int
5053ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5054		   int lock)
5055{
5056	struct ctl_softc *softc;
5057	struct ctl_lun *lun;
5058	struct copan_aps_subpage *current_sp;
5059	struct ctl_page_index *page_index;
5060	int i;
5061
5062	softc = control_softc;
5063
5064	mtx_lock(&softc->ctl_lock);
5065
5066	lun = (struct ctl_lun *)be_lun->ctl_lun;
5067	mtx_lock(&lun->lun_lock);
5068
5069	page_index = NULL;
5070	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5071		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5072		     APS_PAGE_CODE)
5073			continue;
5074
5075		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5076			continue;
5077		page_index = &lun->mode_pages.index[i];
5078	}
5079
5080	if (page_index == NULL) {
5081		mtx_unlock(&lun->lun_lock);
5082		mtx_unlock(&softc->ctl_lock);
5083		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5084		       (uintmax_t)lun->lun);
5085		return (1);
5086	}
5087#if 0
5088	if ((softc->aps_locked_lun != 0)
5089	 && (softc->aps_locked_lun != lun->lun)) {
5090		printf("%s: attempt to lock LUN %llu when %llu is already "
5091		       "locked\n");
5092		mtx_unlock(&lun->lun_lock);
5093		mtx_unlock(&softc->ctl_lock);
5094		return (1);
5095	}
5096#endif
5097
5098	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5099		(page_index->page_len * CTL_PAGE_CURRENT));
5100
5101	if (lock != 0) {
5102		current_sp->lock_active = APS_LOCK_ACTIVE;
5103		softc->aps_locked_lun = lun->lun;
5104	} else {
5105		current_sp->lock_active = 0;
5106		softc->aps_locked_lun = 0;
5107	}
5108
5109
5110	/*
5111	 * If we're in HA mode, try to send the lock message to the other
5112	 * side.
5113	 */
5114	if (ctl_is_single == 0) {
5115		int isc_retval;
5116		union ctl_ha_msg lock_msg;
5117
5118		lock_msg.hdr.nexus = *nexus;
5119		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5120		if (lock != 0)
5121			lock_msg.aps.lock_flag = 1;
5122		else
5123			lock_msg.aps.lock_flag = 0;
5124		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5125					 sizeof(lock_msg), 0);
5126		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5127			printf("%s: APS (lock=%d) error returned from "
5128			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5129			mtx_unlock(&lun->lun_lock);
5130			mtx_unlock(&softc->ctl_lock);
5131			return (1);
5132		}
5133	}
5134
5135	mtx_unlock(&lun->lun_lock);
5136	mtx_unlock(&softc->ctl_lock);
5137
5138	return (0);
5139}
5140
5141void
5142ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5143{
5144	struct ctl_lun *lun;
5145	struct ctl_softc *softc;
5146	int i;
5147
5148	softc = control_softc;
5149
5150	lun = (struct ctl_lun *)be_lun->ctl_lun;
5151
5152	mtx_lock(&lun->lun_lock);
5153
5154	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5155		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5156
5157	mtx_unlock(&lun->lun_lock);
5158}
5159
5160/*
5161 * Backend "memory move is complete" callback for requests that never
5162 * make it down to say RAIDCore's configuration code.
5163 */
5164int
5165ctl_config_move_done(union ctl_io *io)
5166{
5167	int retval;
5168
5169	retval = CTL_RETVAL_COMPLETE;
5170
5171
5172	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5173	/*
5174	 * XXX KDM this shouldn't happen, but what if it does?
5175	 */
5176	if (io->io_hdr.io_type != CTL_IO_SCSI)
5177		panic("I/O type isn't CTL_IO_SCSI!");
5178
5179	if ((io->io_hdr.port_status == 0)
5180	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5181	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5182		io->io_hdr.status = CTL_SUCCESS;
5183	else if ((io->io_hdr.port_status != 0)
5184	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5185	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5186		/*
5187		 * For hardware error sense keys, the sense key
5188		 * specific value is defined to be a retry count,
5189		 * but we use it to pass back an internal FETD
5190		 * error code.  XXX KDM  Hopefully the FETD is only
5191		 * using 16 bits for an error code, since that's
5192		 * all the space we have in the sks field.
5193		 */
5194		ctl_set_internal_failure(&io->scsiio,
5195					 /*sks_valid*/ 1,
5196					 /*retry_count*/
5197					 io->io_hdr.port_status);
5198		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5199			free(io->scsiio.kern_data_ptr, M_CTL);
5200		ctl_done(io);
5201		goto bailout;
5202	}
5203
5204	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5205	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5206	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5207		/*
5208		 * XXX KDM just assuming a single pointer here, and not a
5209		 * S/G list.  If we start using S/G lists for config data,
5210		 * we'll need to know how to clean them up here as well.
5211		 */
5212		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5213			free(io->scsiio.kern_data_ptr, M_CTL);
5214		/* Hopefully the user has already set the status... */
5215		ctl_done(io);
5216	} else {
5217		/*
5218		 * XXX KDM now we need to continue data movement.  Some
5219		 * options:
5220		 * - call ctl_scsiio() again?  We don't do this for data
5221		 *   writes, because for those at least we know ahead of
5222		 *   time where the write will go and how long it is.  For
5223		 *   config writes, though, that information is largely
5224		 *   contained within the write itself, thus we need to
5225		 *   parse out the data again.
5226		 *
5227		 * - Call some other function once the data is in?
5228		 */
5229
5230		/*
5231		 * XXX KDM call ctl_scsiio() again for now, and check flag
5232		 * bits to see whether we're allocated or not.
5233		 */
5234		retval = ctl_scsiio(&io->scsiio);
5235	}
5236bailout:
5237	return (retval);
5238}
5239
5240/*
5241 * This gets called by a backend driver when it is done with a
5242 * data_submit method.
5243 */
5244void
5245ctl_data_submit_done(union ctl_io *io)
5246{
5247	/*
5248	 * If the IO_CONT flag is set, we need to call the supplied
5249	 * function to continue processing the I/O, instead of completing
5250	 * the I/O just yet.
5251	 *
5252	 * If there is an error, though, we don't want to keep processing.
5253	 * Instead, just send status back to the initiator.
5254	 */
5255	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5256	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5257	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5258	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5259		io->scsiio.io_cont(io);
5260		return;
5261	}
5262	ctl_done(io);
5263}
5264
5265/*
5266 * This gets called by a backend driver when it is done with a
5267 * configuration write.
5268 */
5269void
5270ctl_config_write_done(union ctl_io *io)
5271{
5272	uint8_t *buf;
5273
5274	/*
5275	 * If the IO_CONT flag is set, we need to call the supplied
5276	 * function to continue processing the I/O, instead of completing
5277	 * the I/O just yet.
5278	 *
5279	 * If there is an error, though, we don't want to keep processing.
5280	 * Instead, just send status back to the initiator.
5281	 */
5282	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5283	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5284	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5285	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5286		io->scsiio.io_cont(io);
5287		return;
5288	}
5289	/*
5290	 * Since a configuration write can be done for commands that actually
5291	 * have data allocated, like write buffer, and commands that have
5292	 * no data, like start/stop unit, we need to check here.
5293	 */
5294	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5295		buf = io->scsiio.kern_data_ptr;
5296	else
5297		buf = NULL;
5298	ctl_done(io);
5299	if (buf)
5300		free(buf, M_CTL);
5301}
5302
5303/*
5304 * SCSI release command.
5305 */
5306int
5307ctl_scsi_release(struct ctl_scsiio *ctsio)
5308{
5309	int length, longid, thirdparty_id, resv_id;
5310	struct ctl_softc *ctl_softc;
5311	struct ctl_lun *lun;
5312	uint32_t residx;
5313
5314	length = 0;
5315	resv_id = 0;
5316
5317	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5318
5319	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5320	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5321	ctl_softc = control_softc;
5322
5323	switch (ctsio->cdb[0]) {
5324	case RELEASE_10: {
5325		struct scsi_release_10 *cdb;
5326
5327		cdb = (struct scsi_release_10 *)ctsio->cdb;
5328
5329		if (cdb->byte2 & SR10_LONGID)
5330			longid = 1;
5331		else
5332			thirdparty_id = cdb->thirdparty_id;
5333
5334		resv_id = cdb->resv_id;
5335		length = scsi_2btoul(cdb->length);
5336		break;
5337	}
5338	}
5339
5340
5341	/*
5342	 * XXX KDM right now, we only support LUN reservation.  We don't
5343	 * support 3rd party reservations, or extent reservations, which
5344	 * might actually need the parameter list.  If we've gotten this
5345	 * far, we've got a LUN reservation.  Anything else got kicked out
5346	 * above.  So, according to SPC, ignore the length.
5347	 */
5348	length = 0;
5349
5350	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5351	 && (length > 0)) {
5352		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5353		ctsio->kern_data_len = length;
5354		ctsio->kern_total_len = length;
5355		ctsio->kern_data_resid = 0;
5356		ctsio->kern_rel_offset = 0;
5357		ctsio->kern_sg_entries = 0;
5358		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5359		ctsio->be_move_done = ctl_config_move_done;
5360		ctl_datamove((union ctl_io *)ctsio);
5361
5362		return (CTL_RETVAL_COMPLETE);
5363	}
5364
5365	if (length > 0)
5366		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5367
5368	mtx_lock(&lun->lun_lock);
5369
5370	/*
5371	 * According to SPC, it is not an error for an intiator to attempt
5372	 * to release a reservation on a LUN that isn't reserved, or that
5373	 * is reserved by another initiator.  The reservation can only be
5374	 * released, though, by the initiator who made it or by one of
5375	 * several reset type events.
5376	 */
5377	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5378			lun->flags &= ~CTL_LUN_RESERVED;
5379
5380	mtx_unlock(&lun->lun_lock);
5381
5382	ctsio->scsi_status = SCSI_STATUS_OK;
5383	ctsio->io_hdr.status = CTL_SUCCESS;
5384
5385	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5386		free(ctsio->kern_data_ptr, M_CTL);
5387		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5388	}
5389
5390	ctl_done((union ctl_io *)ctsio);
5391	return (CTL_RETVAL_COMPLETE);
5392}
5393
5394int
5395ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5396{
5397	int extent, thirdparty, longid;
5398	int resv_id, length;
5399	uint64_t thirdparty_id;
5400	struct ctl_softc *ctl_softc;
5401	struct ctl_lun *lun;
5402	uint32_t residx;
5403
5404	extent = 0;
5405	thirdparty = 0;
5406	longid = 0;
5407	resv_id = 0;
5408	length = 0;
5409	thirdparty_id = 0;
5410
5411	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5412
5413	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5414	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5415	ctl_softc = control_softc;
5416
5417	switch (ctsio->cdb[0]) {
5418	case RESERVE_10: {
5419		struct scsi_reserve_10 *cdb;
5420
5421		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5422
5423		if (cdb->byte2 & SR10_LONGID)
5424			longid = 1;
5425		else
5426			thirdparty_id = cdb->thirdparty_id;
5427
5428		resv_id = cdb->resv_id;
5429		length = scsi_2btoul(cdb->length);
5430		break;
5431	}
5432	}
5433
5434	/*
5435	 * XXX KDM right now, we only support LUN reservation.  We don't
5436	 * support 3rd party reservations, or extent reservations, which
5437	 * might actually need the parameter list.  If we've gotten this
5438	 * far, we've got a LUN reservation.  Anything else got kicked out
5439	 * above.  So, according to SPC, ignore the length.
5440	 */
5441	length = 0;
5442
5443	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5444	 && (length > 0)) {
5445		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5446		ctsio->kern_data_len = length;
5447		ctsio->kern_total_len = length;
5448		ctsio->kern_data_resid = 0;
5449		ctsio->kern_rel_offset = 0;
5450		ctsio->kern_sg_entries = 0;
5451		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5452		ctsio->be_move_done = ctl_config_move_done;
5453		ctl_datamove((union ctl_io *)ctsio);
5454
5455		return (CTL_RETVAL_COMPLETE);
5456	}
5457
5458	if (length > 0)
5459		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5460
5461	mtx_lock(&lun->lun_lock);
5462	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5463		ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5464		ctsio->io_hdr.status = CTL_SCSI_ERROR;
5465		goto bailout;
5466	}
5467
5468	lun->flags |= CTL_LUN_RESERVED;
5469	lun->res_idx = residx;
5470
5471	ctsio->scsi_status = SCSI_STATUS_OK;
5472	ctsio->io_hdr.status = CTL_SUCCESS;
5473
5474bailout:
5475	mtx_unlock(&lun->lun_lock);
5476
5477	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5478		free(ctsio->kern_data_ptr, M_CTL);
5479		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5480	}
5481
5482	ctl_done((union ctl_io *)ctsio);
5483	return (CTL_RETVAL_COMPLETE);
5484}
5485
5486int
5487ctl_start_stop(struct ctl_scsiio *ctsio)
5488{
5489	struct scsi_start_stop_unit *cdb;
5490	struct ctl_lun *lun;
5491	struct ctl_softc *ctl_softc;
5492	int retval;
5493
5494	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5495
5496	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5497	ctl_softc = control_softc;
5498	retval = 0;
5499
5500	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5501
5502	/*
5503	 * XXX KDM
5504	 * We don't support the immediate bit on a stop unit.  In order to
5505	 * do that, we would need to code up a way to know that a stop is
5506	 * pending, and hold off any new commands until it completes, one
5507	 * way or another.  Then we could accept or reject those commands
5508	 * depending on its status.  We would almost need to do the reverse
5509	 * of what we do below for an immediate start -- return the copy of
5510	 * the ctl_io to the FETD with status to send to the host (and to
5511	 * free the copy!) and then free the original I/O once the stop
5512	 * actually completes.  That way, the OOA queue mechanism can work
5513	 * to block commands that shouldn't proceed.  Another alternative
5514	 * would be to put the copy in the queue in place of the original,
5515	 * and return the original back to the caller.  That could be
5516	 * slightly safer..
5517	 */
5518	if ((cdb->byte2 & SSS_IMMED)
5519	 && ((cdb->how & SSS_START) == 0)) {
5520		ctl_set_invalid_field(ctsio,
5521				      /*sks_valid*/ 1,
5522				      /*command*/ 1,
5523				      /*field*/ 1,
5524				      /*bit_valid*/ 1,
5525				      /*bit*/ 0);
5526		ctl_done((union ctl_io *)ctsio);
5527		return (CTL_RETVAL_COMPLETE);
5528	}
5529
5530	if ((lun->flags & CTL_LUN_PR_RESERVED)
5531	 && ((cdb->how & SSS_START)==0)) {
5532		uint32_t residx;
5533
5534		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5535		if (!lun->per_res[residx].registered
5536		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5537
5538			ctl_set_reservation_conflict(ctsio);
5539			ctl_done((union ctl_io *)ctsio);
5540			return (CTL_RETVAL_COMPLETE);
5541		}
5542	}
5543
5544	/*
5545	 * If there is no backend on this device, we can't start or stop
5546	 * it.  In theory we shouldn't get any start/stop commands in the
5547	 * first place at this level if the LUN doesn't have a backend.
5548	 * That should get stopped by the command decode code.
5549	 */
5550	if (lun->backend == NULL) {
5551		ctl_set_invalid_opcode(ctsio);
5552		ctl_done((union ctl_io *)ctsio);
5553		return (CTL_RETVAL_COMPLETE);
5554	}
5555
5556	/*
5557	 * XXX KDM Copan-specific offline behavior.
5558	 * Figure out a reasonable way to port this?
5559	 */
5560#ifdef NEEDTOPORT
5561	mtx_lock(&lun->lun_lock);
5562
5563	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5564	 && (lun->flags & CTL_LUN_OFFLINE)) {
5565		/*
5566		 * If the LUN is offline, and the on/offline bit isn't set,
5567		 * reject the start or stop.  Otherwise, let it through.
5568		 */
5569		mtx_unlock(&lun->lun_lock);
5570		ctl_set_lun_not_ready(ctsio);
5571		ctl_done((union ctl_io *)ctsio);
5572	} else {
5573		mtx_unlock(&lun->lun_lock);
5574#endif /* NEEDTOPORT */
5575		/*
5576		 * This could be a start or a stop when we're online,
5577		 * or a stop/offline or start/online.  A start or stop when
5578		 * we're offline is covered in the case above.
5579		 */
5580		/*
5581		 * In the non-immediate case, we send the request to
5582		 * the backend and return status to the user when
5583		 * it is done.
5584		 *
5585		 * In the immediate case, we allocate a new ctl_io
5586		 * to hold a copy of the request, and send that to
5587		 * the backend.  We then set good status on the
5588		 * user's request and return it immediately.
5589		 */
5590		if (cdb->byte2 & SSS_IMMED) {
5591			union ctl_io *new_io;
5592
5593			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5594			if (new_io == NULL) {
5595				ctl_set_busy(ctsio);
5596				ctl_done((union ctl_io *)ctsio);
5597			} else {
5598				ctl_copy_io((union ctl_io *)ctsio,
5599					    new_io);
5600				retval = lun->backend->config_write(new_io);
5601				ctl_set_success(ctsio);
5602				ctl_done((union ctl_io *)ctsio);
5603			}
5604		} else {
5605			retval = lun->backend->config_write(
5606				(union ctl_io *)ctsio);
5607		}
5608#ifdef NEEDTOPORT
5609	}
5610#endif
5611	return (retval);
5612}
5613
5614/*
5615 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5616 * we don't really do anything with the LBA and length fields if the user
5617 * passes them in.  Instead we'll just flush out the cache for the entire
5618 * LUN.
5619 */
5620int
5621ctl_sync_cache(struct ctl_scsiio *ctsio)
5622{
5623	struct ctl_lun *lun;
5624	struct ctl_softc *ctl_softc;
5625	uint64_t starting_lba;
5626	uint32_t block_count;
5627	int retval;
5628
5629	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5630
5631	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5632	ctl_softc = control_softc;
5633	retval = 0;
5634
5635	switch (ctsio->cdb[0]) {
5636	case SYNCHRONIZE_CACHE: {
5637		struct scsi_sync_cache *cdb;
5638		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5639
5640		starting_lba = scsi_4btoul(cdb->begin_lba);
5641		block_count = scsi_2btoul(cdb->lb_count);
5642		break;
5643	}
5644	case SYNCHRONIZE_CACHE_16: {
5645		struct scsi_sync_cache_16 *cdb;
5646		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5647
5648		starting_lba = scsi_8btou64(cdb->begin_lba);
5649		block_count = scsi_4btoul(cdb->lb_count);
5650		break;
5651	}
5652	default:
5653		ctl_set_invalid_opcode(ctsio);
5654		ctl_done((union ctl_io *)ctsio);
5655		goto bailout;
5656		break; /* NOTREACHED */
5657	}
5658
5659	/*
5660	 * We check the LBA and length, but don't do anything with them.
5661	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5662	 * get flushed.  This check will just help satisfy anyone who wants
5663	 * to see an error for an out of range LBA.
5664	 */
5665	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5666		ctl_set_lba_out_of_range(ctsio);
5667		ctl_done((union ctl_io *)ctsio);
5668		goto bailout;
5669	}
5670
5671	/*
5672	 * If this LUN has no backend, we can't flush the cache anyway.
5673	 */
5674	if (lun->backend == NULL) {
5675		ctl_set_invalid_opcode(ctsio);
5676		ctl_done((union ctl_io *)ctsio);
5677		goto bailout;
5678	}
5679
5680	/*
5681	 * Check to see whether we're configured to send the SYNCHRONIZE
5682	 * CACHE command directly to the back end.
5683	 */
5684	mtx_lock(&lun->lun_lock);
5685	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5686	 && (++(lun->sync_count) >= lun->sync_interval)) {
5687		lun->sync_count = 0;
5688		mtx_unlock(&lun->lun_lock);
5689		retval = lun->backend->config_write((union ctl_io *)ctsio);
5690	} else {
5691		mtx_unlock(&lun->lun_lock);
5692		ctl_set_success(ctsio);
5693		ctl_done((union ctl_io *)ctsio);
5694	}
5695
5696bailout:
5697
5698	return (retval);
5699}
5700
5701int
5702ctl_format(struct ctl_scsiio *ctsio)
5703{
5704	struct scsi_format *cdb;
5705	struct ctl_lun *lun;
5706	struct ctl_softc *ctl_softc;
5707	int length, defect_list_len;
5708
5709	CTL_DEBUG_PRINT(("ctl_format\n"));
5710
5711	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5712	ctl_softc = control_softc;
5713
5714	cdb = (struct scsi_format *)ctsio->cdb;
5715
5716	length = 0;
5717	if (cdb->byte2 & SF_FMTDATA) {
5718		if (cdb->byte2 & SF_LONGLIST)
5719			length = sizeof(struct scsi_format_header_long);
5720		else
5721			length = sizeof(struct scsi_format_header_short);
5722	}
5723
5724	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5725	 && (length > 0)) {
5726		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5727		ctsio->kern_data_len = length;
5728		ctsio->kern_total_len = length;
5729		ctsio->kern_data_resid = 0;
5730		ctsio->kern_rel_offset = 0;
5731		ctsio->kern_sg_entries = 0;
5732		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5733		ctsio->be_move_done = ctl_config_move_done;
5734		ctl_datamove((union ctl_io *)ctsio);
5735
5736		return (CTL_RETVAL_COMPLETE);
5737	}
5738
5739	defect_list_len = 0;
5740
5741	if (cdb->byte2 & SF_FMTDATA) {
5742		if (cdb->byte2 & SF_LONGLIST) {
5743			struct scsi_format_header_long *header;
5744
5745			header = (struct scsi_format_header_long *)
5746				ctsio->kern_data_ptr;
5747
5748			defect_list_len = scsi_4btoul(header->defect_list_len);
5749			if (defect_list_len != 0) {
5750				ctl_set_invalid_field(ctsio,
5751						      /*sks_valid*/ 1,
5752						      /*command*/ 0,
5753						      /*field*/ 2,
5754						      /*bit_valid*/ 0,
5755						      /*bit*/ 0);
5756				goto bailout;
5757			}
5758		} else {
5759			struct scsi_format_header_short *header;
5760
5761			header = (struct scsi_format_header_short *)
5762				ctsio->kern_data_ptr;
5763
5764			defect_list_len = scsi_2btoul(header->defect_list_len);
5765			if (defect_list_len != 0) {
5766				ctl_set_invalid_field(ctsio,
5767						      /*sks_valid*/ 1,
5768						      /*command*/ 0,
5769						      /*field*/ 2,
5770						      /*bit_valid*/ 0,
5771						      /*bit*/ 0);
5772				goto bailout;
5773			}
5774		}
5775	}
5776
5777	/*
5778	 * The format command will clear out the "Medium format corrupted"
5779	 * status if set by the configuration code.  That status is really
5780	 * just a way to notify the host that we have lost the media, and
5781	 * get them to issue a command that will basically make them think
5782	 * they're blowing away the media.
5783	 */
5784	mtx_lock(&lun->lun_lock);
5785	lun->flags &= ~CTL_LUN_INOPERABLE;
5786	mtx_unlock(&lun->lun_lock);
5787
5788	ctsio->scsi_status = SCSI_STATUS_OK;
5789	ctsio->io_hdr.status = CTL_SUCCESS;
5790bailout:
5791
5792	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5793		free(ctsio->kern_data_ptr, M_CTL);
5794		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5795	}
5796
5797	ctl_done((union ctl_io *)ctsio);
5798	return (CTL_RETVAL_COMPLETE);
5799}
5800
5801int
5802ctl_read_buffer(struct ctl_scsiio *ctsio)
5803{
5804	struct scsi_read_buffer *cdb;
5805	struct ctl_lun *lun;
5806	int buffer_offset, len;
5807	static uint8_t descr[4];
5808	static uint8_t echo_descr[4] = { 0 };
5809
5810	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5811
5812	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5813	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5814
5815	if (lun->flags & CTL_LUN_PR_RESERVED) {
5816		uint32_t residx;
5817
5818		/*
5819		 * XXX KDM need a lock here.
5820		 */
5821		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5822		if ((lun->res_type == SPR_TYPE_EX_AC
5823		  && residx != lun->pr_res_idx)
5824		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5825		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5826		  && !lun->per_res[residx].registered)) {
5827			ctl_set_reservation_conflict(ctsio);
5828			ctl_done((union ctl_io *)ctsio);
5829			return (CTL_RETVAL_COMPLETE);
5830	        }
5831	}
5832
5833	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5834	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5835	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5836		ctl_set_invalid_field(ctsio,
5837				      /*sks_valid*/ 1,
5838				      /*command*/ 1,
5839				      /*field*/ 1,
5840				      /*bit_valid*/ 1,
5841				      /*bit*/ 4);
5842		ctl_done((union ctl_io *)ctsio);
5843		return (CTL_RETVAL_COMPLETE);
5844	}
5845
5846	len = scsi_3btoul(cdb->length);
5847	buffer_offset = scsi_3btoul(cdb->offset);
5848
5849	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5850		ctl_set_invalid_field(ctsio,
5851				      /*sks_valid*/ 1,
5852				      /*command*/ 1,
5853				      /*field*/ 6,
5854				      /*bit_valid*/ 0,
5855				      /*bit*/ 0);
5856		ctl_done((union ctl_io *)ctsio);
5857		return (CTL_RETVAL_COMPLETE);
5858	}
5859
5860	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5861		descr[0] = 0;
5862		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5863		ctsio->kern_data_ptr = descr;
5864		len = min(len, sizeof(descr));
5865	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5866		ctsio->kern_data_ptr = echo_descr;
5867		len = min(len, sizeof(echo_descr));
5868	} else
5869		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5870	ctsio->kern_data_len = len;
5871	ctsio->kern_total_len = len;
5872	ctsio->kern_data_resid = 0;
5873	ctsio->kern_rel_offset = 0;
5874	ctsio->kern_sg_entries = 0;
5875	ctsio->be_move_done = ctl_config_move_done;
5876	ctl_datamove((union ctl_io *)ctsio);
5877
5878	return (CTL_RETVAL_COMPLETE);
5879}
5880
5881int
5882ctl_write_buffer(struct ctl_scsiio *ctsio)
5883{
5884	struct scsi_write_buffer *cdb;
5885	struct ctl_lun *lun;
5886	int buffer_offset, len;
5887
5888	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5889
5890	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5891	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5892
5893	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5894		ctl_set_invalid_field(ctsio,
5895				      /*sks_valid*/ 1,
5896				      /*command*/ 1,
5897				      /*field*/ 1,
5898				      /*bit_valid*/ 1,
5899				      /*bit*/ 4);
5900		ctl_done((union ctl_io *)ctsio);
5901		return (CTL_RETVAL_COMPLETE);
5902	}
5903
5904	len = scsi_3btoul(cdb->length);
5905	buffer_offset = scsi_3btoul(cdb->offset);
5906
5907	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5908		ctl_set_invalid_field(ctsio,
5909				      /*sks_valid*/ 1,
5910				      /*command*/ 1,
5911				      /*field*/ 6,
5912				      /*bit_valid*/ 0,
5913				      /*bit*/ 0);
5914		ctl_done((union ctl_io *)ctsio);
5915		return (CTL_RETVAL_COMPLETE);
5916	}
5917
5918	/*
5919	 * If we've got a kernel request that hasn't been malloced yet,
5920	 * malloc it and tell the caller the data buffer is here.
5921	 */
5922	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5923		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5924		ctsio->kern_data_len = len;
5925		ctsio->kern_total_len = len;
5926		ctsio->kern_data_resid = 0;
5927		ctsio->kern_rel_offset = 0;
5928		ctsio->kern_sg_entries = 0;
5929		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5930		ctsio->be_move_done = ctl_config_move_done;
5931		ctl_datamove((union ctl_io *)ctsio);
5932
5933		return (CTL_RETVAL_COMPLETE);
5934	}
5935
5936	ctl_done((union ctl_io *)ctsio);
5937
5938	return (CTL_RETVAL_COMPLETE);
5939}
5940
5941int
5942ctl_write_same(struct ctl_scsiio *ctsio)
5943{
5944	struct ctl_lun *lun;
5945	struct ctl_lba_len_flags *lbalen;
5946	uint64_t lba;
5947	uint32_t num_blocks;
5948	int len, retval;
5949	uint8_t byte2;
5950
5951	retval = CTL_RETVAL_COMPLETE;
5952
5953	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5954
5955	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5956
5957	switch (ctsio->cdb[0]) {
5958	case WRITE_SAME_10: {
5959		struct scsi_write_same_10 *cdb;
5960
5961		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5962
5963		lba = scsi_4btoul(cdb->addr);
5964		num_blocks = scsi_2btoul(cdb->length);
5965		byte2 = cdb->byte2;
5966		break;
5967	}
5968	case WRITE_SAME_16: {
5969		struct scsi_write_same_16 *cdb;
5970
5971		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5972
5973		lba = scsi_8btou64(cdb->addr);
5974		num_blocks = scsi_4btoul(cdb->length);
5975		byte2 = cdb->byte2;
5976		break;
5977	}
5978	default:
5979		/*
5980		 * We got a command we don't support.  This shouldn't
5981		 * happen, commands should be filtered out above us.
5982		 */
5983		ctl_set_invalid_opcode(ctsio);
5984		ctl_done((union ctl_io *)ctsio);
5985
5986		return (CTL_RETVAL_COMPLETE);
5987		break; /* NOTREACHED */
5988	}
5989
5990	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5991	if ((byte2 & SWS_UNMAP) == 0 &&
5992	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5993		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5994		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5995		ctl_done((union ctl_io *)ctsio);
5996		return (CTL_RETVAL_COMPLETE);
5997	}
5998
5999	/*
6000	 * The first check is to make sure we're in bounds, the second
6001	 * check is to catch wrap-around problems.  If the lba + num blocks
6002	 * is less than the lba, then we've wrapped around and the block
6003	 * range is invalid anyway.
6004	 */
6005	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6006	 || ((lba + num_blocks) < lba)) {
6007		ctl_set_lba_out_of_range(ctsio);
6008		ctl_done((union ctl_io *)ctsio);
6009		return (CTL_RETVAL_COMPLETE);
6010	}
6011
6012	/* Zero number of blocks means "to the last logical block" */
6013	if (num_blocks == 0) {
6014		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6015			ctl_set_invalid_field(ctsio,
6016					      /*sks_valid*/ 0,
6017					      /*command*/ 1,
6018					      /*field*/ 0,
6019					      /*bit_valid*/ 0,
6020					      /*bit*/ 0);
6021			ctl_done((union ctl_io *)ctsio);
6022			return (CTL_RETVAL_COMPLETE);
6023		}
6024		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6025	}
6026
6027	len = lun->be_lun->blocksize;
6028
6029	/*
6030	 * If we've got a kernel request that hasn't been malloced yet,
6031	 * malloc it and tell the caller the data buffer is here.
6032	 */
6033	if ((byte2 & SWS_NDOB) == 0 &&
6034	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6035		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6036		ctsio->kern_data_len = len;
6037		ctsio->kern_total_len = len;
6038		ctsio->kern_data_resid = 0;
6039		ctsio->kern_rel_offset = 0;
6040		ctsio->kern_sg_entries = 0;
6041		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6042		ctsio->be_move_done = ctl_config_move_done;
6043		ctl_datamove((union ctl_io *)ctsio);
6044
6045		return (CTL_RETVAL_COMPLETE);
6046	}
6047
6048	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6049	lbalen->lba = lba;
6050	lbalen->len = num_blocks;
6051	lbalen->flags = byte2;
6052	retval = lun->backend->config_write((union ctl_io *)ctsio);
6053
6054	return (retval);
6055}
6056
6057int
6058ctl_unmap(struct ctl_scsiio *ctsio)
6059{
6060	struct ctl_lun *lun;
6061	struct scsi_unmap *cdb;
6062	struct ctl_ptr_len_flags *ptrlen;
6063	struct scsi_unmap_header *hdr;
6064	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6065	uint64_t lba;
6066	uint32_t num_blocks;
6067	int len, retval;
6068	uint8_t byte2;
6069
6070	retval = CTL_RETVAL_COMPLETE;
6071
6072	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6073
6074	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6075	cdb = (struct scsi_unmap *)ctsio->cdb;
6076
6077	len = scsi_2btoul(cdb->length);
6078	byte2 = cdb->byte2;
6079
6080	/*
6081	 * If we've got a kernel request that hasn't been malloced yet,
6082	 * malloc it and tell the caller the data buffer is here.
6083	 */
6084	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6085		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6086		ctsio->kern_data_len = len;
6087		ctsio->kern_total_len = len;
6088		ctsio->kern_data_resid = 0;
6089		ctsio->kern_rel_offset = 0;
6090		ctsio->kern_sg_entries = 0;
6091		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6092		ctsio->be_move_done = ctl_config_move_done;
6093		ctl_datamove((union ctl_io *)ctsio);
6094
6095		return (CTL_RETVAL_COMPLETE);
6096	}
6097
6098	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6099	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6100	if (len < sizeof (*hdr) ||
6101	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6102	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6103	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6104		ctl_set_invalid_field(ctsio,
6105				      /*sks_valid*/ 0,
6106				      /*command*/ 0,
6107				      /*field*/ 0,
6108				      /*bit_valid*/ 0,
6109				      /*bit*/ 0);
6110		ctl_done((union ctl_io *)ctsio);
6111		return (CTL_RETVAL_COMPLETE);
6112	}
6113	len = scsi_2btoul(hdr->desc_length);
6114	buf = (struct scsi_unmap_desc *)(hdr + 1);
6115	end = buf + len / sizeof(*buf);
6116
6117	endnz = buf;
6118	for (range = buf; range < end; range++) {
6119		lba = scsi_8btou64(range->lba);
6120		num_blocks = scsi_4btoul(range->length);
6121		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6122		 || ((lba + num_blocks) < lba)) {
6123			ctl_set_lba_out_of_range(ctsio);
6124			ctl_done((union ctl_io *)ctsio);
6125			return (CTL_RETVAL_COMPLETE);
6126		}
6127		if (num_blocks != 0)
6128			endnz = range + 1;
6129	}
6130
6131	/*
6132	 * Block backend can not handle zero last range.
6133	 * Filter it out and return if there is nothing left.
6134	 */
6135	len = (uint8_t *)endnz - (uint8_t *)buf;
6136	if (len == 0) {
6137		ctl_set_success(ctsio);
6138		ctl_done((union ctl_io *)ctsio);
6139		return (CTL_RETVAL_COMPLETE);
6140	}
6141
6142	mtx_lock(&lun->lun_lock);
6143	ptrlen = (struct ctl_ptr_len_flags *)
6144	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6145	ptrlen->ptr = (void *)buf;
6146	ptrlen->len = len;
6147	ptrlen->flags = byte2;
6148	ctl_check_blocked(lun);
6149	mtx_unlock(&lun->lun_lock);
6150
6151	retval = lun->backend->config_write((union ctl_io *)ctsio);
6152	return (retval);
6153}
6154
6155/*
6156 * Note that this function currently doesn't actually do anything inside
6157 * CTL to enforce things if the DQue bit is turned on.
6158 *
6159 * Also note that this function can't be used in the default case, because
6160 * the DQue bit isn't set in the changeable mask for the control mode page
6161 * anyway.  This is just here as an example for how to implement a page
6162 * handler, and a placeholder in case we want to allow the user to turn
6163 * tagged queueing on and off.
6164 *
6165 * The D_SENSE bit handling is functional, however, and will turn
6166 * descriptor sense on and off for a given LUN.
6167 */
6168int
6169ctl_control_page_handler(struct ctl_scsiio *ctsio,
6170			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6171{
6172	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6173	struct ctl_lun *lun;
6174	struct ctl_softc *softc;
6175	int set_ua;
6176	uint32_t initidx;
6177
6178	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6179	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6180	set_ua = 0;
6181
6182	user_cp = (struct scsi_control_page *)page_ptr;
6183	current_cp = (struct scsi_control_page *)
6184		(page_index->page_data + (page_index->page_len *
6185		CTL_PAGE_CURRENT));
6186	saved_cp = (struct scsi_control_page *)
6187		(page_index->page_data + (page_index->page_len *
6188		CTL_PAGE_SAVED));
6189
6190	softc = control_softc;
6191
6192	mtx_lock(&lun->lun_lock);
6193	if (((current_cp->rlec & SCP_DSENSE) == 0)
6194	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6195		/*
6196		 * Descriptor sense is currently turned off and the user
6197		 * wants to turn it on.
6198		 */
6199		current_cp->rlec |= SCP_DSENSE;
6200		saved_cp->rlec |= SCP_DSENSE;
6201		lun->flags |= CTL_LUN_SENSE_DESC;
6202		set_ua = 1;
6203	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6204		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6205		/*
6206		 * Descriptor sense is currently turned on, and the user
6207		 * wants to turn it off.
6208		 */
6209		current_cp->rlec &= ~SCP_DSENSE;
6210		saved_cp->rlec &= ~SCP_DSENSE;
6211		lun->flags &= ~CTL_LUN_SENSE_DESC;
6212		set_ua = 1;
6213	}
6214	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6215	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6216		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6217		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6218		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6219		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6220		set_ua = 1;
6221	}
6222	if (set_ua != 0) {
6223		int i;
6224		/*
6225		 * Let other initiators know that the mode
6226		 * parameters for this LUN have changed.
6227		 */
6228		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6229			if (i == initidx)
6230				continue;
6231
6232			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6233		}
6234	}
6235	mtx_unlock(&lun->lun_lock);
6236
6237	return (0);
6238}
6239
6240int
6241ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6242		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6243{
6244	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6245	struct ctl_lun *lun;
6246	int set_ua;
6247	uint32_t initidx;
6248
6249	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6250	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6251	set_ua = 0;
6252
6253	user_cp = (struct scsi_caching_page *)page_ptr;
6254	current_cp = (struct scsi_caching_page *)
6255		(page_index->page_data + (page_index->page_len *
6256		CTL_PAGE_CURRENT));
6257	saved_cp = (struct scsi_caching_page *)
6258		(page_index->page_data + (page_index->page_len *
6259		CTL_PAGE_SAVED));
6260
6261	mtx_lock(&lun->lun_lock);
6262	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6263	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6264		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6265		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6266		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6267		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6268		set_ua = 1;
6269	}
6270	if (set_ua != 0) {
6271		int i;
6272		/*
6273		 * Let other initiators know that the mode
6274		 * parameters for this LUN have changed.
6275		 */
6276		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6277			if (i == initidx)
6278				continue;
6279
6280			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6281		}
6282	}
6283	mtx_unlock(&lun->lun_lock);
6284
6285	return (0);
6286}
6287
6288int
6289ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6290		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6291{
6292	return (0);
6293}
6294
6295int
6296ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6297			   struct ctl_page_index *page_index, int pc)
6298{
6299	struct copan_power_subpage *page;
6300
6301	page = (struct copan_power_subpage *)page_index->page_data +
6302		(page_index->page_len * pc);
6303
6304	switch (pc) {
6305	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6306		/*
6307		 * We don't update the changable bits for this page.
6308		 */
6309		break;
6310	case SMS_PAGE_CTRL_CURRENT >> 6:
6311	case SMS_PAGE_CTRL_DEFAULT >> 6:
6312	case SMS_PAGE_CTRL_SAVED >> 6:
6313#ifdef NEEDTOPORT
6314		ctl_update_power_subpage(page);
6315#endif
6316		break;
6317	default:
6318#ifdef NEEDTOPORT
6319		EPRINT(0, "Invalid PC %d!!", pc);
6320#endif
6321		break;
6322	}
6323	return (0);
6324}
6325
6326
6327int
6328ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6329		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6330{
6331	struct copan_aps_subpage *user_sp;
6332	struct copan_aps_subpage *current_sp;
6333	union ctl_modepage_info *modepage_info;
6334	struct ctl_softc *softc;
6335	struct ctl_lun *lun;
6336	int retval;
6337
6338	retval = CTL_RETVAL_COMPLETE;
6339	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6340		     (page_index->page_len * CTL_PAGE_CURRENT));
6341	softc = control_softc;
6342	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6343
6344	user_sp = (struct copan_aps_subpage *)page_ptr;
6345
6346	modepage_info = (union ctl_modepage_info *)
6347		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6348
6349	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6350	modepage_info->header.subpage = page_index->subpage;
6351	modepage_info->aps.lock_active = user_sp->lock_active;
6352
6353	mtx_lock(&softc->ctl_lock);
6354
6355	/*
6356	 * If there is a request to lock the LUN and another LUN is locked
6357	 * this is an error. If the requested LUN is already locked ignore
6358	 * the request. If no LUN is locked attempt to lock it.
6359	 * if there is a request to unlock the LUN and the LUN is currently
6360	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6361	 * if another LUN is locked or no LUN is locked.
6362	 */
6363	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6364		if (softc->aps_locked_lun == lun->lun) {
6365			/*
6366			 * This LUN is already locked, so we're done.
6367			 */
6368			retval = CTL_RETVAL_COMPLETE;
6369		} else if (softc->aps_locked_lun == 0) {
6370			/*
6371			 * No one has the lock, pass the request to the
6372			 * backend.
6373			 */
6374			retval = lun->backend->config_write(
6375				(union ctl_io *)ctsio);
6376		} else {
6377			/*
6378			 * Someone else has the lock, throw out the request.
6379			 */
6380			ctl_set_already_locked(ctsio);
6381			free(ctsio->kern_data_ptr, M_CTL);
6382			ctl_done((union ctl_io *)ctsio);
6383
6384			/*
6385			 * Set the return value so that ctl_do_mode_select()
6386			 * won't try to complete the command.  We already
6387			 * completed it here.
6388			 */
6389			retval = CTL_RETVAL_ERROR;
6390		}
6391	} else if (softc->aps_locked_lun == lun->lun) {
6392		/*
6393		 * This LUN is locked, so pass the unlock request to the
6394		 * backend.
6395		 */
6396		retval = lun->backend->config_write((union ctl_io *)ctsio);
6397	}
6398	mtx_unlock(&softc->ctl_lock);
6399
6400	return (retval);
6401}
6402
6403int
6404ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6405				struct ctl_page_index *page_index,
6406				uint8_t *page_ptr)
6407{
6408	uint8_t *c;
6409	int i;
6410
6411	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6412	ctl_time_io_secs =
6413		(c[0] << 8) |
6414		(c[1] << 0) |
6415		0;
6416	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6417	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6418	printf("page data:");
6419	for (i=0; i<8; i++)
6420		printf(" %.2x",page_ptr[i]);
6421	printf("\n");
6422	return (0);
6423}
6424
6425int
6426ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6427			       struct ctl_page_index *page_index,
6428			       int pc)
6429{
6430	struct copan_debugconf_subpage *page;
6431
6432	page = (struct copan_debugconf_subpage *)page_index->page_data +
6433		(page_index->page_len * pc);
6434
6435	switch (pc) {
6436	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6437	case SMS_PAGE_CTRL_DEFAULT >> 6:
6438	case SMS_PAGE_CTRL_SAVED >> 6:
6439		/*
6440		 * We don't update the changable or default bits for this page.
6441		 */
6442		break;
6443	case SMS_PAGE_CTRL_CURRENT >> 6:
6444		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6445		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6446		break;
6447	default:
6448#ifdef NEEDTOPORT
6449		EPRINT(0, "Invalid PC %d!!", pc);
6450#endif /* NEEDTOPORT */
6451		break;
6452	}
6453	return (0);
6454}
6455
6456
6457static int
6458ctl_do_mode_select(union ctl_io *io)
6459{
6460	struct scsi_mode_page_header *page_header;
6461	struct ctl_page_index *page_index;
6462	struct ctl_scsiio *ctsio;
6463	int control_dev, page_len;
6464	int page_len_offset, page_len_size;
6465	union ctl_modepage_info *modepage_info;
6466	struct ctl_lun *lun;
6467	int *len_left, *len_used;
6468	int retval, i;
6469
6470	ctsio = &io->scsiio;
6471	page_index = NULL;
6472	page_len = 0;
6473	retval = CTL_RETVAL_COMPLETE;
6474
6475	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6476
6477	if (lun->be_lun->lun_type != T_DIRECT)
6478		control_dev = 1;
6479	else
6480		control_dev = 0;
6481
6482	modepage_info = (union ctl_modepage_info *)
6483		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6484	len_left = &modepage_info->header.len_left;
6485	len_used = &modepage_info->header.len_used;
6486
6487do_next_page:
6488
6489	page_header = (struct scsi_mode_page_header *)
6490		(ctsio->kern_data_ptr + *len_used);
6491
6492	if (*len_left == 0) {
6493		free(ctsio->kern_data_ptr, M_CTL);
6494		ctl_set_success(ctsio);
6495		ctl_done((union ctl_io *)ctsio);
6496		return (CTL_RETVAL_COMPLETE);
6497	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6498
6499		free(ctsio->kern_data_ptr, M_CTL);
6500		ctl_set_param_len_error(ctsio);
6501		ctl_done((union ctl_io *)ctsio);
6502		return (CTL_RETVAL_COMPLETE);
6503
6504	} else if ((page_header->page_code & SMPH_SPF)
6505		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6506
6507		free(ctsio->kern_data_ptr, M_CTL);
6508		ctl_set_param_len_error(ctsio);
6509		ctl_done((union ctl_io *)ctsio);
6510		return (CTL_RETVAL_COMPLETE);
6511	}
6512
6513
6514	/*
6515	 * XXX KDM should we do something with the block descriptor?
6516	 */
6517	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6518
6519		if ((control_dev != 0)
6520		 && (lun->mode_pages.index[i].page_flags &
6521		     CTL_PAGE_FLAG_DISK_ONLY))
6522			continue;
6523
6524		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6525		    (page_header->page_code & SMPH_PC_MASK))
6526			continue;
6527
6528		/*
6529		 * If neither page has a subpage code, then we've got a
6530		 * match.
6531		 */
6532		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6533		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6534			page_index = &lun->mode_pages.index[i];
6535			page_len = page_header->page_length;
6536			break;
6537		}
6538
6539		/*
6540		 * If both pages have subpages, then the subpage numbers
6541		 * have to match.
6542		 */
6543		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6544		  && (page_header->page_code & SMPH_SPF)) {
6545			struct scsi_mode_page_header_sp *sph;
6546
6547			sph = (struct scsi_mode_page_header_sp *)page_header;
6548
6549			if (lun->mode_pages.index[i].subpage ==
6550			    sph->subpage) {
6551				page_index = &lun->mode_pages.index[i];
6552				page_len = scsi_2btoul(sph->page_length);
6553				break;
6554			}
6555		}
6556	}
6557
6558	/*
6559	 * If we couldn't find the page, or if we don't have a mode select
6560	 * handler for it, send back an error to the user.
6561	 */
6562	if ((page_index == NULL)
6563	 || (page_index->select_handler == NULL)) {
6564		ctl_set_invalid_field(ctsio,
6565				      /*sks_valid*/ 1,
6566				      /*command*/ 0,
6567				      /*field*/ *len_used,
6568				      /*bit_valid*/ 0,
6569				      /*bit*/ 0);
6570		free(ctsio->kern_data_ptr, M_CTL);
6571		ctl_done((union ctl_io *)ctsio);
6572		return (CTL_RETVAL_COMPLETE);
6573	}
6574
6575	if (page_index->page_code & SMPH_SPF) {
6576		page_len_offset = 2;
6577		page_len_size = 2;
6578	} else {
6579		page_len_size = 1;
6580		page_len_offset = 1;
6581	}
6582
6583	/*
6584	 * If the length the initiator gives us isn't the one we specify in
6585	 * the mode page header, or if they didn't specify enough data in
6586	 * the CDB to avoid truncating this page, kick out the request.
6587	 */
6588	if ((page_len != (page_index->page_len - page_len_offset -
6589			  page_len_size))
6590	 || (*len_left < page_index->page_len)) {
6591
6592
6593		ctl_set_invalid_field(ctsio,
6594				      /*sks_valid*/ 1,
6595				      /*command*/ 0,
6596				      /*field*/ *len_used + page_len_offset,
6597				      /*bit_valid*/ 0,
6598				      /*bit*/ 0);
6599		free(ctsio->kern_data_ptr, M_CTL);
6600		ctl_done((union ctl_io *)ctsio);
6601		return (CTL_RETVAL_COMPLETE);
6602	}
6603
6604	/*
6605	 * Run through the mode page, checking to make sure that the bits
6606	 * the user changed are actually legal for him to change.
6607	 */
6608	for (i = 0; i < page_index->page_len; i++) {
6609		uint8_t *user_byte, *change_mask, *current_byte;
6610		int bad_bit;
6611		int j;
6612
6613		user_byte = (uint8_t *)page_header + i;
6614		change_mask = page_index->page_data +
6615			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6616		current_byte = page_index->page_data +
6617			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6618
6619		/*
6620		 * Check to see whether the user set any bits in this byte
6621		 * that he is not allowed to set.
6622		 */
6623		if ((*user_byte & ~(*change_mask)) ==
6624		    (*current_byte & ~(*change_mask)))
6625			continue;
6626
6627		/*
6628		 * Go through bit by bit to determine which one is illegal.
6629		 */
6630		bad_bit = 0;
6631		for (j = 7; j >= 0; j--) {
6632			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6633			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6634				bad_bit = i;
6635				break;
6636			}
6637		}
6638		ctl_set_invalid_field(ctsio,
6639				      /*sks_valid*/ 1,
6640				      /*command*/ 0,
6641				      /*field*/ *len_used + i,
6642				      /*bit_valid*/ 1,
6643				      /*bit*/ bad_bit);
6644		free(ctsio->kern_data_ptr, M_CTL);
6645		ctl_done((union ctl_io *)ctsio);
6646		return (CTL_RETVAL_COMPLETE);
6647	}
6648
6649	/*
6650	 * Decrement these before we call the page handler, since we may
6651	 * end up getting called back one way or another before the handler
6652	 * returns to this context.
6653	 */
6654	*len_left -= page_index->page_len;
6655	*len_used += page_index->page_len;
6656
6657	retval = page_index->select_handler(ctsio, page_index,
6658					    (uint8_t *)page_header);
6659
6660	/*
6661	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6662	 * wait until this queued command completes to finish processing
6663	 * the mode page.  If it returns anything other than
6664	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6665	 * already set the sense information, freed the data pointer, and
6666	 * completed the io for us.
6667	 */
6668	if (retval != CTL_RETVAL_COMPLETE)
6669		goto bailout_no_done;
6670
6671	/*
6672	 * If the initiator sent us more than one page, parse the next one.
6673	 */
6674	if (*len_left > 0)
6675		goto do_next_page;
6676
6677	ctl_set_success(ctsio);
6678	free(ctsio->kern_data_ptr, M_CTL);
6679	ctl_done((union ctl_io *)ctsio);
6680
6681bailout_no_done:
6682
6683	return (CTL_RETVAL_COMPLETE);
6684
6685}
6686
6687int
6688ctl_mode_select(struct ctl_scsiio *ctsio)
6689{
6690	int param_len, pf, sp;
6691	int header_size, bd_len;
6692	int len_left, len_used;
6693	struct ctl_page_index *page_index;
6694	struct ctl_lun *lun;
6695	int control_dev, page_len;
6696	union ctl_modepage_info *modepage_info;
6697	int retval;
6698
6699	pf = 0;
6700	sp = 0;
6701	page_len = 0;
6702	len_used = 0;
6703	len_left = 0;
6704	retval = 0;
6705	bd_len = 0;
6706	page_index = NULL;
6707
6708	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6709
6710	if (lun->be_lun->lun_type != T_DIRECT)
6711		control_dev = 1;
6712	else
6713		control_dev = 0;
6714
6715	switch (ctsio->cdb[0]) {
6716	case MODE_SELECT_6: {
6717		struct scsi_mode_select_6 *cdb;
6718
6719		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6720
6721		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6722		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6723
6724		param_len = cdb->length;
6725		header_size = sizeof(struct scsi_mode_header_6);
6726		break;
6727	}
6728	case MODE_SELECT_10: {
6729		struct scsi_mode_select_10 *cdb;
6730
6731		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6732
6733		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6734		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6735
6736		param_len = scsi_2btoul(cdb->length);
6737		header_size = sizeof(struct scsi_mode_header_10);
6738		break;
6739	}
6740	default:
6741		ctl_set_invalid_opcode(ctsio);
6742		ctl_done((union ctl_io *)ctsio);
6743		return (CTL_RETVAL_COMPLETE);
6744		break; /* NOTREACHED */
6745	}
6746
6747	/*
6748	 * From SPC-3:
6749	 * "A parameter list length of zero indicates that the Data-Out Buffer
6750	 * shall be empty. This condition shall not be considered as an error."
6751	 */
6752	if (param_len == 0) {
6753		ctl_set_success(ctsio);
6754		ctl_done((union ctl_io *)ctsio);
6755		return (CTL_RETVAL_COMPLETE);
6756	}
6757
6758	/*
6759	 * Since we'll hit this the first time through, prior to
6760	 * allocation, we don't need to free a data buffer here.
6761	 */
6762	if (param_len < header_size) {
6763		ctl_set_param_len_error(ctsio);
6764		ctl_done((union ctl_io *)ctsio);
6765		return (CTL_RETVAL_COMPLETE);
6766	}
6767
6768	/*
6769	 * Allocate the data buffer and grab the user's data.  In theory,
6770	 * we shouldn't have to sanity check the parameter list length here
6771	 * because the maximum size is 64K.  We should be able to malloc
6772	 * that much without too many problems.
6773	 */
6774	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6775		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6776		ctsio->kern_data_len = param_len;
6777		ctsio->kern_total_len = param_len;
6778		ctsio->kern_data_resid = 0;
6779		ctsio->kern_rel_offset = 0;
6780		ctsio->kern_sg_entries = 0;
6781		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6782		ctsio->be_move_done = ctl_config_move_done;
6783		ctl_datamove((union ctl_io *)ctsio);
6784
6785		return (CTL_RETVAL_COMPLETE);
6786	}
6787
6788	switch (ctsio->cdb[0]) {
6789	case MODE_SELECT_6: {
6790		struct scsi_mode_header_6 *mh6;
6791
6792		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6793		bd_len = mh6->blk_desc_len;
6794		break;
6795	}
6796	case MODE_SELECT_10: {
6797		struct scsi_mode_header_10 *mh10;
6798
6799		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6800		bd_len = scsi_2btoul(mh10->blk_desc_len);
6801		break;
6802	}
6803	default:
6804		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6805		break;
6806	}
6807
6808	if (param_len < (header_size + bd_len)) {
6809		free(ctsio->kern_data_ptr, M_CTL);
6810		ctl_set_param_len_error(ctsio);
6811		ctl_done((union ctl_io *)ctsio);
6812		return (CTL_RETVAL_COMPLETE);
6813	}
6814
6815	/*
6816	 * Set the IO_CONT flag, so that if this I/O gets passed to
6817	 * ctl_config_write_done(), it'll get passed back to
6818	 * ctl_do_mode_select() for further processing, or completion if
6819	 * we're all done.
6820	 */
6821	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6822	ctsio->io_cont = ctl_do_mode_select;
6823
6824	modepage_info = (union ctl_modepage_info *)
6825		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6826
6827	memset(modepage_info, 0, sizeof(*modepage_info));
6828
6829	len_left = param_len - header_size - bd_len;
6830	len_used = header_size + bd_len;
6831
6832	modepage_info->header.len_left = len_left;
6833	modepage_info->header.len_used = len_used;
6834
6835	return (ctl_do_mode_select((union ctl_io *)ctsio));
6836}
6837
6838int
6839ctl_mode_sense(struct ctl_scsiio *ctsio)
6840{
6841	struct ctl_lun *lun;
6842	int pc, page_code, dbd, llba, subpage;
6843	int alloc_len, page_len, header_len, total_len;
6844	struct scsi_mode_block_descr *block_desc;
6845	struct ctl_page_index *page_index;
6846	int control_dev;
6847
6848	dbd = 0;
6849	llba = 0;
6850	block_desc = NULL;
6851	page_index = NULL;
6852
6853	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6854
6855	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6856
6857	if (lun->be_lun->lun_type != T_DIRECT)
6858		control_dev = 1;
6859	else
6860		control_dev = 0;
6861
6862	if (lun->flags & CTL_LUN_PR_RESERVED) {
6863		uint32_t residx;
6864
6865		/*
6866		 * XXX KDM need a lock here.
6867		 */
6868		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6869		if ((lun->res_type == SPR_TYPE_EX_AC
6870		  && residx != lun->pr_res_idx)
6871		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6872		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6873		  && !lun->per_res[residx].registered)) {
6874			ctl_set_reservation_conflict(ctsio);
6875			ctl_done((union ctl_io *)ctsio);
6876			return (CTL_RETVAL_COMPLETE);
6877		}
6878	}
6879
6880	switch (ctsio->cdb[0]) {
6881	case MODE_SENSE_6: {
6882		struct scsi_mode_sense_6 *cdb;
6883
6884		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6885
6886		header_len = sizeof(struct scsi_mode_hdr_6);
6887		if (cdb->byte2 & SMS_DBD)
6888			dbd = 1;
6889		else
6890			header_len += sizeof(struct scsi_mode_block_descr);
6891
6892		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6893		page_code = cdb->page & SMS_PAGE_CODE;
6894		subpage = cdb->subpage;
6895		alloc_len = cdb->length;
6896		break;
6897	}
6898	case MODE_SENSE_10: {
6899		struct scsi_mode_sense_10 *cdb;
6900
6901		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6902
6903		header_len = sizeof(struct scsi_mode_hdr_10);
6904
6905		if (cdb->byte2 & SMS_DBD)
6906			dbd = 1;
6907		else
6908			header_len += sizeof(struct scsi_mode_block_descr);
6909		if (cdb->byte2 & SMS10_LLBAA)
6910			llba = 1;
6911		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6912		page_code = cdb->page & SMS_PAGE_CODE;
6913		subpage = cdb->subpage;
6914		alloc_len = scsi_2btoul(cdb->length);
6915		break;
6916	}
6917	default:
6918		ctl_set_invalid_opcode(ctsio);
6919		ctl_done((union ctl_io *)ctsio);
6920		return (CTL_RETVAL_COMPLETE);
6921		break; /* NOTREACHED */
6922	}
6923
6924	/*
6925	 * We have to make a first pass through to calculate the size of
6926	 * the pages that match the user's query.  Then we allocate enough
6927	 * memory to hold it, and actually copy the data into the buffer.
6928	 */
6929	switch (page_code) {
6930	case SMS_ALL_PAGES_PAGE: {
6931		int i;
6932
6933		page_len = 0;
6934
6935		/*
6936		 * At the moment, values other than 0 and 0xff here are
6937		 * reserved according to SPC-3.
6938		 */
6939		if ((subpage != SMS_SUBPAGE_PAGE_0)
6940		 && (subpage != SMS_SUBPAGE_ALL)) {
6941			ctl_set_invalid_field(ctsio,
6942					      /*sks_valid*/ 1,
6943					      /*command*/ 1,
6944					      /*field*/ 3,
6945					      /*bit_valid*/ 0,
6946					      /*bit*/ 0);
6947			ctl_done((union ctl_io *)ctsio);
6948			return (CTL_RETVAL_COMPLETE);
6949		}
6950
6951		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6952			if ((control_dev != 0)
6953			 && (lun->mode_pages.index[i].page_flags &
6954			     CTL_PAGE_FLAG_DISK_ONLY))
6955				continue;
6956
6957			/*
6958			 * We don't use this subpage if the user didn't
6959			 * request all subpages.
6960			 */
6961			if ((lun->mode_pages.index[i].subpage != 0)
6962			 && (subpage == SMS_SUBPAGE_PAGE_0))
6963				continue;
6964
6965#if 0
6966			printf("found page %#x len %d\n",
6967			       lun->mode_pages.index[i].page_code &
6968			       SMPH_PC_MASK,
6969			       lun->mode_pages.index[i].page_len);
6970#endif
6971			page_len += lun->mode_pages.index[i].page_len;
6972		}
6973		break;
6974	}
6975	default: {
6976		int i;
6977
6978		page_len = 0;
6979
6980		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6981			/* Look for the right page code */
6982			if ((lun->mode_pages.index[i].page_code &
6983			     SMPH_PC_MASK) != page_code)
6984				continue;
6985
6986			/* Look for the right subpage or the subpage wildcard*/
6987			if ((lun->mode_pages.index[i].subpage != subpage)
6988			 && (subpage != SMS_SUBPAGE_ALL))
6989				continue;
6990
6991			/* Make sure the page is supported for this dev type */
6992			if ((control_dev != 0)
6993			 && (lun->mode_pages.index[i].page_flags &
6994			     CTL_PAGE_FLAG_DISK_ONLY))
6995				continue;
6996
6997#if 0
6998			printf("found page %#x len %d\n",
6999			       lun->mode_pages.index[i].page_code &
7000			       SMPH_PC_MASK,
7001			       lun->mode_pages.index[i].page_len);
7002#endif
7003
7004			page_len += lun->mode_pages.index[i].page_len;
7005		}
7006
7007		if (page_len == 0) {
7008			ctl_set_invalid_field(ctsio,
7009					      /*sks_valid*/ 1,
7010					      /*command*/ 1,
7011					      /*field*/ 2,
7012					      /*bit_valid*/ 1,
7013					      /*bit*/ 5);
7014			ctl_done((union ctl_io *)ctsio);
7015			return (CTL_RETVAL_COMPLETE);
7016		}
7017		break;
7018	}
7019	}
7020
7021	total_len = header_len + page_len;
7022#if 0
7023	printf("header_len = %d, page_len = %d, total_len = %d\n",
7024	       header_len, page_len, total_len);
7025#endif
7026
7027	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7028	ctsio->kern_sg_entries = 0;
7029	ctsio->kern_data_resid = 0;
7030	ctsio->kern_rel_offset = 0;
7031	if (total_len < alloc_len) {
7032		ctsio->residual = alloc_len - total_len;
7033		ctsio->kern_data_len = total_len;
7034		ctsio->kern_total_len = total_len;
7035	} else {
7036		ctsio->residual = 0;
7037		ctsio->kern_data_len = alloc_len;
7038		ctsio->kern_total_len = alloc_len;
7039	}
7040
7041	switch (ctsio->cdb[0]) {
7042	case MODE_SENSE_6: {
7043		struct scsi_mode_hdr_6 *header;
7044
7045		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7046
7047		header->datalen = ctl_min(total_len - 1, 254);
7048		if (control_dev == 0)
7049			header->dev_specific = 0x10; /* DPOFUA */
7050		if (dbd)
7051			header->block_descr_len = 0;
7052		else
7053			header->block_descr_len =
7054				sizeof(struct scsi_mode_block_descr);
7055		block_desc = (struct scsi_mode_block_descr *)&header[1];
7056		break;
7057	}
7058	case MODE_SENSE_10: {
7059		struct scsi_mode_hdr_10 *header;
7060		int datalen;
7061
7062		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7063
7064		datalen = ctl_min(total_len - 2, 65533);
7065		scsi_ulto2b(datalen, header->datalen);
7066		if (control_dev == 0)
7067			header->dev_specific = 0x10; /* DPOFUA */
7068		if (dbd)
7069			scsi_ulto2b(0, header->block_descr_len);
7070		else
7071			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7072				    header->block_descr_len);
7073		block_desc = (struct scsi_mode_block_descr *)&header[1];
7074		break;
7075	}
7076	default:
7077		panic("invalid CDB type %#x", ctsio->cdb[0]);
7078		break; /* NOTREACHED */
7079	}
7080
7081	/*
7082	 * If we've got a disk, use its blocksize in the block
7083	 * descriptor.  Otherwise, just set it to 0.
7084	 */
7085	if (dbd == 0) {
7086		if (control_dev == 0)
7087			scsi_ulto3b(lun->be_lun->blocksize,
7088				    block_desc->block_len);
7089		else
7090			scsi_ulto3b(0, block_desc->block_len);
7091	}
7092
7093	switch (page_code) {
7094	case SMS_ALL_PAGES_PAGE: {
7095		int i, data_used;
7096
7097		data_used = header_len;
7098		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7099			struct ctl_page_index *page_index;
7100
7101			page_index = &lun->mode_pages.index[i];
7102
7103			if ((control_dev != 0)
7104			 && (page_index->page_flags &
7105			    CTL_PAGE_FLAG_DISK_ONLY))
7106				continue;
7107
7108			/*
7109			 * We don't use this subpage if the user didn't
7110			 * request all subpages.  We already checked (above)
7111			 * to make sure the user only specified a subpage
7112			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7113			 */
7114			if ((page_index->subpage != 0)
7115			 && (subpage == SMS_SUBPAGE_PAGE_0))
7116				continue;
7117
7118			/*
7119			 * Call the handler, if it exists, to update the
7120			 * page to the latest values.
7121			 */
7122			if (page_index->sense_handler != NULL)
7123				page_index->sense_handler(ctsio, page_index,pc);
7124
7125			memcpy(ctsio->kern_data_ptr + data_used,
7126			       page_index->page_data +
7127			       (page_index->page_len * pc),
7128			       page_index->page_len);
7129			data_used += page_index->page_len;
7130		}
7131		break;
7132	}
7133	default: {
7134		int i, data_used;
7135
7136		data_used = header_len;
7137
7138		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7139			struct ctl_page_index *page_index;
7140
7141			page_index = &lun->mode_pages.index[i];
7142
7143			/* Look for the right page code */
7144			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7145				continue;
7146
7147			/* Look for the right subpage or the subpage wildcard*/
7148			if ((page_index->subpage != subpage)
7149			 && (subpage != SMS_SUBPAGE_ALL))
7150				continue;
7151
7152			/* Make sure the page is supported for this dev type */
7153			if ((control_dev != 0)
7154			 && (page_index->page_flags &
7155			     CTL_PAGE_FLAG_DISK_ONLY))
7156				continue;
7157
7158			/*
7159			 * Call the handler, if it exists, to update the
7160			 * page to the latest values.
7161			 */
7162			if (page_index->sense_handler != NULL)
7163				page_index->sense_handler(ctsio, page_index,pc);
7164
7165			memcpy(ctsio->kern_data_ptr + data_used,
7166			       page_index->page_data +
7167			       (page_index->page_len * pc),
7168			       page_index->page_len);
7169			data_used += page_index->page_len;
7170		}
7171		break;
7172	}
7173	}
7174
7175	ctsio->scsi_status = SCSI_STATUS_OK;
7176
7177	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7178	ctsio->be_move_done = ctl_config_move_done;
7179	ctl_datamove((union ctl_io *)ctsio);
7180
7181	return (CTL_RETVAL_COMPLETE);
7182}
7183
7184int
7185ctl_read_capacity(struct ctl_scsiio *ctsio)
7186{
7187	struct scsi_read_capacity *cdb;
7188	struct scsi_read_capacity_data *data;
7189	struct ctl_lun *lun;
7190	uint32_t lba;
7191
7192	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7193
7194	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7195
7196	lba = scsi_4btoul(cdb->addr);
7197	if (((cdb->pmi & SRC_PMI) == 0)
7198	 && (lba != 0)) {
7199		ctl_set_invalid_field(/*ctsio*/ ctsio,
7200				      /*sks_valid*/ 1,
7201				      /*command*/ 1,
7202				      /*field*/ 2,
7203				      /*bit_valid*/ 0,
7204				      /*bit*/ 0);
7205		ctl_done((union ctl_io *)ctsio);
7206		return (CTL_RETVAL_COMPLETE);
7207	}
7208
7209	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7210
7211	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7212	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7213	ctsio->residual = 0;
7214	ctsio->kern_data_len = sizeof(*data);
7215	ctsio->kern_total_len = sizeof(*data);
7216	ctsio->kern_data_resid = 0;
7217	ctsio->kern_rel_offset = 0;
7218	ctsio->kern_sg_entries = 0;
7219
7220	/*
7221	 * If the maximum LBA is greater than 0xfffffffe, the user must
7222	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7223	 * serivce action set.
7224	 */
7225	if (lun->be_lun->maxlba > 0xfffffffe)
7226		scsi_ulto4b(0xffffffff, data->addr);
7227	else
7228		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7229
7230	/*
7231	 * XXX KDM this may not be 512 bytes...
7232	 */
7233	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7234
7235	ctsio->scsi_status = SCSI_STATUS_OK;
7236
7237	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7238	ctsio->be_move_done = ctl_config_move_done;
7239	ctl_datamove((union ctl_io *)ctsio);
7240
7241	return (CTL_RETVAL_COMPLETE);
7242}
7243
7244int
7245ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7246{
7247	struct scsi_read_capacity_16 *cdb;
7248	struct scsi_read_capacity_data_long *data;
7249	struct ctl_lun *lun;
7250	uint64_t lba;
7251	uint32_t alloc_len;
7252
7253	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7254
7255	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7256
7257	alloc_len = scsi_4btoul(cdb->alloc_len);
7258	lba = scsi_8btou64(cdb->addr);
7259
7260	if ((cdb->reladr & SRC16_PMI)
7261	 && (lba != 0)) {
7262		ctl_set_invalid_field(/*ctsio*/ ctsio,
7263				      /*sks_valid*/ 1,
7264				      /*command*/ 1,
7265				      /*field*/ 2,
7266				      /*bit_valid*/ 0,
7267				      /*bit*/ 0);
7268		ctl_done((union ctl_io *)ctsio);
7269		return (CTL_RETVAL_COMPLETE);
7270	}
7271
7272	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7273
7274	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7275	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7276
7277	if (sizeof(*data) < alloc_len) {
7278		ctsio->residual = alloc_len - sizeof(*data);
7279		ctsio->kern_data_len = sizeof(*data);
7280		ctsio->kern_total_len = sizeof(*data);
7281	} else {
7282		ctsio->residual = 0;
7283		ctsio->kern_data_len = alloc_len;
7284		ctsio->kern_total_len = alloc_len;
7285	}
7286	ctsio->kern_data_resid = 0;
7287	ctsio->kern_rel_offset = 0;
7288	ctsio->kern_sg_entries = 0;
7289
7290	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7291	/* XXX KDM this may not be 512 bytes... */
7292	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7293	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7294	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7295	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7296		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7297
7298	ctsio->scsi_status = SCSI_STATUS_OK;
7299
7300	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7301	ctsio->be_move_done = ctl_config_move_done;
7302	ctl_datamove((union ctl_io *)ctsio);
7303
7304	return (CTL_RETVAL_COMPLETE);
7305}
7306
7307int
7308ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7309{
7310	struct scsi_maintenance_in *cdb;
7311	int retval;
7312	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7313	int num_target_port_groups, num_target_ports, single;
7314	struct ctl_lun *lun;
7315	struct ctl_softc *softc;
7316	struct ctl_port *port;
7317	struct scsi_target_group_data *rtg_ptr;
7318	struct scsi_target_group_data_extended *rtg_ext_ptr;
7319	struct scsi_target_port_group_descriptor *tpg_desc;
7320
7321	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7322
7323	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7324	softc = control_softc;
7325	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7326
7327	retval = CTL_RETVAL_COMPLETE;
7328
7329	switch (cdb->byte2 & STG_PDF_MASK) {
7330	case STG_PDF_LENGTH:
7331		ext = 0;
7332		break;
7333	case STG_PDF_EXTENDED:
7334		ext = 1;
7335		break;
7336	default:
7337		ctl_set_invalid_field(/*ctsio*/ ctsio,
7338				      /*sks_valid*/ 1,
7339				      /*command*/ 1,
7340				      /*field*/ 2,
7341				      /*bit_valid*/ 1,
7342				      /*bit*/ 5);
7343		ctl_done((union ctl_io *)ctsio);
7344		return(retval);
7345	}
7346
7347	single = ctl_is_single;
7348	if (single)
7349		num_target_port_groups = 1;
7350	else
7351		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7352	num_target_ports = 0;
7353	mtx_lock(&softc->ctl_lock);
7354	STAILQ_FOREACH(port, &softc->port_list, links) {
7355		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7356			continue;
7357		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7358			continue;
7359		num_target_ports++;
7360	}
7361	mtx_unlock(&softc->ctl_lock);
7362
7363	if (ext)
7364		total_len = sizeof(struct scsi_target_group_data_extended);
7365	else
7366		total_len = sizeof(struct scsi_target_group_data);
7367	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7368		num_target_port_groups +
7369	    sizeof(struct scsi_target_port_descriptor) *
7370		num_target_ports * num_target_port_groups;
7371
7372	alloc_len = scsi_4btoul(cdb->length);
7373
7374	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7375
7376	ctsio->kern_sg_entries = 0;
7377
7378	if (total_len < alloc_len) {
7379		ctsio->residual = alloc_len - total_len;
7380		ctsio->kern_data_len = total_len;
7381		ctsio->kern_total_len = total_len;
7382	} else {
7383		ctsio->residual = 0;
7384		ctsio->kern_data_len = alloc_len;
7385		ctsio->kern_total_len = alloc_len;
7386	}
7387	ctsio->kern_data_resid = 0;
7388	ctsio->kern_rel_offset = 0;
7389
7390	if (ext) {
7391		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7392		    ctsio->kern_data_ptr;
7393		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7394		rtg_ext_ptr->format_type = 0x10;
7395		rtg_ext_ptr->implicit_transition_time = 0;
7396		tpg_desc = &rtg_ext_ptr->groups[0];
7397	} else {
7398		rtg_ptr = (struct scsi_target_group_data *)
7399		    ctsio->kern_data_ptr;
7400		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7401		tpg_desc = &rtg_ptr->groups[0];
7402	}
7403
7404	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7405	mtx_lock(&softc->ctl_lock);
7406	for (g = 0; g < num_target_port_groups; g++) {
7407		if (g == pg)
7408			tpg_desc->pref_state = TPG_PRIMARY |
7409			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7410		else
7411			tpg_desc->pref_state =
7412			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7413		tpg_desc->support = TPG_AO_SUP;
7414		if (!single)
7415			tpg_desc->support |= TPG_AN_SUP;
7416		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7417		tpg_desc->status = TPG_IMPLICIT;
7418		pc = 0;
7419		STAILQ_FOREACH(port, &softc->port_list, links) {
7420			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7421				continue;
7422			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7423			    CTL_MAX_LUNS)
7424				continue;
7425			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7426			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7427			    relative_target_port_identifier);
7428			pc++;
7429		}
7430		tpg_desc->target_port_count = pc;
7431		tpg_desc = (struct scsi_target_port_group_descriptor *)
7432		    &tpg_desc->descriptors[pc];
7433	}
7434	mtx_unlock(&softc->ctl_lock);
7435
7436	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7437	ctsio->be_move_done = ctl_config_move_done;
7438
7439	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7440			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7441			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7442			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7443			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7444
7445	ctl_datamove((union ctl_io *)ctsio);
7446	return(retval);
7447}
7448
7449int
7450ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7451{
7452	struct ctl_lun *lun;
7453	struct scsi_report_supported_opcodes *cdb;
7454	const struct ctl_cmd_entry *entry, *sentry;
7455	struct scsi_report_supported_opcodes_all *all;
7456	struct scsi_report_supported_opcodes_descr *descr;
7457	struct scsi_report_supported_opcodes_one *one;
7458	int retval;
7459	int alloc_len, total_len;
7460	int opcode, service_action, i, j, num;
7461
7462	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7463
7464	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7465	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7466
7467	retval = CTL_RETVAL_COMPLETE;
7468
7469	opcode = cdb->requested_opcode;
7470	service_action = scsi_2btoul(cdb->requested_service_action);
7471	switch (cdb->options & RSO_OPTIONS_MASK) {
7472	case RSO_OPTIONS_ALL:
7473		num = 0;
7474		for (i = 0; i < 256; i++) {
7475			entry = &ctl_cmd_table[i];
7476			if (entry->flags & CTL_CMD_FLAG_SA5) {
7477				for (j = 0; j < 32; j++) {
7478					sentry = &((const struct ctl_cmd_entry *)
7479					    entry->execute)[j];
7480					if (ctl_cmd_applicable(
7481					    lun->be_lun->lun_type, sentry))
7482						num++;
7483				}
7484			} else {
7485				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7486				    entry))
7487					num++;
7488			}
7489		}
7490		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7491		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7492		break;
7493	case RSO_OPTIONS_OC:
7494		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7495			ctl_set_invalid_field(/*ctsio*/ ctsio,
7496					      /*sks_valid*/ 1,
7497					      /*command*/ 1,
7498					      /*field*/ 2,
7499					      /*bit_valid*/ 1,
7500					      /*bit*/ 2);
7501			ctl_done((union ctl_io *)ctsio);
7502			return (CTL_RETVAL_COMPLETE);
7503		}
7504		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7505		break;
7506	case RSO_OPTIONS_OC_SA:
7507		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7508		    service_action >= 32) {
7509			ctl_set_invalid_field(/*ctsio*/ ctsio,
7510					      /*sks_valid*/ 1,
7511					      /*command*/ 1,
7512					      /*field*/ 2,
7513					      /*bit_valid*/ 1,
7514					      /*bit*/ 2);
7515			ctl_done((union ctl_io *)ctsio);
7516			return (CTL_RETVAL_COMPLETE);
7517		}
7518		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7519		break;
7520	default:
7521		ctl_set_invalid_field(/*ctsio*/ ctsio,
7522				      /*sks_valid*/ 1,
7523				      /*command*/ 1,
7524				      /*field*/ 2,
7525				      /*bit_valid*/ 1,
7526				      /*bit*/ 2);
7527		ctl_done((union ctl_io *)ctsio);
7528		return (CTL_RETVAL_COMPLETE);
7529	}
7530
7531	alloc_len = scsi_4btoul(cdb->length);
7532
7533	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7534
7535	ctsio->kern_sg_entries = 0;
7536
7537	if (total_len < alloc_len) {
7538		ctsio->residual = alloc_len - total_len;
7539		ctsio->kern_data_len = total_len;
7540		ctsio->kern_total_len = total_len;
7541	} else {
7542		ctsio->residual = 0;
7543		ctsio->kern_data_len = alloc_len;
7544		ctsio->kern_total_len = alloc_len;
7545	}
7546	ctsio->kern_data_resid = 0;
7547	ctsio->kern_rel_offset = 0;
7548
7549	switch (cdb->options & RSO_OPTIONS_MASK) {
7550	case RSO_OPTIONS_ALL:
7551		all = (struct scsi_report_supported_opcodes_all *)
7552		    ctsio->kern_data_ptr;
7553		num = 0;
7554		for (i = 0; i < 256; i++) {
7555			entry = &ctl_cmd_table[i];
7556			if (entry->flags & CTL_CMD_FLAG_SA5) {
7557				for (j = 0; j < 32; j++) {
7558					sentry = &((const struct ctl_cmd_entry *)
7559					    entry->execute)[j];
7560					if (!ctl_cmd_applicable(
7561					    lun->be_lun->lun_type, sentry))
7562						continue;
7563					descr = &all->descr[num++];
7564					descr->opcode = i;
7565					scsi_ulto2b(j, descr->service_action);
7566					descr->flags = RSO_SERVACTV;
7567					scsi_ulto2b(sentry->length,
7568					    descr->cdb_length);
7569				}
7570			} else {
7571				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7572				    entry))
7573					continue;
7574				descr = &all->descr[num++];
7575				descr->opcode = i;
7576				scsi_ulto2b(0, descr->service_action);
7577				descr->flags = 0;
7578				scsi_ulto2b(entry->length, descr->cdb_length);
7579			}
7580		}
7581		scsi_ulto4b(
7582		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7583		    all->length);
7584		break;
7585	case RSO_OPTIONS_OC:
7586		one = (struct scsi_report_supported_opcodes_one *)
7587		    ctsio->kern_data_ptr;
7588		entry = &ctl_cmd_table[opcode];
7589		goto fill_one;
7590	case RSO_OPTIONS_OC_SA:
7591		one = (struct scsi_report_supported_opcodes_one *)
7592		    ctsio->kern_data_ptr;
7593		entry = &ctl_cmd_table[opcode];
7594		entry = &((const struct ctl_cmd_entry *)
7595		    entry->execute)[service_action];
7596fill_one:
7597		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7598			one->support = 3;
7599			scsi_ulto2b(entry->length, one->cdb_length);
7600			one->cdb_usage[0] = opcode;
7601			memcpy(&one->cdb_usage[1], entry->usage,
7602			    entry->length - 1);
7603		} else
7604			one->support = 1;
7605		break;
7606	}
7607
7608	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7609	ctsio->be_move_done = ctl_config_move_done;
7610
7611	ctl_datamove((union ctl_io *)ctsio);
7612	return(retval);
7613}
7614
7615int
7616ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7617{
7618	struct ctl_lun *lun;
7619	struct scsi_report_supported_tmf *cdb;
7620	struct scsi_report_supported_tmf_data *data;
7621	int retval;
7622	int alloc_len, total_len;
7623
7624	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7625
7626	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7627	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7628
7629	retval = CTL_RETVAL_COMPLETE;
7630
7631	total_len = sizeof(struct scsi_report_supported_tmf_data);
7632	alloc_len = scsi_4btoul(cdb->length);
7633
7634	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7635
7636	ctsio->kern_sg_entries = 0;
7637
7638	if (total_len < alloc_len) {
7639		ctsio->residual = alloc_len - total_len;
7640		ctsio->kern_data_len = total_len;
7641		ctsio->kern_total_len = total_len;
7642	} else {
7643		ctsio->residual = 0;
7644		ctsio->kern_data_len = alloc_len;
7645		ctsio->kern_total_len = alloc_len;
7646	}
7647	ctsio->kern_data_resid = 0;
7648	ctsio->kern_rel_offset = 0;
7649
7650	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7651	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7652	data->byte2 |= RST_ITNRS;
7653
7654	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7655	ctsio->be_move_done = ctl_config_move_done;
7656
7657	ctl_datamove((union ctl_io *)ctsio);
7658	return (retval);
7659}
7660
7661int
7662ctl_report_timestamp(struct ctl_scsiio *ctsio)
7663{
7664	struct ctl_lun *lun;
7665	struct scsi_report_timestamp *cdb;
7666	struct scsi_report_timestamp_data *data;
7667	struct timeval tv;
7668	int64_t timestamp;
7669	int retval;
7670	int alloc_len, total_len;
7671
7672	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7673
7674	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7675	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7676
7677	retval = CTL_RETVAL_COMPLETE;
7678
7679	total_len = sizeof(struct scsi_report_timestamp_data);
7680	alloc_len = scsi_4btoul(cdb->length);
7681
7682	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7683
7684	ctsio->kern_sg_entries = 0;
7685
7686	if (total_len < alloc_len) {
7687		ctsio->residual = alloc_len - total_len;
7688		ctsio->kern_data_len = total_len;
7689		ctsio->kern_total_len = total_len;
7690	} else {
7691		ctsio->residual = 0;
7692		ctsio->kern_data_len = alloc_len;
7693		ctsio->kern_total_len = alloc_len;
7694	}
7695	ctsio->kern_data_resid = 0;
7696	ctsio->kern_rel_offset = 0;
7697
7698	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7699	scsi_ulto2b(sizeof(*data) - 2, data->length);
7700	data->origin = RTS_ORIG_OUTSIDE;
7701	getmicrotime(&tv);
7702	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7703	scsi_ulto4b(timestamp >> 16, data->timestamp);
7704	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7705
7706	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7707	ctsio->be_move_done = ctl_config_move_done;
7708
7709	ctl_datamove((union ctl_io *)ctsio);
7710	return (retval);
7711}
7712
7713int
7714ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7715{
7716	struct scsi_per_res_in *cdb;
7717	int alloc_len, total_len = 0;
7718	/* struct scsi_per_res_in_rsrv in_data; */
7719	struct ctl_lun *lun;
7720	struct ctl_softc *softc;
7721
7722	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7723
7724	softc = control_softc;
7725
7726	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7727
7728	alloc_len = scsi_2btoul(cdb->length);
7729
7730	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7731
7732retry:
7733	mtx_lock(&lun->lun_lock);
7734	switch (cdb->action) {
7735	case SPRI_RK: /* read keys */
7736		total_len = sizeof(struct scsi_per_res_in_keys) +
7737			lun->pr_key_count *
7738			sizeof(struct scsi_per_res_key);
7739		break;
7740	case SPRI_RR: /* read reservation */
7741		if (lun->flags & CTL_LUN_PR_RESERVED)
7742			total_len = sizeof(struct scsi_per_res_in_rsrv);
7743		else
7744			total_len = sizeof(struct scsi_per_res_in_header);
7745		break;
7746	case SPRI_RC: /* report capabilities */
7747		total_len = sizeof(struct scsi_per_res_cap);
7748		break;
7749	case SPRI_RS: /* read full status */
7750		total_len = sizeof(struct scsi_per_res_in_header) +
7751		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7752		    lun->pr_key_count;
7753		break;
7754	default:
7755		panic("Invalid PR type %x", cdb->action);
7756	}
7757	mtx_unlock(&lun->lun_lock);
7758
7759	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7760
7761	if (total_len < alloc_len) {
7762		ctsio->residual = alloc_len - total_len;
7763		ctsio->kern_data_len = total_len;
7764		ctsio->kern_total_len = total_len;
7765	} else {
7766		ctsio->residual = 0;
7767		ctsio->kern_data_len = alloc_len;
7768		ctsio->kern_total_len = alloc_len;
7769	}
7770
7771	ctsio->kern_data_resid = 0;
7772	ctsio->kern_rel_offset = 0;
7773	ctsio->kern_sg_entries = 0;
7774
7775	mtx_lock(&lun->lun_lock);
7776	switch (cdb->action) {
7777	case SPRI_RK: { // read keys
7778        struct scsi_per_res_in_keys *res_keys;
7779		int i, key_count;
7780
7781		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7782
7783		/*
7784		 * We had to drop the lock to allocate our buffer, which
7785		 * leaves time for someone to come in with another
7786		 * persistent reservation.  (That is unlikely, though,
7787		 * since this should be the only persistent reservation
7788		 * command active right now.)
7789		 */
7790		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7791		    (lun->pr_key_count *
7792		     sizeof(struct scsi_per_res_key)))){
7793			mtx_unlock(&lun->lun_lock);
7794			free(ctsio->kern_data_ptr, M_CTL);
7795			printf("%s: reservation length changed, retrying\n",
7796			       __func__);
7797			goto retry;
7798		}
7799
7800		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7801
7802		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7803			     lun->pr_key_count, res_keys->header.length);
7804
7805		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7806			if (!lun->per_res[i].registered)
7807				continue;
7808
7809			/*
7810			 * We used lun->pr_key_count to calculate the
7811			 * size to allocate.  If it turns out the number of
7812			 * initiators with the registered flag set is
7813			 * larger than that (i.e. they haven't been kept in
7814			 * sync), we've got a problem.
7815			 */
7816			if (key_count >= lun->pr_key_count) {
7817#ifdef NEEDTOPORT
7818				csevent_log(CSC_CTL | CSC_SHELF_SW |
7819					    CTL_PR_ERROR,
7820					    csevent_LogType_Fault,
7821					    csevent_AlertLevel_Yellow,
7822					    csevent_FRU_ShelfController,
7823					    csevent_FRU_Firmware,
7824				        csevent_FRU_Unknown,
7825					    "registered keys %d >= key "
7826					    "count %d", key_count,
7827					    lun->pr_key_count);
7828#endif
7829				key_count++;
7830				continue;
7831			}
7832			memcpy(res_keys->keys[key_count].key,
7833			       lun->per_res[i].res_key.key,
7834			       ctl_min(sizeof(res_keys->keys[key_count].key),
7835			       sizeof(lun->per_res[i].res_key)));
7836			key_count++;
7837		}
7838		break;
7839	}
7840	case SPRI_RR: { // read reservation
7841		struct scsi_per_res_in_rsrv *res;
7842		int tmp_len, header_only;
7843
7844		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7845
7846		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7847
7848		if (lun->flags & CTL_LUN_PR_RESERVED)
7849		{
7850			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7851			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7852				    res->header.length);
7853			header_only = 0;
7854		} else {
7855			tmp_len = sizeof(struct scsi_per_res_in_header);
7856			scsi_ulto4b(0, res->header.length);
7857			header_only = 1;
7858		}
7859
7860		/*
7861		 * We had to drop the lock to allocate our buffer, which
7862		 * leaves time for someone to come in with another
7863		 * persistent reservation.  (That is unlikely, though,
7864		 * since this should be the only persistent reservation
7865		 * command active right now.)
7866		 */
7867		if (tmp_len != total_len) {
7868			mtx_unlock(&lun->lun_lock);
7869			free(ctsio->kern_data_ptr, M_CTL);
7870			printf("%s: reservation status changed, retrying\n",
7871			       __func__);
7872			goto retry;
7873		}
7874
7875		/*
7876		 * No reservation held, so we're done.
7877		 */
7878		if (header_only != 0)
7879			break;
7880
7881		/*
7882		 * If the registration is an All Registrants type, the key
7883		 * is 0, since it doesn't really matter.
7884		 */
7885		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7886			memcpy(res->data.reservation,
7887			       &lun->per_res[lun->pr_res_idx].res_key,
7888			       sizeof(struct scsi_per_res_key));
7889		}
7890		res->data.scopetype = lun->res_type;
7891		break;
7892	}
7893	case SPRI_RC:     //report capabilities
7894	{
7895		struct scsi_per_res_cap *res_cap;
7896		uint16_t type_mask;
7897
7898		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7899		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7900		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7901		type_mask = SPRI_TM_WR_EX_AR |
7902			    SPRI_TM_EX_AC_RO |
7903			    SPRI_TM_WR_EX_RO |
7904			    SPRI_TM_EX_AC |
7905			    SPRI_TM_WR_EX |
7906			    SPRI_TM_EX_AC_AR;
7907		scsi_ulto2b(type_mask, res_cap->type_mask);
7908		break;
7909	}
7910	case SPRI_RS: { // read full status
7911		struct scsi_per_res_in_full *res_status;
7912		struct scsi_per_res_in_full_desc *res_desc;
7913		struct ctl_port *port;
7914		int i, len;
7915
7916		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7917
7918		/*
7919		 * We had to drop the lock to allocate our buffer, which
7920		 * leaves time for someone to come in with another
7921		 * persistent reservation.  (That is unlikely, though,
7922		 * since this should be the only persistent reservation
7923		 * command active right now.)
7924		 */
7925		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7926		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7927		     lun->pr_key_count)){
7928			mtx_unlock(&lun->lun_lock);
7929			free(ctsio->kern_data_ptr, M_CTL);
7930			printf("%s: reservation length changed, retrying\n",
7931			       __func__);
7932			goto retry;
7933		}
7934
7935		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7936
7937		res_desc = &res_status->desc[0];
7938		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7939			if (!lun->per_res[i].registered)
7940				continue;
7941
7942			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7943			    sizeof(res_desc->res_key));
7944			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7945			    (lun->pr_res_idx == i ||
7946			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7947				res_desc->flags = SPRI_FULL_R_HOLDER;
7948				res_desc->scopetype = lun->res_type;
7949			}
7950			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7951			    res_desc->rel_trgt_port_id);
7952			len = 0;
7953			port = softc->ctl_ports[
7954			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7955			if (port != NULL)
7956				len = ctl_create_iid(port,
7957				    i % CTL_MAX_INIT_PER_PORT,
7958				    res_desc->transport_id);
7959			scsi_ulto4b(len, res_desc->additional_length);
7960			res_desc = (struct scsi_per_res_in_full_desc *)
7961			    &res_desc->transport_id[len];
7962		}
7963		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7964		    res_status->header.length);
7965		break;
7966	}
7967	default:
7968		/*
7969		 * This is a bug, because we just checked for this above,
7970		 * and should have returned an error.
7971		 */
7972		panic("Invalid PR type %x", cdb->action);
7973		break; /* NOTREACHED */
7974	}
7975	mtx_unlock(&lun->lun_lock);
7976
7977	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7978	ctsio->be_move_done = ctl_config_move_done;
7979
7980	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7981			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7982			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7983			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7984			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7985
7986	ctl_datamove((union ctl_io *)ctsio);
7987
7988	return (CTL_RETVAL_COMPLETE);
7989}
7990
7991/*
7992 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7993 * it should return.
7994 */
7995static int
7996ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7997		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7998		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7999		struct scsi_per_res_out_parms* param)
8000{
8001	union ctl_ha_msg persis_io;
8002	int retval, i;
8003	int isc_retval;
8004
8005	retval = 0;
8006
8007	mtx_lock(&lun->lun_lock);
8008	if (sa_res_key == 0) {
8009		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8010			/* validate scope and type */
8011			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8012			     SPR_LU_SCOPE) {
8013				mtx_unlock(&lun->lun_lock);
8014				ctl_set_invalid_field(/*ctsio*/ ctsio,
8015						      /*sks_valid*/ 1,
8016						      /*command*/ 1,
8017						      /*field*/ 2,
8018						      /*bit_valid*/ 1,
8019						      /*bit*/ 4);
8020				ctl_done((union ctl_io *)ctsio);
8021				return (1);
8022			}
8023
8024		        if (type>8 || type==2 || type==4 || type==0) {
8025				mtx_unlock(&lun->lun_lock);
8026				ctl_set_invalid_field(/*ctsio*/ ctsio,
8027       	           				      /*sks_valid*/ 1,
8028						      /*command*/ 1,
8029						      /*field*/ 2,
8030						      /*bit_valid*/ 1,
8031						      /*bit*/ 0);
8032				ctl_done((union ctl_io *)ctsio);
8033				return (1);
8034		        }
8035
8036			/* temporarily unregister this nexus */
8037			lun->per_res[residx].registered = 0;
8038
8039			/*
8040			 * Unregister everybody else and build UA for
8041			 * them
8042			 */
8043			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8044				if (lun->per_res[i].registered == 0)
8045					continue;
8046
8047				if (!persis_offset
8048				 && i <CTL_MAX_INITIATORS)
8049					lun->pending_ua[i] |=
8050						CTL_UA_REG_PREEMPT;
8051				else if (persis_offset
8052				      && i >= persis_offset)
8053					lun->pending_ua[i-persis_offset] |=
8054						CTL_UA_REG_PREEMPT;
8055				lun->per_res[i].registered = 0;
8056				memset(&lun->per_res[i].res_key, 0,
8057				       sizeof(struct scsi_per_res_key));
8058			}
8059			lun->per_res[residx].registered = 1;
8060			lun->pr_key_count = 1;
8061			lun->res_type = type;
8062			if (lun->res_type != SPR_TYPE_WR_EX_AR
8063			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8064				lun->pr_res_idx = residx;
8065
8066			/* send msg to other side */
8067			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8068			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8069			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8070			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8071			persis_io.pr.pr_info.res_type = type;
8072			memcpy(persis_io.pr.pr_info.sa_res_key,
8073			       param->serv_act_res_key,
8074			       sizeof(param->serv_act_res_key));
8075			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8076			     &persis_io, sizeof(persis_io), 0)) >
8077			     CTL_HA_STATUS_SUCCESS) {
8078				printf("CTL:Persis Out error returned "
8079				       "from ctl_ha_msg_send %d\n",
8080				       isc_retval);
8081			}
8082		} else {
8083			/* not all registrants */
8084			mtx_unlock(&lun->lun_lock);
8085			free(ctsio->kern_data_ptr, M_CTL);
8086			ctl_set_invalid_field(ctsio,
8087					      /*sks_valid*/ 1,
8088					      /*command*/ 0,
8089					      /*field*/ 8,
8090					      /*bit_valid*/ 0,
8091					      /*bit*/ 0);
8092			ctl_done((union ctl_io *)ctsio);
8093			return (1);
8094		}
8095	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8096		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8097		int found = 0;
8098
8099		if (res_key == sa_res_key) {
8100			/* special case */
8101			/*
8102			 * The spec implies this is not good but doesn't
8103			 * say what to do. There are two choices either
8104			 * generate a res conflict or check condition
8105			 * with illegal field in parameter data. Since
8106			 * that is what is done when the sa_res_key is
8107			 * zero I'll take that approach since this has
8108			 * to do with the sa_res_key.
8109			 */
8110			mtx_unlock(&lun->lun_lock);
8111			free(ctsio->kern_data_ptr, M_CTL);
8112			ctl_set_invalid_field(ctsio,
8113					      /*sks_valid*/ 1,
8114					      /*command*/ 0,
8115					      /*field*/ 8,
8116					      /*bit_valid*/ 0,
8117					      /*bit*/ 0);
8118			ctl_done((union ctl_io *)ctsio);
8119			return (1);
8120		}
8121
8122		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8123			if (lun->per_res[i].registered
8124			 && memcmp(param->serv_act_res_key,
8125			    lun->per_res[i].res_key.key,
8126			    sizeof(struct scsi_per_res_key)) != 0)
8127				continue;
8128
8129			found = 1;
8130			lun->per_res[i].registered = 0;
8131			memset(&lun->per_res[i].res_key, 0,
8132			       sizeof(struct scsi_per_res_key));
8133			lun->pr_key_count--;
8134
8135			if (!persis_offset && i < CTL_MAX_INITIATORS)
8136				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8137			else if (persis_offset && i >= persis_offset)
8138				lun->pending_ua[i-persis_offset] |=
8139					CTL_UA_REG_PREEMPT;
8140		}
8141		if (!found) {
8142			mtx_unlock(&lun->lun_lock);
8143			free(ctsio->kern_data_ptr, M_CTL);
8144			ctl_set_reservation_conflict(ctsio);
8145			ctl_done((union ctl_io *)ctsio);
8146			return (CTL_RETVAL_COMPLETE);
8147		}
8148		/* send msg to other side */
8149		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8150		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8151		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8152		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8153		persis_io.pr.pr_info.res_type = type;
8154		memcpy(persis_io.pr.pr_info.sa_res_key,
8155		       param->serv_act_res_key,
8156		       sizeof(param->serv_act_res_key));
8157		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8158		     &persis_io, sizeof(persis_io), 0)) >
8159		     CTL_HA_STATUS_SUCCESS) {
8160			printf("CTL:Persis Out error returned from "
8161			       "ctl_ha_msg_send %d\n", isc_retval);
8162		}
8163	} else {
8164		/* Reserved but not all registrants */
8165		/* sa_res_key is res holder */
8166		if (memcmp(param->serv_act_res_key,
8167                   lun->per_res[lun->pr_res_idx].res_key.key,
8168                   sizeof(struct scsi_per_res_key)) == 0) {
8169			/* validate scope and type */
8170			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8171			     SPR_LU_SCOPE) {
8172				mtx_unlock(&lun->lun_lock);
8173				ctl_set_invalid_field(/*ctsio*/ ctsio,
8174						      /*sks_valid*/ 1,
8175						      /*command*/ 1,
8176						      /*field*/ 2,
8177						      /*bit_valid*/ 1,
8178						      /*bit*/ 4);
8179				ctl_done((union ctl_io *)ctsio);
8180				return (1);
8181			}
8182
8183			if (type>8 || type==2 || type==4 || type==0) {
8184				mtx_unlock(&lun->lun_lock);
8185				ctl_set_invalid_field(/*ctsio*/ ctsio,
8186						      /*sks_valid*/ 1,
8187						      /*command*/ 1,
8188						      /*field*/ 2,
8189						      /*bit_valid*/ 1,
8190						      /*bit*/ 0);
8191				ctl_done((union ctl_io *)ctsio);
8192				return (1);
8193			}
8194
8195			/*
8196			 * Do the following:
8197			 * if sa_res_key != res_key remove all
8198			 * registrants w/sa_res_key and generate UA
8199			 * for these registrants(Registrations
8200			 * Preempted) if it wasn't an exclusive
8201			 * reservation generate UA(Reservations
8202			 * Preempted) for all other registered nexuses
8203			 * if the type has changed. Establish the new
8204			 * reservation and holder. If res_key and
8205			 * sa_res_key are the same do the above
8206			 * except don't unregister the res holder.
8207			 */
8208
8209			/*
8210			 * Temporarily unregister so it won't get
8211			 * removed or UA generated
8212			 */
8213			lun->per_res[residx].registered = 0;
8214			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8215				if (lun->per_res[i].registered == 0)
8216					continue;
8217
8218				if (memcmp(param->serv_act_res_key,
8219				    lun->per_res[i].res_key.key,
8220				    sizeof(struct scsi_per_res_key)) == 0) {
8221					lun->per_res[i].registered = 0;
8222					memset(&lun->per_res[i].res_key,
8223					       0,
8224					       sizeof(struct scsi_per_res_key));
8225					lun->pr_key_count--;
8226
8227					if (!persis_offset
8228					 && i < CTL_MAX_INITIATORS)
8229						lun->pending_ua[i] |=
8230							CTL_UA_REG_PREEMPT;
8231					else if (persis_offset
8232					      && i >= persis_offset)
8233						lun->pending_ua[i-persis_offset] |=
8234						  CTL_UA_REG_PREEMPT;
8235				} else if (type != lun->res_type
8236					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8237					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8238						if (!persis_offset
8239						 && i < CTL_MAX_INITIATORS)
8240							lun->pending_ua[i] |=
8241							CTL_UA_RES_RELEASE;
8242						else if (persis_offset
8243						      && i >= persis_offset)
8244							lun->pending_ua[
8245							i-persis_offset] |=
8246							CTL_UA_RES_RELEASE;
8247				}
8248			}
8249			lun->per_res[residx].registered = 1;
8250			lun->res_type = type;
8251			if (lun->res_type != SPR_TYPE_WR_EX_AR
8252			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8253				lun->pr_res_idx = residx;
8254			else
8255				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8256
8257			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8258			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8259			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8260			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8261			persis_io.pr.pr_info.res_type = type;
8262			memcpy(persis_io.pr.pr_info.sa_res_key,
8263			       param->serv_act_res_key,
8264			       sizeof(param->serv_act_res_key));
8265			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8266			     &persis_io, sizeof(persis_io), 0)) >
8267			     CTL_HA_STATUS_SUCCESS) {
8268				printf("CTL:Persis Out error returned "
8269				       "from ctl_ha_msg_send %d\n",
8270				       isc_retval);
8271			}
8272		} else {
8273			/*
8274			 * sa_res_key is not the res holder just
8275			 * remove registrants
8276			 */
8277			int found=0;
8278
8279			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8280				if (memcmp(param->serv_act_res_key,
8281				    lun->per_res[i].res_key.key,
8282				    sizeof(struct scsi_per_res_key)) != 0)
8283					continue;
8284
8285				found = 1;
8286				lun->per_res[i].registered = 0;
8287				memset(&lun->per_res[i].res_key, 0,
8288				       sizeof(struct scsi_per_res_key));
8289				lun->pr_key_count--;
8290
8291				if (!persis_offset
8292				 && i < CTL_MAX_INITIATORS)
8293					lun->pending_ua[i] |=
8294						CTL_UA_REG_PREEMPT;
8295				else if (persis_offset
8296				      && i >= persis_offset)
8297					lun->pending_ua[i-persis_offset] |=
8298						CTL_UA_REG_PREEMPT;
8299			}
8300
8301			if (!found) {
8302				mtx_unlock(&lun->lun_lock);
8303				free(ctsio->kern_data_ptr, M_CTL);
8304				ctl_set_reservation_conflict(ctsio);
8305				ctl_done((union ctl_io *)ctsio);
8306		        	return (1);
8307			}
8308			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8309			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8310			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8311			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8312			persis_io.pr.pr_info.res_type = type;
8313			memcpy(persis_io.pr.pr_info.sa_res_key,
8314			       param->serv_act_res_key,
8315			       sizeof(param->serv_act_res_key));
8316			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8317			     &persis_io, sizeof(persis_io), 0)) >
8318			     CTL_HA_STATUS_SUCCESS) {
8319				printf("CTL:Persis Out error returned "
8320				       "from ctl_ha_msg_send %d\n",
8321				isc_retval);
8322			}
8323		}
8324	}
8325
8326	lun->PRGeneration++;
8327	mtx_unlock(&lun->lun_lock);
8328
8329	return (retval);
8330}
8331
8332static void
8333ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8334{
8335	int i;
8336
8337	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8338	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8339	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8340		   msg->pr.pr_info.sa_res_key,
8341		   sizeof(struct scsi_per_res_key)) != 0) {
8342		uint64_t sa_res_key;
8343		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8344
8345		if (sa_res_key == 0) {
8346			/* temporarily unregister this nexus */
8347			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8348
8349			/*
8350			 * Unregister everybody else and build UA for
8351			 * them
8352			 */
8353			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8354				if (lun->per_res[i].registered == 0)
8355					continue;
8356
8357				if (!persis_offset
8358				 && i < CTL_MAX_INITIATORS)
8359					lun->pending_ua[i] |=
8360						CTL_UA_REG_PREEMPT;
8361				else if (persis_offset && i >= persis_offset)
8362					lun->pending_ua[i - persis_offset] |=
8363						CTL_UA_REG_PREEMPT;
8364				lun->per_res[i].registered = 0;
8365				memset(&lun->per_res[i].res_key, 0,
8366				       sizeof(struct scsi_per_res_key));
8367			}
8368
8369			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8370			lun->pr_key_count = 1;
8371			lun->res_type = msg->pr.pr_info.res_type;
8372			if (lun->res_type != SPR_TYPE_WR_EX_AR
8373			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8374				lun->pr_res_idx = msg->pr.pr_info.residx;
8375		} else {
8376		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8377				if (memcmp(msg->pr.pr_info.sa_res_key,
8378		                   lun->per_res[i].res_key.key,
8379		                   sizeof(struct scsi_per_res_key)) != 0)
8380					continue;
8381
8382				lun->per_res[i].registered = 0;
8383				memset(&lun->per_res[i].res_key, 0,
8384				       sizeof(struct scsi_per_res_key));
8385				lun->pr_key_count--;
8386
8387				if (!persis_offset
8388				 && i < persis_offset)
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			}
8396		}
8397	} else {
8398		/*
8399		 * Temporarily unregister so it won't get removed
8400		 * or UA generated
8401		 */
8402		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8403		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8404			if (lun->per_res[i].registered == 0)
8405				continue;
8406
8407			if (memcmp(msg->pr.pr_info.sa_res_key,
8408	                   lun->per_res[i].res_key.key,
8409	                   sizeof(struct scsi_per_res_key)) == 0) {
8410				lun->per_res[i].registered = 0;
8411				memset(&lun->per_res[i].res_key, 0,
8412				       sizeof(struct scsi_per_res_key));
8413				lun->pr_key_count--;
8414				if (!persis_offset
8415				 && i < CTL_MAX_INITIATORS)
8416					lun->pending_ua[i] |=
8417						CTL_UA_REG_PREEMPT;
8418				else if (persis_offset
8419				      && i >= persis_offset)
8420					lun->pending_ua[i - persis_offset] |=
8421						CTL_UA_REG_PREEMPT;
8422			} else if (msg->pr.pr_info.res_type != lun->res_type
8423				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8424				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8425					if (!persis_offset
8426					 && i < persis_offset)
8427						lun->pending_ua[i] |=
8428							CTL_UA_RES_RELEASE;
8429					else if (persis_offset
8430					      && i >= persis_offset)
8431					lun->pending_ua[i - persis_offset] |=
8432						CTL_UA_RES_RELEASE;
8433			}
8434		}
8435		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8436		lun->res_type = msg->pr.pr_info.res_type;
8437		if (lun->res_type != SPR_TYPE_WR_EX_AR
8438		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8439			lun->pr_res_idx = msg->pr.pr_info.residx;
8440		else
8441			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8442	}
8443	lun->PRGeneration++;
8444
8445}
8446
8447
8448int
8449ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8450{
8451	int retval;
8452	int isc_retval;
8453	u_int32_t param_len;
8454	struct scsi_per_res_out *cdb;
8455	struct ctl_lun *lun;
8456	struct scsi_per_res_out_parms* param;
8457	struct ctl_softc *softc;
8458	uint32_t residx;
8459	uint64_t res_key, sa_res_key;
8460	uint8_t type;
8461	union ctl_ha_msg persis_io;
8462	int    i;
8463
8464	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8465
8466	retval = CTL_RETVAL_COMPLETE;
8467
8468	softc = control_softc;
8469
8470	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8471	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8472
8473	/*
8474	 * We only support whole-LUN scope.  The scope & type are ignored for
8475	 * register, register and ignore existing key and clear.
8476	 * We sometimes ignore scope and type on preempts too!!
8477	 * Verify reservation type here as well.
8478	 */
8479	type = cdb->scope_type & SPR_TYPE_MASK;
8480	if ((cdb->action == SPRO_RESERVE)
8481	 || (cdb->action == SPRO_RELEASE)) {
8482		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8483			ctl_set_invalid_field(/*ctsio*/ ctsio,
8484					      /*sks_valid*/ 1,
8485					      /*command*/ 1,
8486					      /*field*/ 2,
8487					      /*bit_valid*/ 1,
8488					      /*bit*/ 4);
8489			ctl_done((union ctl_io *)ctsio);
8490			return (CTL_RETVAL_COMPLETE);
8491		}
8492
8493		if (type>8 || type==2 || type==4 || type==0) {
8494			ctl_set_invalid_field(/*ctsio*/ ctsio,
8495					      /*sks_valid*/ 1,
8496					      /*command*/ 1,
8497					      /*field*/ 2,
8498					      /*bit_valid*/ 1,
8499					      /*bit*/ 0);
8500			ctl_done((union ctl_io *)ctsio);
8501			return (CTL_RETVAL_COMPLETE);
8502		}
8503	}
8504
8505	param_len = scsi_4btoul(cdb->length);
8506
8507	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8508		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8509		ctsio->kern_data_len = param_len;
8510		ctsio->kern_total_len = param_len;
8511		ctsio->kern_data_resid = 0;
8512		ctsio->kern_rel_offset = 0;
8513		ctsio->kern_sg_entries = 0;
8514		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8515		ctsio->be_move_done = ctl_config_move_done;
8516		ctl_datamove((union ctl_io *)ctsio);
8517
8518		return (CTL_RETVAL_COMPLETE);
8519	}
8520
8521	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8522
8523	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8524	res_key = scsi_8btou64(param->res_key.key);
8525	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8526
8527	/*
8528	 * Validate the reservation key here except for SPRO_REG_IGNO
8529	 * This must be done for all other service actions
8530	 */
8531	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8532		mtx_lock(&lun->lun_lock);
8533		if (lun->per_res[residx].registered) {
8534		    if (memcmp(param->res_key.key,
8535			       lun->per_res[residx].res_key.key,
8536			       ctl_min(sizeof(param->res_key),
8537			       sizeof(lun->per_res[residx].res_key))) != 0) {
8538				/*
8539				 * The current key passed in doesn't match
8540				 * the one the initiator previously
8541				 * registered.
8542				 */
8543				mtx_unlock(&lun->lun_lock);
8544				free(ctsio->kern_data_ptr, M_CTL);
8545				ctl_set_reservation_conflict(ctsio);
8546				ctl_done((union ctl_io *)ctsio);
8547				return (CTL_RETVAL_COMPLETE);
8548			}
8549		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8550			/*
8551			 * We are not registered
8552			 */
8553			mtx_unlock(&lun->lun_lock);
8554			free(ctsio->kern_data_ptr, M_CTL);
8555			ctl_set_reservation_conflict(ctsio);
8556			ctl_done((union ctl_io *)ctsio);
8557			return (CTL_RETVAL_COMPLETE);
8558		} else if (res_key != 0) {
8559			/*
8560			 * We are not registered and trying to register but
8561			 * the register key isn't zero.
8562			 */
8563			mtx_unlock(&lun->lun_lock);
8564			free(ctsio->kern_data_ptr, M_CTL);
8565			ctl_set_reservation_conflict(ctsio);
8566			ctl_done((union ctl_io *)ctsio);
8567			return (CTL_RETVAL_COMPLETE);
8568		}
8569		mtx_unlock(&lun->lun_lock);
8570	}
8571
8572	switch (cdb->action & SPRO_ACTION_MASK) {
8573	case SPRO_REGISTER:
8574	case SPRO_REG_IGNO: {
8575
8576#if 0
8577		printf("Registration received\n");
8578#endif
8579
8580		/*
8581		 * We don't support any of these options, as we report in
8582		 * the read capabilities request (see
8583		 * ctl_persistent_reserve_in(), above).
8584		 */
8585		if ((param->flags & SPR_SPEC_I_PT)
8586		 || (param->flags & SPR_ALL_TG_PT)
8587		 || (param->flags & SPR_APTPL)) {
8588			int bit_ptr;
8589
8590			if (param->flags & SPR_APTPL)
8591				bit_ptr = 0;
8592			else if (param->flags & SPR_ALL_TG_PT)
8593				bit_ptr = 2;
8594			else /* SPR_SPEC_I_PT */
8595				bit_ptr = 3;
8596
8597			free(ctsio->kern_data_ptr, M_CTL);
8598			ctl_set_invalid_field(ctsio,
8599					      /*sks_valid*/ 1,
8600					      /*command*/ 0,
8601					      /*field*/ 20,
8602					      /*bit_valid*/ 1,
8603					      /*bit*/ bit_ptr);
8604			ctl_done((union ctl_io *)ctsio);
8605			return (CTL_RETVAL_COMPLETE);
8606		}
8607
8608		mtx_lock(&lun->lun_lock);
8609
8610		/*
8611		 * The initiator wants to clear the
8612		 * key/unregister.
8613		 */
8614		if (sa_res_key == 0) {
8615			if ((res_key == 0
8616			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8617			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8618			  && !lun->per_res[residx].registered)) {
8619				mtx_unlock(&lun->lun_lock);
8620				goto done;
8621			}
8622
8623			lun->per_res[residx].registered = 0;
8624			memset(&lun->per_res[residx].res_key,
8625			       0, sizeof(lun->per_res[residx].res_key));
8626			lun->pr_key_count--;
8627
8628			if (residx == lun->pr_res_idx) {
8629				lun->flags &= ~CTL_LUN_PR_RESERVED;
8630				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8631
8632				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8633				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8634				 && lun->pr_key_count) {
8635					/*
8636					 * If the reservation is a registrants
8637					 * only type we need to generate a UA
8638					 * for other registered inits.  The
8639					 * sense code should be RESERVATIONS
8640					 * RELEASED
8641					 */
8642
8643					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8644						if (lun->per_res[
8645						    i+persis_offset].registered
8646						    == 0)
8647							continue;
8648						lun->pending_ua[i] |=
8649							CTL_UA_RES_RELEASE;
8650					}
8651				}
8652				lun->res_type = 0;
8653			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8654				if (lun->pr_key_count==0) {
8655					lun->flags &= ~CTL_LUN_PR_RESERVED;
8656					lun->res_type = 0;
8657					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8658				}
8659			}
8660			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8661			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8662			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8663			persis_io.pr.pr_info.residx = residx;
8664			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8665			     &persis_io, sizeof(persis_io), 0 )) >
8666			     CTL_HA_STATUS_SUCCESS) {
8667				printf("CTL:Persis Out error returned from "
8668				       "ctl_ha_msg_send %d\n", isc_retval);
8669			}
8670		} else /* sa_res_key != 0 */ {
8671
8672			/*
8673			 * If we aren't registered currently then increment
8674			 * the key count and set the registered flag.
8675			 */
8676			if (!lun->per_res[residx].registered) {
8677				lun->pr_key_count++;
8678				lun->per_res[residx].registered = 1;
8679			}
8680
8681			memcpy(&lun->per_res[residx].res_key,
8682			       param->serv_act_res_key,
8683			       ctl_min(sizeof(param->serv_act_res_key),
8684			       sizeof(lun->per_res[residx].res_key)));
8685
8686			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8687			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8688			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8689			persis_io.pr.pr_info.residx = residx;
8690			memcpy(persis_io.pr.pr_info.sa_res_key,
8691			       param->serv_act_res_key,
8692			       sizeof(param->serv_act_res_key));
8693			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8694			     &persis_io, sizeof(persis_io), 0)) >
8695			     CTL_HA_STATUS_SUCCESS) {
8696				printf("CTL:Persis Out error returned from "
8697				       "ctl_ha_msg_send %d\n", isc_retval);
8698			}
8699		}
8700		lun->PRGeneration++;
8701		mtx_unlock(&lun->lun_lock);
8702
8703		break;
8704	}
8705	case SPRO_RESERVE:
8706#if 0
8707                printf("Reserve executed type %d\n", type);
8708#endif
8709		mtx_lock(&lun->lun_lock);
8710		if (lun->flags & CTL_LUN_PR_RESERVED) {
8711			/*
8712			 * if this isn't the reservation holder and it's
8713			 * not a "all registrants" type or if the type is
8714			 * different then we have a conflict
8715			 */
8716			if ((lun->pr_res_idx != residx
8717			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8718			 || lun->res_type != type) {
8719				mtx_unlock(&lun->lun_lock);
8720				free(ctsio->kern_data_ptr, M_CTL);
8721				ctl_set_reservation_conflict(ctsio);
8722				ctl_done((union ctl_io *)ctsio);
8723				return (CTL_RETVAL_COMPLETE);
8724			}
8725			mtx_unlock(&lun->lun_lock);
8726		} else /* create a reservation */ {
8727			/*
8728			 * If it's not an "all registrants" type record
8729			 * reservation holder
8730			 */
8731			if (type != SPR_TYPE_WR_EX_AR
8732			 && type != SPR_TYPE_EX_AC_AR)
8733				lun->pr_res_idx = residx; /* Res holder */
8734			else
8735				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8736
8737			lun->flags |= CTL_LUN_PR_RESERVED;
8738			lun->res_type = type;
8739
8740			mtx_unlock(&lun->lun_lock);
8741
8742			/* send msg to other side */
8743			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8744			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8745			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8746			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8747			persis_io.pr.pr_info.res_type = type;
8748			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8749			     &persis_io, sizeof(persis_io), 0)) >
8750			     CTL_HA_STATUS_SUCCESS) {
8751				printf("CTL:Persis Out error returned from "
8752				       "ctl_ha_msg_send %d\n", isc_retval);
8753			}
8754		}
8755		break;
8756
8757	case SPRO_RELEASE:
8758		mtx_lock(&lun->lun_lock);
8759		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8760			/* No reservation exists return good status */
8761			mtx_unlock(&lun->lun_lock);
8762			goto done;
8763		}
8764		/*
8765		 * Is this nexus a reservation holder?
8766		 */
8767		if (lun->pr_res_idx != residx
8768		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8769			/*
8770			 * not a res holder return good status but
8771			 * do nothing
8772			 */
8773			mtx_unlock(&lun->lun_lock);
8774			goto done;
8775		}
8776
8777		if (lun->res_type != type) {
8778			mtx_unlock(&lun->lun_lock);
8779			free(ctsio->kern_data_ptr, M_CTL);
8780			ctl_set_illegal_pr_release(ctsio);
8781			ctl_done((union ctl_io *)ctsio);
8782			return (CTL_RETVAL_COMPLETE);
8783		}
8784
8785		/* okay to release */
8786		lun->flags &= ~CTL_LUN_PR_RESERVED;
8787		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8788		lun->res_type = 0;
8789
8790		/*
8791		 * if this isn't an exclusive access
8792		 * res generate UA for all other
8793		 * registrants.
8794		 */
8795		if (type != SPR_TYPE_EX_AC
8796		 && type != SPR_TYPE_WR_EX) {
8797			/*
8798			 * temporarily unregister so we don't generate UA
8799			 */
8800			lun->per_res[residx].registered = 0;
8801
8802			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8803				if (lun->per_res[i+persis_offset].registered
8804				    == 0)
8805					continue;
8806				lun->pending_ua[i] |=
8807					CTL_UA_RES_RELEASE;
8808			}
8809
8810			lun->per_res[residx].registered = 1;
8811		}
8812		mtx_unlock(&lun->lun_lock);
8813		/* Send msg to other side */
8814		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8815		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8816		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8817		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8818		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8819			printf("CTL:Persis Out error returned from "
8820			       "ctl_ha_msg_send %d\n", isc_retval);
8821		}
8822		break;
8823
8824	case SPRO_CLEAR:
8825		/* send msg to other side */
8826
8827		mtx_lock(&lun->lun_lock);
8828		lun->flags &= ~CTL_LUN_PR_RESERVED;
8829		lun->res_type = 0;
8830		lun->pr_key_count = 0;
8831		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8832
8833
8834		memset(&lun->per_res[residx].res_key,
8835		       0, sizeof(lun->per_res[residx].res_key));
8836		lun->per_res[residx].registered = 0;
8837
8838		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8839			if (lun->per_res[i].registered) {
8840				if (!persis_offset && i < CTL_MAX_INITIATORS)
8841					lun->pending_ua[i] |=
8842						CTL_UA_RES_PREEMPT;
8843				else if (persis_offset && i >= persis_offset)
8844					lun->pending_ua[i-persis_offset] |=
8845					    CTL_UA_RES_PREEMPT;
8846
8847				memset(&lun->per_res[i].res_key,
8848				       0, sizeof(struct scsi_per_res_key));
8849				lun->per_res[i].registered = 0;
8850			}
8851		lun->PRGeneration++;
8852		mtx_unlock(&lun->lun_lock);
8853		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8854		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8855		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8856		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8857		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8858			printf("CTL:Persis Out error returned from "
8859			       "ctl_ha_msg_send %d\n", isc_retval);
8860		}
8861		break;
8862
8863	case SPRO_PREEMPT: {
8864		int nretval;
8865
8866		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8867					  residx, ctsio, cdb, param);
8868		if (nretval != 0)
8869			return (CTL_RETVAL_COMPLETE);
8870		break;
8871	}
8872	default:
8873		panic("Invalid PR type %x", cdb->action);
8874	}
8875
8876done:
8877	free(ctsio->kern_data_ptr, M_CTL);
8878	ctl_set_success(ctsio);
8879	ctl_done((union ctl_io *)ctsio);
8880
8881	return (retval);
8882}
8883
8884/*
8885 * This routine is for handling a message from the other SC pertaining to
8886 * persistent reserve out. All the error checking will have been done
8887 * so only perorming the action need be done here to keep the two
8888 * in sync.
8889 */
8890static void
8891ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8892{
8893	struct ctl_lun *lun;
8894	struct ctl_softc *softc;
8895	int i;
8896	uint32_t targ_lun;
8897
8898	softc = control_softc;
8899
8900	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8901	lun = softc->ctl_luns[targ_lun];
8902	mtx_lock(&lun->lun_lock);
8903	switch(msg->pr.pr_info.action) {
8904	case CTL_PR_REG_KEY:
8905		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8906			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8907			lun->pr_key_count++;
8908		}
8909		lun->PRGeneration++;
8910		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8911		       msg->pr.pr_info.sa_res_key,
8912		       sizeof(struct scsi_per_res_key));
8913		break;
8914
8915	case CTL_PR_UNREG_KEY:
8916		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8917		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8918		       0, sizeof(struct scsi_per_res_key));
8919		lun->pr_key_count--;
8920
8921		/* XXX Need to see if the reservation has been released */
8922		/* if so do we need to generate UA? */
8923		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8924			lun->flags &= ~CTL_LUN_PR_RESERVED;
8925			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8926
8927			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8928			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8929			 && lun->pr_key_count) {
8930				/*
8931				 * If the reservation is a registrants
8932				 * only type we need to generate a UA
8933				 * for other registered inits.  The
8934				 * sense code should be RESERVATIONS
8935				 * RELEASED
8936				 */
8937
8938				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8939					if (lun->per_res[i+
8940					    persis_offset].registered == 0)
8941						continue;
8942
8943					lun->pending_ua[i] |=
8944						CTL_UA_RES_RELEASE;
8945				}
8946			}
8947			lun->res_type = 0;
8948		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8949			if (lun->pr_key_count==0) {
8950				lun->flags &= ~CTL_LUN_PR_RESERVED;
8951				lun->res_type = 0;
8952				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8953			}
8954		}
8955		lun->PRGeneration++;
8956		break;
8957
8958	case CTL_PR_RESERVE:
8959		lun->flags |= CTL_LUN_PR_RESERVED;
8960		lun->res_type = msg->pr.pr_info.res_type;
8961		lun->pr_res_idx = msg->pr.pr_info.residx;
8962
8963		break;
8964
8965	case CTL_PR_RELEASE:
8966		/*
8967		 * if this isn't an exclusive access res generate UA for all
8968		 * other registrants.
8969		 */
8970		if (lun->res_type != SPR_TYPE_EX_AC
8971		 && lun->res_type != SPR_TYPE_WR_EX) {
8972			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8973				if (lun->per_res[i+persis_offset].registered)
8974					lun->pending_ua[i] |=
8975						CTL_UA_RES_RELEASE;
8976		}
8977
8978		lun->flags &= ~CTL_LUN_PR_RESERVED;
8979		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8980		lun->res_type = 0;
8981		break;
8982
8983	case CTL_PR_PREEMPT:
8984		ctl_pro_preempt_other(lun, msg);
8985		break;
8986	case CTL_PR_CLEAR:
8987		lun->flags &= ~CTL_LUN_PR_RESERVED;
8988		lun->res_type = 0;
8989		lun->pr_key_count = 0;
8990		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8991
8992		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8993			if (lun->per_res[i].registered == 0)
8994				continue;
8995			if (!persis_offset
8996			 && i < CTL_MAX_INITIATORS)
8997				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8998			else if (persis_offset
8999			      && i >= persis_offset)
9000				lun->pending_ua[i-persis_offset] |=
9001					CTL_UA_RES_PREEMPT;
9002			memset(&lun->per_res[i].res_key, 0,
9003			       sizeof(struct scsi_per_res_key));
9004			lun->per_res[i].registered = 0;
9005		}
9006		lun->PRGeneration++;
9007		break;
9008	}
9009
9010	mtx_unlock(&lun->lun_lock);
9011}
9012
9013int
9014ctl_read_write(struct ctl_scsiio *ctsio)
9015{
9016	struct ctl_lun *lun;
9017	struct ctl_lba_len_flags *lbalen;
9018	uint64_t lba;
9019	uint32_t num_blocks;
9020	int flags, retval;
9021	int isread;
9022
9023	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9024
9025	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9026
9027	flags = 0;
9028	retval = CTL_RETVAL_COMPLETE;
9029
9030	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9031	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9032	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9033		uint32_t residx;
9034
9035		/*
9036		 * XXX KDM need a lock here.
9037		 */
9038		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9039		if ((lun->res_type == SPR_TYPE_EX_AC
9040		  && residx != lun->pr_res_idx)
9041		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9042		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9043		  && !lun->per_res[residx].registered)) {
9044			ctl_set_reservation_conflict(ctsio);
9045			ctl_done((union ctl_io *)ctsio);
9046			return (CTL_RETVAL_COMPLETE);
9047	        }
9048	}
9049
9050	switch (ctsio->cdb[0]) {
9051	case READ_6:
9052	case WRITE_6: {
9053		struct scsi_rw_6 *cdb;
9054
9055		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9056
9057		lba = scsi_3btoul(cdb->addr);
9058		/* only 5 bits are valid in the most significant address byte */
9059		lba &= 0x1fffff;
9060		num_blocks = cdb->length;
9061		/*
9062		 * This is correct according to SBC-2.
9063		 */
9064		if (num_blocks == 0)
9065			num_blocks = 256;
9066		break;
9067	}
9068	case READ_10:
9069	case WRITE_10: {
9070		struct scsi_rw_10 *cdb;
9071
9072		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9073		if (cdb->byte2 & SRW10_FUA)
9074			flags |= CTL_LLF_FUA;
9075		if (cdb->byte2 & SRW10_DPO)
9076			flags |= CTL_LLF_DPO;
9077		lba = scsi_4btoul(cdb->addr);
9078		num_blocks = scsi_2btoul(cdb->length);
9079		break;
9080	}
9081	case WRITE_VERIFY_10: {
9082		struct scsi_write_verify_10 *cdb;
9083
9084		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9085		flags |= CTL_LLF_FUA;
9086		if (cdb->byte2 & SWV_DPO)
9087			flags |= CTL_LLF_DPO;
9088		lba = scsi_4btoul(cdb->addr);
9089		num_blocks = scsi_2btoul(cdb->length);
9090		break;
9091	}
9092	case READ_12:
9093	case WRITE_12: {
9094		struct scsi_rw_12 *cdb;
9095
9096		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9097		if (cdb->byte2 & SRW12_FUA)
9098			flags |= CTL_LLF_FUA;
9099		if (cdb->byte2 & SRW12_DPO)
9100			flags |= CTL_LLF_DPO;
9101		lba = scsi_4btoul(cdb->addr);
9102		num_blocks = scsi_4btoul(cdb->length);
9103		break;
9104	}
9105	case WRITE_VERIFY_12: {
9106		struct scsi_write_verify_12 *cdb;
9107
9108		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9109		flags |= CTL_LLF_FUA;
9110		if (cdb->byte2 & SWV_DPO)
9111			flags |= CTL_LLF_DPO;
9112		lba = scsi_4btoul(cdb->addr);
9113		num_blocks = scsi_4btoul(cdb->length);
9114		break;
9115	}
9116	case READ_16:
9117	case WRITE_16: {
9118		struct scsi_rw_16 *cdb;
9119
9120		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9121		if (cdb->byte2 & SRW12_FUA)
9122			flags |= CTL_LLF_FUA;
9123		if (cdb->byte2 & SRW12_DPO)
9124			flags |= CTL_LLF_DPO;
9125		lba = scsi_8btou64(cdb->addr);
9126		num_blocks = scsi_4btoul(cdb->length);
9127		break;
9128	}
9129	case WRITE_VERIFY_16: {
9130		struct scsi_write_verify_16 *cdb;
9131
9132		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9133		flags |= CTL_LLF_FUA;
9134		if (cdb->byte2 & SWV_DPO)
9135			flags |= CTL_LLF_DPO;
9136		lba = scsi_8btou64(cdb->addr);
9137		num_blocks = scsi_4btoul(cdb->length);
9138		break;
9139	}
9140	default:
9141		/*
9142		 * We got a command we don't support.  This shouldn't
9143		 * happen, commands should be filtered out above us.
9144		 */
9145		ctl_set_invalid_opcode(ctsio);
9146		ctl_done((union ctl_io *)ctsio);
9147
9148		return (CTL_RETVAL_COMPLETE);
9149		break; /* NOTREACHED */
9150	}
9151
9152	/*
9153	 * The first check is to make sure we're in bounds, the second
9154	 * check is to catch wrap-around problems.  If the lba + num blocks
9155	 * is less than the lba, then we've wrapped around and the block
9156	 * range is invalid anyway.
9157	 */
9158	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9159	 || ((lba + num_blocks) < lba)) {
9160		ctl_set_lba_out_of_range(ctsio);
9161		ctl_done((union ctl_io *)ctsio);
9162		return (CTL_RETVAL_COMPLETE);
9163	}
9164
9165	/*
9166	 * According to SBC-3, a transfer length of 0 is not an error.
9167	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9168	 * translates to 256 blocks for those commands.
9169	 */
9170	if (num_blocks == 0) {
9171		ctl_set_success(ctsio);
9172		ctl_done((union ctl_io *)ctsio);
9173		return (CTL_RETVAL_COMPLETE);
9174	}
9175
9176	/* Set FUA and/or DPO if caches are disabled. */
9177	if (isread) {
9178		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9179		    SCP_RCD) != 0)
9180			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9181	} else {
9182		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9183		    SCP_WCE) == 0)
9184			flags |= CTL_LLF_FUA;
9185	}
9186
9187	lbalen = (struct ctl_lba_len_flags *)
9188	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9189	lbalen->lba = lba;
9190	lbalen->len = num_blocks;
9191	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9192
9193	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9194	ctsio->kern_rel_offset = 0;
9195
9196	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9197
9198	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9199
9200	return (retval);
9201}
9202
9203static int
9204ctl_cnw_cont(union ctl_io *io)
9205{
9206	struct ctl_scsiio *ctsio;
9207	struct ctl_lun *lun;
9208	struct ctl_lba_len_flags *lbalen;
9209	int retval;
9210
9211	ctsio = &io->scsiio;
9212	ctsio->io_hdr.status = CTL_STATUS_NONE;
9213	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9214	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9215	lbalen = (struct ctl_lba_len_flags *)
9216	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9217	lbalen->flags &= ~CTL_LLF_COMPARE;
9218	lbalen->flags |= CTL_LLF_WRITE;
9219
9220	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9221	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9222	return (retval);
9223}
9224
9225int
9226ctl_cnw(struct ctl_scsiio *ctsio)
9227{
9228	struct ctl_lun *lun;
9229	struct ctl_lba_len_flags *lbalen;
9230	uint64_t lba;
9231	uint32_t num_blocks;
9232	int flags, retval;
9233
9234	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9235
9236	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9237
9238	flags = 0;
9239	retval = CTL_RETVAL_COMPLETE;
9240
9241	switch (ctsio->cdb[0]) {
9242	case COMPARE_AND_WRITE: {
9243		struct scsi_compare_and_write *cdb;
9244
9245		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9246		if (cdb->byte2 & SRW10_FUA)
9247			flags |= CTL_LLF_FUA;
9248		if (cdb->byte2 & SRW10_DPO)
9249			flags |= CTL_LLF_DPO;
9250		lba = scsi_8btou64(cdb->addr);
9251		num_blocks = cdb->length;
9252		break;
9253	}
9254	default:
9255		/*
9256		 * We got a command we don't support.  This shouldn't
9257		 * happen, commands should be filtered out above us.
9258		 */
9259		ctl_set_invalid_opcode(ctsio);
9260		ctl_done((union ctl_io *)ctsio);
9261
9262		return (CTL_RETVAL_COMPLETE);
9263		break; /* NOTREACHED */
9264	}
9265
9266	/*
9267	 * The first check is to make sure we're in bounds, the second
9268	 * check is to catch wrap-around problems.  If the lba + num blocks
9269	 * is less than the lba, then we've wrapped around and the block
9270	 * range is invalid anyway.
9271	 */
9272	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9273	 || ((lba + num_blocks) < lba)) {
9274		ctl_set_lba_out_of_range(ctsio);
9275		ctl_done((union ctl_io *)ctsio);
9276		return (CTL_RETVAL_COMPLETE);
9277	}
9278
9279	/*
9280	 * According to SBC-3, a transfer length of 0 is not an error.
9281	 */
9282	if (num_blocks == 0) {
9283		ctl_set_success(ctsio);
9284		ctl_done((union ctl_io *)ctsio);
9285		return (CTL_RETVAL_COMPLETE);
9286	}
9287
9288	/* Set FUA if write cache is disabled. */
9289	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9290	    SCP_WCE) == 0)
9291		flags |= CTL_LLF_FUA;
9292
9293	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9294	ctsio->kern_rel_offset = 0;
9295
9296	/*
9297	 * Set the IO_CONT flag, so that if this I/O gets passed to
9298	 * ctl_data_submit_done(), it'll get passed back to
9299	 * ctl_ctl_cnw_cont() for further processing.
9300	 */
9301	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9302	ctsio->io_cont = ctl_cnw_cont;
9303
9304	lbalen = (struct ctl_lba_len_flags *)
9305	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9306	lbalen->lba = lba;
9307	lbalen->len = num_blocks;
9308	lbalen->flags = CTL_LLF_COMPARE | flags;
9309
9310	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9311	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9312	return (retval);
9313}
9314
9315int
9316ctl_verify(struct ctl_scsiio *ctsio)
9317{
9318	struct ctl_lun *lun;
9319	struct ctl_lba_len_flags *lbalen;
9320	uint64_t lba;
9321	uint32_t num_blocks;
9322	int bytchk, flags;
9323	int retval;
9324
9325	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9326
9327	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9328
9329	bytchk = 0;
9330	flags = CTL_LLF_FUA;
9331	retval = CTL_RETVAL_COMPLETE;
9332
9333	switch (ctsio->cdb[0]) {
9334	case VERIFY_10: {
9335		struct scsi_verify_10 *cdb;
9336
9337		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9338		if (cdb->byte2 & SVFY_BYTCHK)
9339			bytchk = 1;
9340		if (cdb->byte2 & SVFY_DPO)
9341			flags |= CTL_LLF_DPO;
9342		lba = scsi_4btoul(cdb->addr);
9343		num_blocks = scsi_2btoul(cdb->length);
9344		break;
9345	}
9346	case VERIFY_12: {
9347		struct scsi_verify_12 *cdb;
9348
9349		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9350		if (cdb->byte2 & SVFY_BYTCHK)
9351			bytchk = 1;
9352		if (cdb->byte2 & SVFY_DPO)
9353			flags |= CTL_LLF_DPO;
9354		lba = scsi_4btoul(cdb->addr);
9355		num_blocks = scsi_4btoul(cdb->length);
9356		break;
9357	}
9358	case VERIFY_16: {
9359		struct scsi_rw_16 *cdb;
9360
9361		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9362		if (cdb->byte2 & SVFY_BYTCHK)
9363			bytchk = 1;
9364		if (cdb->byte2 & SVFY_DPO)
9365			flags |= CTL_LLF_DPO;
9366		lba = scsi_8btou64(cdb->addr);
9367		num_blocks = scsi_4btoul(cdb->length);
9368		break;
9369	}
9370	default:
9371		/*
9372		 * We got a command we don't support.  This shouldn't
9373		 * happen, commands should be filtered out above us.
9374		 */
9375		ctl_set_invalid_opcode(ctsio);
9376		ctl_done((union ctl_io *)ctsio);
9377		return (CTL_RETVAL_COMPLETE);
9378	}
9379
9380	/*
9381	 * The first check is to make sure we're in bounds, the second
9382	 * check is to catch wrap-around problems.  If the lba + num blocks
9383	 * is less than the lba, then we've wrapped around and the block
9384	 * range is invalid anyway.
9385	 */
9386	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9387	 || ((lba + num_blocks) < lba)) {
9388		ctl_set_lba_out_of_range(ctsio);
9389		ctl_done((union ctl_io *)ctsio);
9390		return (CTL_RETVAL_COMPLETE);
9391	}
9392
9393	/*
9394	 * According to SBC-3, a transfer length of 0 is not an error.
9395	 */
9396	if (num_blocks == 0) {
9397		ctl_set_success(ctsio);
9398		ctl_done((union ctl_io *)ctsio);
9399		return (CTL_RETVAL_COMPLETE);
9400	}
9401
9402	lbalen = (struct ctl_lba_len_flags *)
9403	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9404	lbalen->lba = lba;
9405	lbalen->len = num_blocks;
9406	if (bytchk) {
9407		lbalen->flags = CTL_LLF_COMPARE | flags;
9408		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9409	} else {
9410		lbalen->flags = CTL_LLF_VERIFY | flags;
9411		ctsio->kern_total_len = 0;
9412	}
9413	ctsio->kern_rel_offset = 0;
9414
9415	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9416	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9417	return (retval);
9418}
9419
9420int
9421ctl_report_luns(struct ctl_scsiio *ctsio)
9422{
9423	struct scsi_report_luns *cdb;
9424	struct scsi_report_luns_data *lun_data;
9425	struct ctl_lun *lun, *request_lun;
9426	int num_luns, retval;
9427	uint32_t alloc_len, lun_datalen;
9428	int num_filled, well_known;
9429	uint32_t initidx, targ_lun_id, lun_id;
9430
9431	retval = CTL_RETVAL_COMPLETE;
9432	well_known = 0;
9433
9434	cdb = (struct scsi_report_luns *)ctsio->cdb;
9435
9436	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9437
9438	mtx_lock(&control_softc->ctl_lock);
9439	num_luns = control_softc->num_luns;
9440	mtx_unlock(&control_softc->ctl_lock);
9441
9442	switch (cdb->select_report) {
9443	case RPL_REPORT_DEFAULT:
9444	case RPL_REPORT_ALL:
9445		break;
9446	case RPL_REPORT_WELLKNOWN:
9447		well_known = 1;
9448		num_luns = 0;
9449		break;
9450	default:
9451		ctl_set_invalid_field(ctsio,
9452				      /*sks_valid*/ 1,
9453				      /*command*/ 1,
9454				      /*field*/ 2,
9455				      /*bit_valid*/ 0,
9456				      /*bit*/ 0);
9457		ctl_done((union ctl_io *)ctsio);
9458		return (retval);
9459		break; /* NOTREACHED */
9460	}
9461
9462	alloc_len = scsi_4btoul(cdb->length);
9463	/*
9464	 * The initiator has to allocate at least 16 bytes for this request,
9465	 * so he can at least get the header and the first LUN.  Otherwise
9466	 * we reject the request (per SPC-3 rev 14, section 6.21).
9467	 */
9468	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9469	    sizeof(struct scsi_report_luns_lundata))) {
9470		ctl_set_invalid_field(ctsio,
9471				      /*sks_valid*/ 1,
9472				      /*command*/ 1,
9473				      /*field*/ 6,
9474				      /*bit_valid*/ 0,
9475				      /*bit*/ 0);
9476		ctl_done((union ctl_io *)ctsio);
9477		return (retval);
9478	}
9479
9480	request_lun = (struct ctl_lun *)
9481		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9482
9483	lun_datalen = sizeof(*lun_data) +
9484		(num_luns * sizeof(struct scsi_report_luns_lundata));
9485
9486	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9487	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9488	ctsio->kern_sg_entries = 0;
9489
9490	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9491
9492	mtx_lock(&control_softc->ctl_lock);
9493	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9494		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9495		if (lun_id >= CTL_MAX_LUNS)
9496			continue;
9497		lun = control_softc->ctl_luns[lun_id];
9498		if (lun == NULL)
9499			continue;
9500
9501		if (targ_lun_id <= 0xff) {
9502			/*
9503			 * Peripheral addressing method, bus number 0.
9504			 */
9505			lun_data->luns[num_filled].lundata[0] =
9506				RPL_LUNDATA_ATYP_PERIPH;
9507			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9508			num_filled++;
9509		} else if (targ_lun_id <= 0x3fff) {
9510			/*
9511			 * Flat addressing method.
9512			 */
9513			lun_data->luns[num_filled].lundata[0] =
9514				RPL_LUNDATA_ATYP_FLAT |
9515				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9516#ifdef OLDCTLHEADERS
9517				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9518				(targ_lun_id & SRLD_BUS_LUN_MASK);
9519#endif
9520			lun_data->luns[num_filled].lundata[1] =
9521#ifdef OLDCTLHEADERS
9522				targ_lun_id >> SRLD_BUS_LUN_BITS;
9523#endif
9524				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9525			num_filled++;
9526		} else {
9527			printf("ctl_report_luns: bogus LUN number %jd, "
9528			       "skipping\n", (intmax_t)targ_lun_id);
9529		}
9530		/*
9531		 * According to SPC-3, rev 14 section 6.21:
9532		 *
9533		 * "The execution of a REPORT LUNS command to any valid and
9534		 * installed logical unit shall clear the REPORTED LUNS DATA
9535		 * HAS CHANGED unit attention condition for all logical
9536		 * units of that target with respect to the requesting
9537		 * initiator. A valid and installed logical unit is one
9538		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9539		 * INQUIRY data (see 6.4.2)."
9540		 *
9541		 * If request_lun is NULL, the LUN this report luns command
9542		 * was issued to is either disabled or doesn't exist. In that
9543		 * case, we shouldn't clear any pending lun change unit
9544		 * attention.
9545		 */
9546		if (request_lun != NULL) {
9547			mtx_lock(&lun->lun_lock);
9548			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9549			mtx_unlock(&lun->lun_lock);
9550		}
9551	}
9552	mtx_unlock(&control_softc->ctl_lock);
9553
9554	/*
9555	 * It's quite possible that we've returned fewer LUNs than we allocated
9556	 * space for.  Trim it.
9557	 */
9558	lun_datalen = sizeof(*lun_data) +
9559		(num_filled * sizeof(struct scsi_report_luns_lundata));
9560
9561	if (lun_datalen < alloc_len) {
9562		ctsio->residual = alloc_len - lun_datalen;
9563		ctsio->kern_data_len = lun_datalen;
9564		ctsio->kern_total_len = lun_datalen;
9565	} else {
9566		ctsio->residual = 0;
9567		ctsio->kern_data_len = alloc_len;
9568		ctsio->kern_total_len = alloc_len;
9569	}
9570	ctsio->kern_data_resid = 0;
9571	ctsio->kern_rel_offset = 0;
9572	ctsio->kern_sg_entries = 0;
9573
9574	/*
9575	 * We set this to the actual data length, regardless of how much
9576	 * space we actually have to return results.  If the user looks at
9577	 * this value, he'll know whether or not he allocated enough space
9578	 * and reissue the command if necessary.  We don't support well
9579	 * known logical units, so if the user asks for that, return none.
9580	 */
9581	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9582
9583	/*
9584	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9585	 * this request.
9586	 */
9587	ctsio->scsi_status = SCSI_STATUS_OK;
9588
9589	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9590	ctsio->be_move_done = ctl_config_move_done;
9591	ctl_datamove((union ctl_io *)ctsio);
9592
9593	return (retval);
9594}
9595
9596int
9597ctl_request_sense(struct ctl_scsiio *ctsio)
9598{
9599	struct scsi_request_sense *cdb;
9600	struct scsi_sense_data *sense_ptr;
9601	struct ctl_lun *lun;
9602	uint32_t initidx;
9603	int have_error;
9604	scsi_sense_data_type sense_format;
9605
9606	cdb = (struct scsi_request_sense *)ctsio->cdb;
9607
9608	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9609
9610	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9611
9612	/*
9613	 * Determine which sense format the user wants.
9614	 */
9615	if (cdb->byte2 & SRS_DESC)
9616		sense_format = SSD_TYPE_DESC;
9617	else
9618		sense_format = SSD_TYPE_FIXED;
9619
9620	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9621	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9622	ctsio->kern_sg_entries = 0;
9623
9624	/*
9625	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9626	 * larger than the largest allowed value for the length field in the
9627	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9628	 */
9629	ctsio->residual = 0;
9630	ctsio->kern_data_len = cdb->length;
9631	ctsio->kern_total_len = cdb->length;
9632
9633	ctsio->kern_data_resid = 0;
9634	ctsio->kern_rel_offset = 0;
9635	ctsio->kern_sg_entries = 0;
9636
9637	/*
9638	 * If we don't have a LUN, we don't have any pending sense.
9639	 */
9640	if (lun == NULL)
9641		goto no_sense;
9642
9643	have_error = 0;
9644	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9645	/*
9646	 * Check for pending sense, and then for pending unit attentions.
9647	 * Pending sense gets returned first, then pending unit attentions.
9648	 */
9649	mtx_lock(&lun->lun_lock);
9650#ifdef CTL_WITH_CA
9651	if (ctl_is_set(lun->have_ca, initidx)) {
9652		scsi_sense_data_type stored_format;
9653
9654		/*
9655		 * Check to see which sense format was used for the stored
9656		 * sense data.
9657		 */
9658		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9659
9660		/*
9661		 * If the user requested a different sense format than the
9662		 * one we stored, then we need to convert it to the other
9663		 * format.  If we're going from descriptor to fixed format
9664		 * sense data, we may lose things in translation, depending
9665		 * on what options were used.
9666		 *
9667		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9668		 * for some reason we'll just copy it out as-is.
9669		 */
9670		if ((stored_format == SSD_TYPE_FIXED)
9671		 && (sense_format == SSD_TYPE_DESC))
9672			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9673			    &lun->pending_sense[initidx],
9674			    (struct scsi_sense_data_desc *)sense_ptr);
9675		else if ((stored_format == SSD_TYPE_DESC)
9676		      && (sense_format == SSD_TYPE_FIXED))
9677			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9678			    &lun->pending_sense[initidx],
9679			    (struct scsi_sense_data_fixed *)sense_ptr);
9680		else
9681			memcpy(sense_ptr, &lun->pending_sense[initidx],
9682			       ctl_min(sizeof(*sense_ptr),
9683			       sizeof(lun->pending_sense[initidx])));
9684
9685		ctl_clear_mask(lun->have_ca, initidx);
9686		have_error = 1;
9687	} else
9688#endif
9689	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9690		ctl_ua_type ua_type;
9691
9692		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9693				       sense_ptr, sense_format);
9694		if (ua_type != CTL_UA_NONE)
9695			have_error = 1;
9696	}
9697	mtx_unlock(&lun->lun_lock);
9698
9699	/*
9700	 * We already have a pending error, return it.
9701	 */
9702	if (have_error != 0) {
9703		/*
9704		 * We report the SCSI status as OK, since the status of the
9705		 * request sense command itself is OK.
9706		 */
9707		ctsio->scsi_status = SCSI_STATUS_OK;
9708
9709		/*
9710		 * We report 0 for the sense length, because we aren't doing
9711		 * autosense in this case.  We're reporting sense as
9712		 * parameter data.
9713		 */
9714		ctsio->sense_len = 0;
9715		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9716		ctsio->be_move_done = ctl_config_move_done;
9717		ctl_datamove((union ctl_io *)ctsio);
9718
9719		return (CTL_RETVAL_COMPLETE);
9720	}
9721
9722no_sense:
9723
9724	/*
9725	 * No sense information to report, so we report that everything is
9726	 * okay.
9727	 */
9728	ctl_set_sense_data(sense_ptr,
9729			   lun,
9730			   sense_format,
9731			   /*current_error*/ 1,
9732			   /*sense_key*/ SSD_KEY_NO_SENSE,
9733			   /*asc*/ 0x00,
9734			   /*ascq*/ 0x00,
9735			   SSD_ELEM_NONE);
9736
9737	ctsio->scsi_status = SCSI_STATUS_OK;
9738
9739	/*
9740	 * We report 0 for the sense length, because we aren't doing
9741	 * autosense in this case.  We're reporting sense as parameter data.
9742	 */
9743	ctsio->sense_len = 0;
9744	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9745	ctsio->be_move_done = ctl_config_move_done;
9746	ctl_datamove((union ctl_io *)ctsio);
9747
9748	return (CTL_RETVAL_COMPLETE);
9749}
9750
9751int
9752ctl_tur(struct ctl_scsiio *ctsio)
9753{
9754	struct ctl_lun *lun;
9755
9756	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9757
9758	CTL_DEBUG_PRINT(("ctl_tur\n"));
9759
9760	if (lun == NULL)
9761		return (EINVAL);
9762
9763	ctsio->scsi_status = SCSI_STATUS_OK;
9764	ctsio->io_hdr.status = CTL_SUCCESS;
9765
9766	ctl_done((union ctl_io *)ctsio);
9767
9768	return (CTL_RETVAL_COMPLETE);
9769}
9770
9771#ifdef notyet
9772static int
9773ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9774{
9775
9776}
9777#endif
9778
9779static int
9780ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9781{
9782	struct scsi_vpd_supported_pages *pages;
9783	int sup_page_size;
9784	struct ctl_lun *lun;
9785
9786	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9787
9788	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9789	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9790	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9791	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9792	ctsio->kern_sg_entries = 0;
9793
9794	if (sup_page_size < alloc_len) {
9795		ctsio->residual = alloc_len - sup_page_size;
9796		ctsio->kern_data_len = sup_page_size;
9797		ctsio->kern_total_len = sup_page_size;
9798	} else {
9799		ctsio->residual = 0;
9800		ctsio->kern_data_len = alloc_len;
9801		ctsio->kern_total_len = alloc_len;
9802	}
9803	ctsio->kern_data_resid = 0;
9804	ctsio->kern_rel_offset = 0;
9805	ctsio->kern_sg_entries = 0;
9806
9807	/*
9808	 * The control device is always connected.  The disk device, on the
9809	 * other hand, may not be online all the time.  Need to change this
9810	 * to figure out whether the disk device is actually online or not.
9811	 */
9812	if (lun != NULL)
9813		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9814				lun->be_lun->lun_type;
9815	else
9816		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9817
9818	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9819	/* Supported VPD pages */
9820	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9821	/* Serial Number */
9822	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9823	/* Device Identification */
9824	pages->page_list[2] = SVPD_DEVICE_ID;
9825	/* Extended INQUIRY Data */
9826	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9827	/* Mode Page Policy */
9828	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9829	/* SCSI Ports */
9830	pages->page_list[5] = SVPD_SCSI_PORTS;
9831	/* Third-party Copy */
9832	pages->page_list[6] = SVPD_SCSI_TPC;
9833	/* Block limits */
9834	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9835	/* Block Device Characteristics */
9836	pages->page_list[8] = SVPD_BDC;
9837	/* Logical Block Provisioning */
9838	pages->page_list[9] = SVPD_LBP;
9839
9840	ctsio->scsi_status = SCSI_STATUS_OK;
9841
9842	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9843	ctsio->be_move_done = ctl_config_move_done;
9844	ctl_datamove((union ctl_io *)ctsio);
9845
9846	return (CTL_RETVAL_COMPLETE);
9847}
9848
9849static int
9850ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9851{
9852	struct scsi_vpd_unit_serial_number *sn_ptr;
9853	struct ctl_lun *lun;
9854
9855	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9856
9857	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9858	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9859	ctsio->kern_sg_entries = 0;
9860
9861	if (sizeof(*sn_ptr) < alloc_len) {
9862		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9863		ctsio->kern_data_len = sizeof(*sn_ptr);
9864		ctsio->kern_total_len = sizeof(*sn_ptr);
9865	} else {
9866		ctsio->residual = 0;
9867		ctsio->kern_data_len = alloc_len;
9868		ctsio->kern_total_len = alloc_len;
9869	}
9870	ctsio->kern_data_resid = 0;
9871	ctsio->kern_rel_offset = 0;
9872	ctsio->kern_sg_entries = 0;
9873
9874	/*
9875	 * The control device is always connected.  The disk device, on the
9876	 * other hand, may not be online all the time.  Need to change this
9877	 * to figure out whether the disk device is actually online or not.
9878	 */
9879	if (lun != NULL)
9880		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9881				  lun->be_lun->lun_type;
9882	else
9883		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9884
9885	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9886	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9887	/*
9888	 * If we don't have a LUN, we just leave the serial number as
9889	 * all spaces.
9890	 */
9891	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9892	if (lun != NULL) {
9893		strncpy((char *)sn_ptr->serial_num,
9894			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9895	}
9896	ctsio->scsi_status = SCSI_STATUS_OK;
9897
9898	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9899	ctsio->be_move_done = ctl_config_move_done;
9900	ctl_datamove((union ctl_io *)ctsio);
9901
9902	return (CTL_RETVAL_COMPLETE);
9903}
9904
9905
9906static int
9907ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9908{
9909	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9910	struct ctl_lun *lun;
9911	int data_len;
9912
9913	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9914
9915	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9916	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9917	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9918	ctsio->kern_sg_entries = 0;
9919
9920	if (data_len < alloc_len) {
9921		ctsio->residual = alloc_len - data_len;
9922		ctsio->kern_data_len = data_len;
9923		ctsio->kern_total_len = data_len;
9924	} else {
9925		ctsio->residual = 0;
9926		ctsio->kern_data_len = alloc_len;
9927		ctsio->kern_total_len = alloc_len;
9928	}
9929	ctsio->kern_data_resid = 0;
9930	ctsio->kern_rel_offset = 0;
9931	ctsio->kern_sg_entries = 0;
9932
9933	/*
9934	 * The control device is always connected.  The disk device, on the
9935	 * other hand, may not be online all the time.
9936	 */
9937	if (lun != NULL)
9938		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9939				     lun->be_lun->lun_type;
9940	else
9941		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9942	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9943	eid_ptr->page_length = data_len - 4;
9944	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9945	eid_ptr->flags3 = SVPD_EID_V_SUP;
9946
9947	ctsio->scsi_status = SCSI_STATUS_OK;
9948	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9949	ctsio->be_move_done = ctl_config_move_done;
9950	ctl_datamove((union ctl_io *)ctsio);
9951
9952	return (CTL_RETVAL_COMPLETE);
9953}
9954
9955static int
9956ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9957{
9958	struct scsi_vpd_mode_page_policy *mpp_ptr;
9959	struct ctl_lun *lun;
9960	int data_len;
9961
9962	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9963
9964	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9965	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9966
9967	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9968	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9969	ctsio->kern_sg_entries = 0;
9970
9971	if (data_len < alloc_len) {
9972		ctsio->residual = alloc_len - data_len;
9973		ctsio->kern_data_len = data_len;
9974		ctsio->kern_total_len = data_len;
9975	} else {
9976		ctsio->residual = 0;
9977		ctsio->kern_data_len = alloc_len;
9978		ctsio->kern_total_len = alloc_len;
9979	}
9980	ctsio->kern_data_resid = 0;
9981	ctsio->kern_rel_offset = 0;
9982	ctsio->kern_sg_entries = 0;
9983
9984	/*
9985	 * The control device is always connected.  The disk device, on the
9986	 * other hand, may not be online all the time.
9987	 */
9988	if (lun != NULL)
9989		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9990				     lun->be_lun->lun_type;
9991	else
9992		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9993	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9994	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9995	mpp_ptr->descr[0].page_code = 0x3f;
9996	mpp_ptr->descr[0].subpage_code = 0xff;
9997	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9998
9999	ctsio->scsi_status = SCSI_STATUS_OK;
10000	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10001	ctsio->be_move_done = ctl_config_move_done;
10002	ctl_datamove((union ctl_io *)ctsio);
10003
10004	return (CTL_RETVAL_COMPLETE);
10005}
10006
10007static int
10008ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10009{
10010	struct scsi_vpd_device_id *devid_ptr;
10011	struct scsi_vpd_id_descriptor *desc;
10012	struct ctl_softc *ctl_softc;
10013	struct ctl_lun *lun;
10014	struct ctl_port *port;
10015	int data_len;
10016	uint8_t proto;
10017
10018	ctl_softc = control_softc;
10019
10020	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10021	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10022
10023	data_len = sizeof(struct scsi_vpd_device_id) +
10024	    sizeof(struct scsi_vpd_id_descriptor) +
10025		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10026	    sizeof(struct scsi_vpd_id_descriptor) +
10027		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10028	if (lun && lun->lun_devid)
10029		data_len += lun->lun_devid->len;
10030	if (port->port_devid)
10031		data_len += port->port_devid->len;
10032	if (port->target_devid)
10033		data_len += port->target_devid->len;
10034
10035	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10036	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10037	ctsio->kern_sg_entries = 0;
10038
10039	if (data_len < alloc_len) {
10040		ctsio->residual = alloc_len - data_len;
10041		ctsio->kern_data_len = data_len;
10042		ctsio->kern_total_len = data_len;
10043	} else {
10044		ctsio->residual = 0;
10045		ctsio->kern_data_len = alloc_len;
10046		ctsio->kern_total_len = alloc_len;
10047	}
10048	ctsio->kern_data_resid = 0;
10049	ctsio->kern_rel_offset = 0;
10050	ctsio->kern_sg_entries = 0;
10051
10052	/*
10053	 * The control device is always connected.  The disk device, on the
10054	 * other hand, may not be online all the time.
10055	 */
10056	if (lun != NULL)
10057		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10058				     lun->be_lun->lun_type;
10059	else
10060		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10061	devid_ptr->page_code = SVPD_DEVICE_ID;
10062	scsi_ulto2b(data_len - 4, devid_ptr->length);
10063
10064	if (port->port_type == CTL_PORT_FC)
10065		proto = SCSI_PROTO_FC << 4;
10066	else if (port->port_type == CTL_PORT_ISCSI)
10067		proto = SCSI_PROTO_ISCSI << 4;
10068	else
10069		proto = SCSI_PROTO_SPI << 4;
10070	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10071
10072	/*
10073	 * We're using a LUN association here.  i.e., this device ID is a
10074	 * per-LUN identifier.
10075	 */
10076	if (lun && lun->lun_devid) {
10077		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10078		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10079		    lun->lun_devid->len);
10080	}
10081
10082	/*
10083	 * This is for the WWPN which is a port association.
10084	 */
10085	if (port->port_devid) {
10086		memcpy(desc, port->port_devid->data, port->port_devid->len);
10087		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10088		    port->port_devid->len);
10089	}
10090
10091	/*
10092	 * This is for the Relative Target Port(type 4h) identifier
10093	 */
10094	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10095	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10096	    SVPD_ID_TYPE_RELTARG;
10097	desc->length = 4;
10098	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10099	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10100	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10101
10102	/*
10103	 * This is for the Target Port Group(type 5h) identifier
10104	 */
10105	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10106	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10107	    SVPD_ID_TYPE_TPORTGRP;
10108	desc->length = 4;
10109	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10110	    &desc->identifier[2]);
10111	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10112	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10113
10114	/*
10115	 * This is for the Target identifier
10116	 */
10117	if (port->target_devid) {
10118		memcpy(desc, port->target_devid->data, port->target_devid->len);
10119	}
10120
10121	ctsio->scsi_status = SCSI_STATUS_OK;
10122	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10123	ctsio->be_move_done = ctl_config_move_done;
10124	ctl_datamove((union ctl_io *)ctsio);
10125
10126	return (CTL_RETVAL_COMPLETE);
10127}
10128
10129static int
10130ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10131{
10132	struct ctl_softc *softc = control_softc;
10133	struct scsi_vpd_scsi_ports *sp;
10134	struct scsi_vpd_port_designation *pd;
10135	struct scsi_vpd_port_designation_cont *pdc;
10136	struct ctl_lun *lun;
10137	struct ctl_port *port;
10138	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10139	int num_target_port_groups, single;
10140
10141	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10142
10143	single = ctl_is_single;
10144	if (single)
10145		num_target_port_groups = 1;
10146	else
10147		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10148	num_target_ports = 0;
10149	iid_len = 0;
10150	id_len = 0;
10151	mtx_lock(&softc->ctl_lock);
10152	STAILQ_FOREACH(port, &softc->port_list, links) {
10153		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10154			continue;
10155		if (lun != NULL &&
10156		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10157		    CTL_MAX_LUNS)
10158			continue;
10159		num_target_ports++;
10160		if (port->init_devid)
10161			iid_len += port->init_devid->len;
10162		if (port->port_devid)
10163			id_len += port->port_devid->len;
10164	}
10165	mtx_unlock(&softc->ctl_lock);
10166
10167	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10168	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10169	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10170	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10171	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10172	ctsio->kern_sg_entries = 0;
10173
10174	if (data_len < alloc_len) {
10175		ctsio->residual = alloc_len - data_len;
10176		ctsio->kern_data_len = data_len;
10177		ctsio->kern_total_len = data_len;
10178	} else {
10179		ctsio->residual = 0;
10180		ctsio->kern_data_len = alloc_len;
10181		ctsio->kern_total_len = alloc_len;
10182	}
10183	ctsio->kern_data_resid = 0;
10184	ctsio->kern_rel_offset = 0;
10185	ctsio->kern_sg_entries = 0;
10186
10187	/*
10188	 * The control device is always connected.  The disk device, on the
10189	 * other hand, may not be online all the time.  Need to change this
10190	 * to figure out whether the disk device is actually online or not.
10191	 */
10192	if (lun != NULL)
10193		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10194				  lun->be_lun->lun_type;
10195	else
10196		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10197
10198	sp->page_code = SVPD_SCSI_PORTS;
10199	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10200	    sp->page_length);
10201	pd = &sp->design[0];
10202
10203	mtx_lock(&softc->ctl_lock);
10204	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10205		pg = 0;
10206	else
10207		pg = 1;
10208	for (g = 0; g < num_target_port_groups; g++) {
10209		STAILQ_FOREACH(port, &softc->port_list, links) {
10210			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10211				continue;
10212			if (lun != NULL &&
10213			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10214			    CTL_MAX_LUNS)
10215				continue;
10216			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10217			scsi_ulto2b(p, pd->relative_port_id);
10218			if (port->init_devid && g == pg) {
10219				iid_len = port->init_devid->len;
10220				memcpy(pd->initiator_transportid,
10221				    port->init_devid->data, port->init_devid->len);
10222			} else
10223				iid_len = 0;
10224			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10225			pdc = (struct scsi_vpd_port_designation_cont *)
10226			    (&pd->initiator_transportid[iid_len]);
10227			if (port->port_devid && g == pg) {
10228				id_len = port->port_devid->len;
10229				memcpy(pdc->target_port_descriptors,
10230				    port->port_devid->data, port->port_devid->len);
10231			} else
10232				id_len = 0;
10233			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10234			pd = (struct scsi_vpd_port_designation *)
10235			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10236		}
10237	}
10238	mtx_unlock(&softc->ctl_lock);
10239
10240	ctsio->scsi_status = SCSI_STATUS_OK;
10241	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10242	ctsio->be_move_done = ctl_config_move_done;
10243	ctl_datamove((union ctl_io *)ctsio);
10244
10245	return (CTL_RETVAL_COMPLETE);
10246}
10247
10248static int
10249ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10250{
10251	struct scsi_vpd_block_limits *bl_ptr;
10252	struct ctl_lun *lun;
10253	int bs;
10254
10255	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10256
10257	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10258	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10259	ctsio->kern_sg_entries = 0;
10260
10261	if (sizeof(*bl_ptr) < alloc_len) {
10262		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10263		ctsio->kern_data_len = sizeof(*bl_ptr);
10264		ctsio->kern_total_len = sizeof(*bl_ptr);
10265	} else {
10266		ctsio->residual = 0;
10267		ctsio->kern_data_len = alloc_len;
10268		ctsio->kern_total_len = alloc_len;
10269	}
10270	ctsio->kern_data_resid = 0;
10271	ctsio->kern_rel_offset = 0;
10272	ctsio->kern_sg_entries = 0;
10273
10274	/*
10275	 * The control device is always connected.  The disk device, on the
10276	 * other hand, may not be online all the time.  Need to change this
10277	 * to figure out whether the disk device is actually online or not.
10278	 */
10279	if (lun != NULL)
10280		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10281				  lun->be_lun->lun_type;
10282	else
10283		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10284
10285	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10286	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10287	bl_ptr->max_cmp_write_len = 0xff;
10288	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10289	if (lun != NULL) {
10290		bs = lun->be_lun->blocksize;
10291		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10292		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10293			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10294			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10295			if (lun->be_lun->pblockexp != 0) {
10296				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10297				    bl_ptr->opt_unmap_grain);
10298				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10299				    bl_ptr->unmap_grain_align);
10300			}
10301		}
10302	}
10303	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10304
10305	ctsio->scsi_status = SCSI_STATUS_OK;
10306	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10307	ctsio->be_move_done = ctl_config_move_done;
10308	ctl_datamove((union ctl_io *)ctsio);
10309
10310	return (CTL_RETVAL_COMPLETE);
10311}
10312
10313static int
10314ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10315{
10316	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10317	struct ctl_lun *lun;
10318
10319	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10320
10321	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10322	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10323	ctsio->kern_sg_entries = 0;
10324
10325	if (sizeof(*bdc_ptr) < alloc_len) {
10326		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10327		ctsio->kern_data_len = sizeof(*bdc_ptr);
10328		ctsio->kern_total_len = sizeof(*bdc_ptr);
10329	} else {
10330		ctsio->residual = 0;
10331		ctsio->kern_data_len = alloc_len;
10332		ctsio->kern_total_len = alloc_len;
10333	}
10334	ctsio->kern_data_resid = 0;
10335	ctsio->kern_rel_offset = 0;
10336	ctsio->kern_sg_entries = 0;
10337
10338	/*
10339	 * The control device is always connected.  The disk device, on the
10340	 * other hand, may not be online all the time.  Need to change this
10341	 * to figure out whether the disk device is actually online or not.
10342	 */
10343	if (lun != NULL)
10344		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10345				  lun->be_lun->lun_type;
10346	else
10347		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10348	bdc_ptr->page_code = SVPD_BDC;
10349	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10350	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10351	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10352
10353	ctsio->scsi_status = SCSI_STATUS_OK;
10354	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10355	ctsio->be_move_done = ctl_config_move_done;
10356	ctl_datamove((union ctl_io *)ctsio);
10357
10358	return (CTL_RETVAL_COMPLETE);
10359}
10360
10361static int
10362ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10363{
10364	struct scsi_vpd_logical_block_prov *lbp_ptr;
10365	struct ctl_lun *lun;
10366
10367	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10368
10369	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10370	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10371	ctsio->kern_sg_entries = 0;
10372
10373	if (sizeof(*lbp_ptr) < alloc_len) {
10374		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10375		ctsio->kern_data_len = sizeof(*lbp_ptr);
10376		ctsio->kern_total_len = sizeof(*lbp_ptr);
10377	} else {
10378		ctsio->residual = 0;
10379		ctsio->kern_data_len = alloc_len;
10380		ctsio->kern_total_len = alloc_len;
10381	}
10382	ctsio->kern_data_resid = 0;
10383	ctsio->kern_rel_offset = 0;
10384	ctsio->kern_sg_entries = 0;
10385
10386	/*
10387	 * The control device is always connected.  The disk device, on the
10388	 * other hand, may not be online all the time.  Need to change this
10389	 * to figure out whether the disk device is actually online or not.
10390	 */
10391	if (lun != NULL)
10392		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10393				  lun->be_lun->lun_type;
10394	else
10395		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10396
10397	lbp_ptr->page_code = SVPD_LBP;
10398	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10399	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10400		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10401		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10402		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10403	}
10404
10405	ctsio->scsi_status = SCSI_STATUS_OK;
10406	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10407	ctsio->be_move_done = ctl_config_move_done;
10408	ctl_datamove((union ctl_io *)ctsio);
10409
10410	return (CTL_RETVAL_COMPLETE);
10411}
10412
10413static int
10414ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10415{
10416	struct scsi_inquiry *cdb;
10417	struct ctl_lun *lun;
10418	int alloc_len, retval;
10419
10420	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10421	cdb = (struct scsi_inquiry *)ctsio->cdb;
10422
10423	retval = CTL_RETVAL_COMPLETE;
10424
10425	alloc_len = scsi_2btoul(cdb->length);
10426
10427	switch (cdb->page_code) {
10428	case SVPD_SUPPORTED_PAGES:
10429		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10430		break;
10431	case SVPD_UNIT_SERIAL_NUMBER:
10432		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10433		break;
10434	case SVPD_DEVICE_ID:
10435		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10436		break;
10437	case SVPD_EXTENDED_INQUIRY_DATA:
10438		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10439		break;
10440	case SVPD_MODE_PAGE_POLICY:
10441		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10442		break;
10443	case SVPD_SCSI_PORTS:
10444		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10445		break;
10446	case SVPD_SCSI_TPC:
10447		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10448		break;
10449	case SVPD_BLOCK_LIMITS:
10450		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10451		break;
10452	case SVPD_BDC:
10453		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10454		break;
10455	case SVPD_LBP:
10456		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10457		break;
10458	default:
10459		ctl_set_invalid_field(ctsio,
10460				      /*sks_valid*/ 1,
10461				      /*command*/ 1,
10462				      /*field*/ 2,
10463				      /*bit_valid*/ 0,
10464				      /*bit*/ 0);
10465		ctl_done((union ctl_io *)ctsio);
10466		retval = CTL_RETVAL_COMPLETE;
10467		break;
10468	}
10469
10470	return (retval);
10471}
10472
10473static int
10474ctl_inquiry_std(struct ctl_scsiio *ctsio)
10475{
10476	struct scsi_inquiry_data *inq_ptr;
10477	struct scsi_inquiry *cdb;
10478	struct ctl_softc *ctl_softc;
10479	struct ctl_lun *lun;
10480	char *val;
10481	uint32_t alloc_len, data_len;
10482	ctl_port_type port_type;
10483
10484	ctl_softc = control_softc;
10485
10486	/*
10487	 * Figure out whether we're talking to a Fibre Channel port or not.
10488	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10489	 * SCSI front ends.
10490	 */
10491	port_type = ctl_softc->ctl_ports[
10492	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10493	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10494		port_type = CTL_PORT_SCSI;
10495
10496	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10497	cdb = (struct scsi_inquiry *)ctsio->cdb;
10498	alloc_len = scsi_2btoul(cdb->length);
10499
10500	/*
10501	 * We malloc the full inquiry data size here and fill it
10502	 * in.  If the user only asks for less, we'll give him
10503	 * that much.
10504	 */
10505	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10506	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10507	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10508	ctsio->kern_sg_entries = 0;
10509	ctsio->kern_data_resid = 0;
10510	ctsio->kern_rel_offset = 0;
10511
10512	if (data_len < alloc_len) {
10513		ctsio->residual = alloc_len - data_len;
10514		ctsio->kern_data_len = data_len;
10515		ctsio->kern_total_len = data_len;
10516	} else {
10517		ctsio->residual = 0;
10518		ctsio->kern_data_len = alloc_len;
10519		ctsio->kern_total_len = alloc_len;
10520	}
10521
10522	/*
10523	 * If we have a LUN configured, report it as connected.  Otherwise,
10524	 * report that it is offline or no device is supported, depending
10525	 * on the value of inquiry_pq_no_lun.
10526	 *
10527	 * According to the spec (SPC-4 r34), the peripheral qualifier
10528	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10529	 *
10530	 * "A peripheral device having the specified peripheral device type
10531	 * is not connected to this logical unit. However, the device
10532	 * server is capable of supporting the specified peripheral device
10533	 * type on this logical unit."
10534	 *
10535	 * According to the same spec, the peripheral qualifier
10536	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10537	 *
10538	 * "The device server is not capable of supporting a peripheral
10539	 * device on this logical unit. For this peripheral qualifier the
10540	 * peripheral device type shall be set to 1Fh. All other peripheral
10541	 * device type values are reserved for this peripheral qualifier."
10542	 *
10543	 * Given the text, it would seem that we probably want to report that
10544	 * the LUN is offline here.  There is no LUN connected, but we can
10545	 * support a LUN at the given LUN number.
10546	 *
10547	 * In the real world, though, it sounds like things are a little
10548	 * different:
10549	 *
10550	 * - Linux, when presented with a LUN with the offline peripheral
10551	 *   qualifier, will create an sg driver instance for it.  So when
10552	 *   you attach it to CTL, you wind up with a ton of sg driver
10553	 *   instances.  (One for every LUN that Linux bothered to probe.)
10554	 *   Linux does this despite the fact that it issues a REPORT LUNs
10555	 *   to LUN 0 to get the inventory of supported LUNs.
10556	 *
10557	 * - There is other anecdotal evidence (from Emulex folks) about
10558	 *   arrays that use the offline peripheral qualifier for LUNs that
10559	 *   are on the "passive" path in an active/passive array.
10560	 *
10561	 * So the solution is provide a hopefully reasonable default
10562	 * (return bad/no LUN) and allow the user to change the behavior
10563	 * with a tunable/sysctl variable.
10564	 */
10565	if (lun != NULL)
10566		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10567				  lun->be_lun->lun_type;
10568	else if (ctl_softc->inquiry_pq_no_lun == 0)
10569		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10570	else
10571		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10572
10573	/* RMB in byte 2 is 0 */
10574	inq_ptr->version = SCSI_REV_SPC4;
10575
10576	/*
10577	 * According to SAM-3, even if a device only supports a single
10578	 * level of LUN addressing, it should still set the HISUP bit:
10579	 *
10580	 * 4.9.1 Logical unit numbers overview
10581	 *
10582	 * All logical unit number formats described in this standard are
10583	 * hierarchical in structure even when only a single level in that
10584	 * hierarchy is used. The HISUP bit shall be set to one in the
10585	 * standard INQUIRY data (see SPC-2) when any logical unit number
10586	 * format described in this standard is used.  Non-hierarchical
10587	 * formats are outside the scope of this standard.
10588	 *
10589	 * Therefore we set the HiSup bit here.
10590	 *
10591	 * The reponse format is 2, per SPC-3.
10592	 */
10593	inq_ptr->response_format = SID_HiSup | 2;
10594
10595	inq_ptr->additional_length = data_len -
10596	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10597	CTL_DEBUG_PRINT(("additional_length = %d\n",
10598			 inq_ptr->additional_length));
10599
10600	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10601	/* 16 bit addressing */
10602	if (port_type == CTL_PORT_SCSI)
10603		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10604	/* XXX set the SID_MultiP bit here if we're actually going to
10605	   respond on multiple ports */
10606	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10607
10608	/* 16 bit data bus, synchronous transfers */
10609	if (port_type == CTL_PORT_SCSI)
10610		inq_ptr->flags = SID_WBus16 | SID_Sync;
10611	/*
10612	 * XXX KDM do we want to support tagged queueing on the control
10613	 * device at all?
10614	 */
10615	if ((lun == NULL)
10616	 || (lun->be_lun->lun_type != T_PROCESSOR))
10617		inq_ptr->flags |= SID_CmdQue;
10618	/*
10619	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10620	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10621	 * name and 4 bytes for the revision.
10622	 */
10623	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10624	    "vendor")) == NULL) {
10625		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10626	} else {
10627		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10628		strncpy(inq_ptr->vendor, val,
10629		    min(sizeof(inq_ptr->vendor), strlen(val)));
10630	}
10631	if (lun == NULL) {
10632		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10633		    sizeof(inq_ptr->product));
10634	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10635		switch (lun->be_lun->lun_type) {
10636		case T_DIRECT:
10637			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10638			    sizeof(inq_ptr->product));
10639			break;
10640		case T_PROCESSOR:
10641			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10642			    sizeof(inq_ptr->product));
10643			break;
10644		default:
10645			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10646			    sizeof(inq_ptr->product));
10647			break;
10648		}
10649	} else {
10650		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10651		strncpy(inq_ptr->product, val,
10652		    min(sizeof(inq_ptr->product), strlen(val)));
10653	}
10654
10655	/*
10656	 * XXX make this a macro somewhere so it automatically gets
10657	 * incremented when we make changes.
10658	 */
10659	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10660	    "revision")) == NULL) {
10661		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10662	} else {
10663		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10664		strncpy(inq_ptr->revision, val,
10665		    min(sizeof(inq_ptr->revision), strlen(val)));
10666	}
10667
10668	/*
10669	 * For parallel SCSI, we support double transition and single
10670	 * transition clocking.  We also support QAS (Quick Arbitration
10671	 * and Selection) and Information Unit transfers on both the
10672	 * control and array devices.
10673	 */
10674	if (port_type == CTL_PORT_SCSI)
10675		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10676				    SID_SPI_IUS;
10677
10678	/* SAM-5 (no version claimed) */
10679	scsi_ulto2b(0x00A0, inq_ptr->version1);
10680	/* SPC-4 (no version claimed) */
10681	scsi_ulto2b(0x0460, inq_ptr->version2);
10682	if (port_type == CTL_PORT_FC) {
10683		/* FCP-2 ANSI INCITS.350:2003 */
10684		scsi_ulto2b(0x0917, inq_ptr->version3);
10685	} else if (port_type == CTL_PORT_SCSI) {
10686		/* SPI-4 ANSI INCITS.362:200x */
10687		scsi_ulto2b(0x0B56, inq_ptr->version3);
10688	} else if (port_type == CTL_PORT_ISCSI) {
10689		/* iSCSI (no version claimed) */
10690		scsi_ulto2b(0x0960, inq_ptr->version3);
10691	} else if (port_type == CTL_PORT_SAS) {
10692		/* SAS (no version claimed) */
10693		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10694	}
10695
10696	if (lun == NULL) {
10697		/* SBC-3 (no version claimed) */
10698		scsi_ulto2b(0x04C0, inq_ptr->version4);
10699	} else {
10700		switch (lun->be_lun->lun_type) {
10701		case T_DIRECT:
10702			/* SBC-3 (no version claimed) */
10703			scsi_ulto2b(0x04C0, inq_ptr->version4);
10704			break;
10705		case T_PROCESSOR:
10706		default:
10707			break;
10708		}
10709	}
10710
10711	ctsio->scsi_status = SCSI_STATUS_OK;
10712	if (ctsio->kern_data_len > 0) {
10713		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10714		ctsio->be_move_done = ctl_config_move_done;
10715		ctl_datamove((union ctl_io *)ctsio);
10716	} else {
10717		ctsio->io_hdr.status = CTL_SUCCESS;
10718		ctl_done((union ctl_io *)ctsio);
10719	}
10720
10721	return (CTL_RETVAL_COMPLETE);
10722}
10723
10724int
10725ctl_inquiry(struct ctl_scsiio *ctsio)
10726{
10727	struct scsi_inquiry *cdb;
10728	int retval;
10729
10730	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10731
10732	cdb = (struct scsi_inquiry *)ctsio->cdb;
10733	if (cdb->byte2 & SI_EVPD)
10734		retval = ctl_inquiry_evpd(ctsio);
10735	else if (cdb->page_code == 0)
10736		retval = ctl_inquiry_std(ctsio);
10737	else {
10738		ctl_set_invalid_field(ctsio,
10739				      /*sks_valid*/ 1,
10740				      /*command*/ 1,
10741				      /*field*/ 2,
10742				      /*bit_valid*/ 0,
10743				      /*bit*/ 0);
10744		ctl_done((union ctl_io *)ctsio);
10745		return (CTL_RETVAL_COMPLETE);
10746	}
10747
10748	return (retval);
10749}
10750
10751/*
10752 * For known CDB types, parse the LBA and length.
10753 */
10754static int
10755ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10756{
10757	if (io->io_hdr.io_type != CTL_IO_SCSI)
10758		return (1);
10759
10760	switch (io->scsiio.cdb[0]) {
10761	case COMPARE_AND_WRITE: {
10762		struct scsi_compare_and_write *cdb;
10763
10764		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10765
10766		*lba = scsi_8btou64(cdb->addr);
10767		*len = cdb->length;
10768		break;
10769	}
10770	case READ_6:
10771	case WRITE_6: {
10772		struct scsi_rw_6 *cdb;
10773
10774		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10775
10776		*lba = scsi_3btoul(cdb->addr);
10777		/* only 5 bits are valid in the most significant address byte */
10778		*lba &= 0x1fffff;
10779		*len = cdb->length;
10780		break;
10781	}
10782	case READ_10:
10783	case WRITE_10: {
10784		struct scsi_rw_10 *cdb;
10785
10786		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10787
10788		*lba = scsi_4btoul(cdb->addr);
10789		*len = scsi_2btoul(cdb->length);
10790		break;
10791	}
10792	case WRITE_VERIFY_10: {
10793		struct scsi_write_verify_10 *cdb;
10794
10795		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10796
10797		*lba = scsi_4btoul(cdb->addr);
10798		*len = scsi_2btoul(cdb->length);
10799		break;
10800	}
10801	case READ_12:
10802	case WRITE_12: {
10803		struct scsi_rw_12 *cdb;
10804
10805		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10806
10807		*lba = scsi_4btoul(cdb->addr);
10808		*len = scsi_4btoul(cdb->length);
10809		break;
10810	}
10811	case WRITE_VERIFY_12: {
10812		struct scsi_write_verify_12 *cdb;
10813
10814		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10815
10816		*lba = scsi_4btoul(cdb->addr);
10817		*len = scsi_4btoul(cdb->length);
10818		break;
10819	}
10820	case READ_16:
10821	case WRITE_16: {
10822		struct scsi_rw_16 *cdb;
10823
10824		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10825
10826		*lba = scsi_8btou64(cdb->addr);
10827		*len = scsi_4btoul(cdb->length);
10828		break;
10829	}
10830	case WRITE_VERIFY_16: {
10831		struct scsi_write_verify_16 *cdb;
10832
10833		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10834
10835
10836		*lba = scsi_8btou64(cdb->addr);
10837		*len = scsi_4btoul(cdb->length);
10838		break;
10839	}
10840	case WRITE_SAME_10: {
10841		struct scsi_write_same_10 *cdb;
10842
10843		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10844
10845		*lba = scsi_4btoul(cdb->addr);
10846		*len = scsi_2btoul(cdb->length);
10847		break;
10848	}
10849	case WRITE_SAME_16: {
10850		struct scsi_write_same_16 *cdb;
10851
10852		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10853
10854		*lba = scsi_8btou64(cdb->addr);
10855		*len = scsi_4btoul(cdb->length);
10856		break;
10857	}
10858	case VERIFY_10: {
10859		struct scsi_verify_10 *cdb;
10860
10861		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10862
10863		*lba = scsi_4btoul(cdb->addr);
10864		*len = scsi_2btoul(cdb->length);
10865		break;
10866	}
10867	case VERIFY_12: {
10868		struct scsi_verify_12 *cdb;
10869
10870		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10871
10872		*lba = scsi_4btoul(cdb->addr);
10873		*len = scsi_4btoul(cdb->length);
10874		break;
10875	}
10876	case VERIFY_16: {
10877		struct scsi_verify_16 *cdb;
10878
10879		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10880
10881		*lba = scsi_8btou64(cdb->addr);
10882		*len = scsi_4btoul(cdb->length);
10883		break;
10884	}
10885	case UNMAP: {
10886		*lba = 0;
10887		*len = UINT64_MAX;
10888		break;
10889	}
10890	default:
10891		return (1);
10892		break; /* NOTREACHED */
10893	}
10894
10895	return (0);
10896}
10897
10898static ctl_action
10899ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10900{
10901	uint64_t endlba1, endlba2;
10902
10903	endlba1 = lba1 + len1 - 1;
10904	endlba2 = lba2 + len2 - 1;
10905
10906	if ((endlba1 < lba2)
10907	 || (endlba2 < lba1))
10908		return (CTL_ACTION_PASS);
10909	else
10910		return (CTL_ACTION_BLOCK);
10911}
10912
10913static int
10914ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10915{
10916	struct ctl_ptr_len_flags *ptrlen;
10917	struct scsi_unmap_desc *buf, *end, *range;
10918	uint64_t lba;
10919	uint32_t len;
10920
10921	/* If not UNMAP -- go other way. */
10922	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10923	    io->scsiio.cdb[0] != UNMAP)
10924		return (CTL_ACTION_ERROR);
10925
10926	/* If UNMAP without data -- block and wait for data. */
10927	ptrlen = (struct ctl_ptr_len_flags *)
10928	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10929	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10930	    ptrlen->ptr == NULL)
10931		return (CTL_ACTION_BLOCK);
10932
10933	/* UNMAP with data -- check for collision. */
10934	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10935	end = buf + ptrlen->len / sizeof(*buf);
10936	for (range = buf; range < end; range++) {
10937		lba = scsi_8btou64(range->lba);
10938		len = scsi_4btoul(range->length);
10939		if ((lba < lba2 + len2) && (lba + len > lba2))
10940			return (CTL_ACTION_BLOCK);
10941	}
10942	return (CTL_ACTION_PASS);
10943}
10944
10945static ctl_action
10946ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10947{
10948	uint64_t lba1, lba2;
10949	uint64_t len1, len2;
10950	int retval;
10951
10952	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10953		return (CTL_ACTION_ERROR);
10954
10955	retval = ctl_extent_check_unmap(io2, lba1, len1);
10956	if (retval != CTL_ACTION_ERROR)
10957		return (retval);
10958
10959	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10960		return (CTL_ACTION_ERROR);
10961
10962	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10963}
10964
10965static ctl_action
10966ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10967    union ctl_io *ooa_io)
10968{
10969	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10970	ctl_serialize_action *serialize_row;
10971
10972	/*
10973	 * The initiator attempted multiple untagged commands at the same
10974	 * time.  Can't do that.
10975	 */
10976	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10977	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10978	 && ((pending_io->io_hdr.nexus.targ_port ==
10979	      ooa_io->io_hdr.nexus.targ_port)
10980	  && (pending_io->io_hdr.nexus.initid.id ==
10981	      ooa_io->io_hdr.nexus.initid.id))
10982	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10983		return (CTL_ACTION_OVERLAP);
10984
10985	/*
10986	 * The initiator attempted to send multiple tagged commands with
10987	 * the same ID.  (It's fine if different initiators have the same
10988	 * tag ID.)
10989	 *
10990	 * Even if all of those conditions are true, we don't kill the I/O
10991	 * if the command ahead of us has been aborted.  We won't end up
10992	 * sending it to the FETD, and it's perfectly legal to resend a
10993	 * command with the same tag number as long as the previous
10994	 * instance of this tag number has been aborted somehow.
10995	 */
10996	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10997	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10998	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10999	 && ((pending_io->io_hdr.nexus.targ_port ==
11000	      ooa_io->io_hdr.nexus.targ_port)
11001	  && (pending_io->io_hdr.nexus.initid.id ==
11002	      ooa_io->io_hdr.nexus.initid.id))
11003	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11004		return (CTL_ACTION_OVERLAP_TAG);
11005
11006	/*
11007	 * If we get a head of queue tag, SAM-3 says that we should
11008	 * immediately execute it.
11009	 *
11010	 * What happens if this command would normally block for some other
11011	 * reason?  e.g. a request sense with a head of queue tag
11012	 * immediately after a write.  Normally that would block, but this
11013	 * will result in its getting executed immediately...
11014	 *
11015	 * We currently return "pass" instead of "skip", so we'll end up
11016	 * going through the rest of the queue to check for overlapped tags.
11017	 *
11018	 * XXX KDM check for other types of blockage first??
11019	 */
11020	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11021		return (CTL_ACTION_PASS);
11022
11023	/*
11024	 * Ordered tags have to block until all items ahead of them
11025	 * have completed.  If we get called with an ordered tag, we always
11026	 * block, if something else is ahead of us in the queue.
11027	 */
11028	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11029		return (CTL_ACTION_BLOCK);
11030
11031	/*
11032	 * Simple tags get blocked until all head of queue and ordered tags
11033	 * ahead of them have completed.  I'm lumping untagged commands in
11034	 * with simple tags here.  XXX KDM is that the right thing to do?
11035	 */
11036	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11037	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11038	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11039	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11040		return (CTL_ACTION_BLOCK);
11041
11042	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11043	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11044
11045	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11046
11047	switch (serialize_row[pending_entry->seridx]) {
11048	case CTL_SER_BLOCK:
11049		return (CTL_ACTION_BLOCK);
11050	case CTL_SER_EXTENT:
11051		return (ctl_extent_check(pending_io, ooa_io));
11052	case CTL_SER_EXTENTOPT:
11053		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11054		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11055			return (ctl_extent_check(pending_io, ooa_io));
11056		/* FALLTHROUGH */
11057	case CTL_SER_PASS:
11058		return (CTL_ACTION_PASS);
11059	case CTL_SER_BLOCKOPT:
11060		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11061		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11062			return (CTL_ACTION_BLOCK);
11063		return (CTL_ACTION_PASS);
11064	case CTL_SER_SKIP:
11065		return (CTL_ACTION_SKIP);
11066	default:
11067		panic("invalid serialization value %d",
11068		      serialize_row[pending_entry->seridx]);
11069	}
11070
11071	return (CTL_ACTION_ERROR);
11072}
11073
11074/*
11075 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11076 * Assumptions:
11077 * - pending_io is generally either incoming, or on the blocked queue
11078 * - starting I/O is the I/O we want to start the check with.
11079 */
11080static ctl_action
11081ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11082	      union ctl_io *starting_io)
11083{
11084	union ctl_io *ooa_io;
11085	ctl_action action;
11086
11087	mtx_assert(&lun->lun_lock, MA_OWNED);
11088
11089	/*
11090	 * Run back along the OOA queue, starting with the current
11091	 * blocked I/O and going through every I/O before it on the
11092	 * queue.  If starting_io is NULL, we'll just end up returning
11093	 * CTL_ACTION_PASS.
11094	 */
11095	for (ooa_io = starting_io; ooa_io != NULL;
11096	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11097	     ooa_links)){
11098
11099		/*
11100		 * This routine just checks to see whether
11101		 * cur_blocked is blocked by ooa_io, which is ahead
11102		 * of it in the queue.  It doesn't queue/dequeue
11103		 * cur_blocked.
11104		 */
11105		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11106		switch (action) {
11107		case CTL_ACTION_BLOCK:
11108		case CTL_ACTION_OVERLAP:
11109		case CTL_ACTION_OVERLAP_TAG:
11110		case CTL_ACTION_SKIP:
11111		case CTL_ACTION_ERROR:
11112			return (action);
11113			break; /* NOTREACHED */
11114		case CTL_ACTION_PASS:
11115			break;
11116		default:
11117			panic("invalid action %d", action);
11118			break;  /* NOTREACHED */
11119		}
11120	}
11121
11122	return (CTL_ACTION_PASS);
11123}
11124
11125/*
11126 * Assumptions:
11127 * - An I/O has just completed, and has been removed from the per-LUN OOA
11128 *   queue, so some items on the blocked queue may now be unblocked.
11129 */
11130static int
11131ctl_check_blocked(struct ctl_lun *lun)
11132{
11133	union ctl_io *cur_blocked, *next_blocked;
11134
11135	mtx_assert(&lun->lun_lock, MA_OWNED);
11136
11137	/*
11138	 * Run forward from the head of the blocked queue, checking each
11139	 * entry against the I/Os prior to it on the OOA queue to see if
11140	 * there is still any blockage.
11141	 *
11142	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11143	 * with our removing a variable on it while it is traversing the
11144	 * list.
11145	 */
11146	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11147	     cur_blocked != NULL; cur_blocked = next_blocked) {
11148		union ctl_io *prev_ooa;
11149		ctl_action action;
11150
11151		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11152							  blocked_links);
11153
11154		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11155						      ctl_ooaq, ooa_links);
11156
11157		/*
11158		 * If cur_blocked happens to be the first item in the OOA
11159		 * queue now, prev_ooa will be NULL, and the action
11160		 * returned will just be CTL_ACTION_PASS.
11161		 */
11162		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11163
11164		switch (action) {
11165		case CTL_ACTION_BLOCK:
11166			/* Nothing to do here, still blocked */
11167			break;
11168		case CTL_ACTION_OVERLAP:
11169		case CTL_ACTION_OVERLAP_TAG:
11170			/*
11171			 * This shouldn't happen!  In theory we've already
11172			 * checked this command for overlap...
11173			 */
11174			break;
11175		case CTL_ACTION_PASS:
11176		case CTL_ACTION_SKIP: {
11177			struct ctl_softc *softc;
11178			const struct ctl_cmd_entry *entry;
11179			uint32_t initidx;
11180			int isc_retval;
11181
11182			/*
11183			 * The skip case shouldn't happen, this transaction
11184			 * should have never made it onto the blocked queue.
11185			 */
11186			/*
11187			 * This I/O is no longer blocked, we can remove it
11188			 * from the blocked queue.  Since this is a TAILQ
11189			 * (doubly linked list), we can do O(1) removals
11190			 * from any place on the list.
11191			 */
11192			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11193				     blocked_links);
11194			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11195
11196			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11197				/*
11198				 * Need to send IO back to original side to
11199				 * run
11200				 */
11201				union ctl_ha_msg msg_info;
11202
11203				msg_info.hdr.original_sc =
11204					cur_blocked->io_hdr.original_sc;
11205				msg_info.hdr.serializing_sc = cur_blocked;
11206				msg_info.hdr.msg_type = CTL_MSG_R2R;
11207				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11208				     &msg_info, sizeof(msg_info), 0)) >
11209				     CTL_HA_STATUS_SUCCESS) {
11210					printf("CTL:Check Blocked error from "
11211					       "ctl_ha_msg_send %d\n",
11212					       isc_retval);
11213				}
11214				break;
11215			}
11216			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11217			softc = control_softc;
11218
11219			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11220
11221			/*
11222			 * Check this I/O for LUN state changes that may
11223			 * have happened while this command was blocked.
11224			 * The LUN state may have been changed by a command
11225			 * ahead of us in the queue, so we need to re-check
11226			 * for any states that can be caused by SCSI
11227			 * commands.
11228			 */
11229			if (ctl_scsiio_lun_check(softc, lun, entry,
11230						 &cur_blocked->scsiio) == 0) {
11231				cur_blocked->io_hdr.flags |=
11232				                      CTL_FLAG_IS_WAS_ON_RTR;
11233				ctl_enqueue_rtr(cur_blocked);
11234			} else
11235				ctl_done(cur_blocked);
11236			break;
11237		}
11238		default:
11239			/*
11240			 * This probably shouldn't happen -- we shouldn't
11241			 * get CTL_ACTION_ERROR, or anything else.
11242			 */
11243			break;
11244		}
11245	}
11246
11247	return (CTL_RETVAL_COMPLETE);
11248}
11249
11250/*
11251 * This routine (with one exception) checks LUN flags that can be set by
11252 * commands ahead of us in the OOA queue.  These flags have to be checked
11253 * when a command initially comes in, and when we pull a command off the
11254 * blocked queue and are preparing to execute it.  The reason we have to
11255 * check these flags for commands on the blocked queue is that the LUN
11256 * state may have been changed by a command ahead of us while we're on the
11257 * blocked queue.
11258 *
11259 * Ordering is somewhat important with these checks, so please pay
11260 * careful attention to the placement of any new checks.
11261 */
11262static int
11263ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11264    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11265{
11266	int retval;
11267	uint32_t residx;
11268
11269	retval = 0;
11270
11271	mtx_assert(&lun->lun_lock, MA_OWNED);
11272
11273	/*
11274	 * If this shelf is a secondary shelf controller, we have to reject
11275	 * any media access commands.
11276	 */
11277#if 0
11278	/* No longer needed for HA */
11279	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11280	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11281		ctl_set_lun_standby(ctsio);
11282		retval = 1;
11283		goto bailout;
11284	}
11285#endif
11286
11287	/*
11288	 * Check for a reservation conflict.  If this command isn't allowed
11289	 * even on reserved LUNs, and if this initiator isn't the one who
11290	 * reserved us, reject the command with a reservation conflict.
11291	 */
11292	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11293	if ((lun->flags & CTL_LUN_RESERVED)
11294	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11295		if (lun->res_idx != residx) {
11296			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11297			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11298			retval = 1;
11299			goto bailout;
11300		}
11301	}
11302
11303	if ((lun->flags & CTL_LUN_PR_RESERVED)
11304	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11305		/*
11306		 * if we aren't registered or it's a res holder type
11307		 * reservation and this isn't the res holder then set a
11308		 * conflict.
11309		 * NOTE: Commands which might be allowed on write exclusive
11310		 * type reservations are checked in the particular command
11311		 * for a conflict. Read and SSU are the only ones.
11312		 */
11313		if (!lun->per_res[residx].registered
11314		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11315			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11316			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11317			retval = 1;
11318			goto bailout;
11319		}
11320
11321	}
11322
11323	if ((lun->flags & CTL_LUN_OFFLINE)
11324	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11325		ctl_set_lun_not_ready(ctsio);
11326		retval = 1;
11327		goto bailout;
11328	}
11329
11330	/*
11331	 * If the LUN is stopped, see if this particular command is allowed
11332	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11333	 */
11334	if ((lun->flags & CTL_LUN_STOPPED)
11335	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11336		/* "Logical unit not ready, initializing cmd. required" */
11337		ctl_set_lun_stopped(ctsio);
11338		retval = 1;
11339		goto bailout;
11340	}
11341
11342	if ((lun->flags & CTL_LUN_INOPERABLE)
11343	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11344		/* "Medium format corrupted" */
11345		ctl_set_medium_format_corrupted(ctsio);
11346		retval = 1;
11347		goto bailout;
11348	}
11349
11350bailout:
11351	return (retval);
11352
11353}
11354
11355static void
11356ctl_failover_io(union ctl_io *io, int have_lock)
11357{
11358	ctl_set_busy(&io->scsiio);
11359	ctl_done(io);
11360}
11361
11362static void
11363ctl_failover(void)
11364{
11365	struct ctl_lun *lun;
11366	struct ctl_softc *ctl_softc;
11367	union ctl_io *next_io, *pending_io;
11368	union ctl_io *io;
11369	int lun_idx;
11370	int i;
11371
11372	ctl_softc = control_softc;
11373
11374	mtx_lock(&ctl_softc->ctl_lock);
11375	/*
11376	 * Remove any cmds from the other SC from the rtr queue.  These
11377	 * will obviously only be for LUNs for which we're the primary.
11378	 * We can't send status or get/send data for these commands.
11379	 * Since they haven't been executed yet, we can just remove them.
11380	 * We'll either abort them or delete them below, depending on
11381	 * which HA mode we're in.
11382	 */
11383#ifdef notyet
11384	mtx_lock(&ctl_softc->queue_lock);
11385	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11386	     io != NULL; io = next_io) {
11387		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11388		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11389			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11390				      ctl_io_hdr, links);
11391	}
11392	mtx_unlock(&ctl_softc->queue_lock);
11393#endif
11394
11395	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11396		lun = ctl_softc->ctl_luns[lun_idx];
11397		if (lun==NULL)
11398			continue;
11399
11400		/*
11401		 * Processor LUNs are primary on both sides.
11402		 * XXX will this always be true?
11403		 */
11404		if (lun->be_lun->lun_type == T_PROCESSOR)
11405			continue;
11406
11407		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11408		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11409			printf("FAILOVER: primary lun %d\n", lun_idx);
11410		        /*
11411			 * Remove all commands from the other SC. First from the
11412			 * blocked queue then from the ooa queue. Once we have
11413			 * removed them. Call ctl_check_blocked to see if there
11414			 * is anything that can run.
11415			 */
11416			for (io = (union ctl_io *)TAILQ_FIRST(
11417			     &lun->blocked_queue); io != NULL; io = next_io) {
11418
11419		        	next_io = (union ctl_io *)TAILQ_NEXT(
11420				    &io->io_hdr, blocked_links);
11421
11422				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11423					TAILQ_REMOVE(&lun->blocked_queue,
11424						     &io->io_hdr,blocked_links);
11425					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11426					TAILQ_REMOVE(&lun->ooa_queue,
11427						     &io->io_hdr, ooa_links);
11428
11429					ctl_free_io(io);
11430				}
11431			}
11432
11433			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11434	     		     io != NULL; io = next_io) {
11435
11436		        	next_io = (union ctl_io *)TAILQ_NEXT(
11437				    &io->io_hdr, ooa_links);
11438
11439				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11440
11441					TAILQ_REMOVE(&lun->ooa_queue,
11442						&io->io_hdr,
11443					     	ooa_links);
11444
11445					ctl_free_io(io);
11446				}
11447			}
11448			ctl_check_blocked(lun);
11449		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11450			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11451
11452			printf("FAILOVER: primary lun %d\n", lun_idx);
11453			/*
11454			 * Abort all commands from the other SC.  We can't
11455			 * send status back for them now.  These should get
11456			 * cleaned up when they are completed or come out
11457			 * for a datamove operation.
11458			 */
11459			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11460	     		     io != NULL; io = next_io) {
11461		        	next_io = (union ctl_io *)TAILQ_NEXT(
11462					&io->io_hdr, ooa_links);
11463
11464				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11465					io->io_hdr.flags |= CTL_FLAG_ABORT;
11466			}
11467		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11468			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11469
11470			printf("FAILOVER: secondary lun %d\n", lun_idx);
11471
11472			lun->flags |= CTL_LUN_PRIMARY_SC;
11473
11474			/*
11475			 * We send all I/O that was sent to this controller
11476			 * and redirected to the other side back with
11477			 * busy status, and have the initiator retry it.
11478			 * Figuring out how much data has been transferred,
11479			 * etc. and picking up where we left off would be
11480			 * very tricky.
11481			 *
11482			 * XXX KDM need to remove I/O from the blocked
11483			 * queue as well!
11484			 */
11485			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11486			     &lun->ooa_queue); pending_io != NULL;
11487			     pending_io = next_io) {
11488
11489				next_io =  (union ctl_io *)TAILQ_NEXT(
11490					&pending_io->io_hdr, ooa_links);
11491
11492				pending_io->io_hdr.flags &=
11493					~CTL_FLAG_SENT_2OTHER_SC;
11494
11495				if (pending_io->io_hdr.flags &
11496				    CTL_FLAG_IO_ACTIVE) {
11497					pending_io->io_hdr.flags |=
11498						CTL_FLAG_FAILOVER;
11499				} else {
11500					ctl_set_busy(&pending_io->scsiio);
11501					ctl_done(pending_io);
11502				}
11503			}
11504
11505			/*
11506			 * Build Unit Attention
11507			 */
11508			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11509				lun->pending_ua[i] |=
11510				                     CTL_UA_ASYM_ACC_CHANGE;
11511			}
11512		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11513			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11514			printf("FAILOVER: secondary lun %d\n", lun_idx);
11515			/*
11516			 * if the first io on the OOA is not on the RtR queue
11517			 * add it.
11518			 */
11519			lun->flags |= CTL_LUN_PRIMARY_SC;
11520
11521			pending_io = (union ctl_io *)TAILQ_FIRST(
11522			    &lun->ooa_queue);
11523			if (pending_io==NULL) {
11524				printf("Nothing on OOA queue\n");
11525				continue;
11526			}
11527
11528			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11529			if ((pending_io->io_hdr.flags &
11530			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11531				pending_io->io_hdr.flags |=
11532				    CTL_FLAG_IS_WAS_ON_RTR;
11533				ctl_enqueue_rtr(pending_io);
11534			}
11535#if 0
11536			else
11537			{
11538				printf("Tag 0x%04x is running\n",
11539				      pending_io->scsiio.tag_num);
11540			}
11541#endif
11542
11543			next_io = (union ctl_io *)TAILQ_NEXT(
11544			    &pending_io->io_hdr, ooa_links);
11545			for (pending_io=next_io; pending_io != NULL;
11546			     pending_io = next_io) {
11547				pending_io->io_hdr.flags &=
11548				    ~CTL_FLAG_SENT_2OTHER_SC;
11549				next_io = (union ctl_io *)TAILQ_NEXT(
11550					&pending_io->io_hdr, ooa_links);
11551				if (pending_io->io_hdr.flags &
11552				    CTL_FLAG_IS_WAS_ON_RTR) {
11553#if 0
11554				        printf("Tag 0x%04x is running\n",
11555				      		pending_io->scsiio.tag_num);
11556#endif
11557					continue;
11558				}
11559
11560				switch (ctl_check_ooa(lun, pending_io,
11561			            (union ctl_io *)TAILQ_PREV(
11562				    &pending_io->io_hdr, ctl_ooaq,
11563				    ooa_links))) {
11564
11565				case CTL_ACTION_BLOCK:
11566					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11567							  &pending_io->io_hdr,
11568							  blocked_links);
11569					pending_io->io_hdr.flags |=
11570					    CTL_FLAG_BLOCKED;
11571					break;
11572				case CTL_ACTION_PASS:
11573				case CTL_ACTION_SKIP:
11574					pending_io->io_hdr.flags |=
11575					    CTL_FLAG_IS_WAS_ON_RTR;
11576					ctl_enqueue_rtr(pending_io);
11577					break;
11578				case CTL_ACTION_OVERLAP:
11579					ctl_set_overlapped_cmd(
11580					    (struct ctl_scsiio *)pending_io);
11581					ctl_done(pending_io);
11582					break;
11583				case CTL_ACTION_OVERLAP_TAG:
11584					ctl_set_overlapped_tag(
11585					    (struct ctl_scsiio *)pending_io,
11586					    pending_io->scsiio.tag_num & 0xff);
11587					ctl_done(pending_io);
11588					break;
11589				case CTL_ACTION_ERROR:
11590				default:
11591					ctl_set_internal_failure(
11592						(struct ctl_scsiio *)pending_io,
11593						0,  // sks_valid
11594						0); //retry count
11595					ctl_done(pending_io);
11596					break;
11597				}
11598			}
11599
11600			/*
11601			 * Build Unit Attention
11602			 */
11603			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11604				lun->pending_ua[i] |=
11605				                     CTL_UA_ASYM_ACC_CHANGE;
11606			}
11607		} else {
11608			panic("Unhandled HA mode failover, LUN flags = %#x, "
11609			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11610		}
11611	}
11612	ctl_pause_rtr = 0;
11613	mtx_unlock(&ctl_softc->ctl_lock);
11614}
11615
11616static int
11617ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11618{
11619	struct ctl_lun *lun;
11620	const struct ctl_cmd_entry *entry;
11621	uint32_t initidx, targ_lun;
11622	int retval;
11623
11624	retval = 0;
11625
11626	lun = NULL;
11627
11628	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11629	if ((targ_lun < CTL_MAX_LUNS)
11630	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11631		lun = ctl_softc->ctl_luns[targ_lun];
11632		/*
11633		 * If the LUN is invalid, pretend that it doesn't exist.
11634		 * It will go away as soon as all pending I/O has been
11635		 * completed.
11636		 */
11637		if (lun->flags & CTL_LUN_DISABLED) {
11638			lun = NULL;
11639		} else {
11640			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11641			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11642				lun->be_lun;
11643			if (lun->be_lun->lun_type == T_PROCESSOR) {
11644				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11645			}
11646
11647			/*
11648			 * Every I/O goes into the OOA queue for a
11649			 * particular LUN, and stays there until completion.
11650			 */
11651			mtx_lock(&lun->lun_lock);
11652			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11653			    ooa_links);
11654		}
11655	} else {
11656		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11657		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11658	}
11659
11660	/* Get command entry and return error if it is unsuppotyed. */
11661	entry = ctl_validate_command(ctsio);
11662	if (entry == NULL) {
11663		if (lun)
11664			mtx_unlock(&lun->lun_lock);
11665		return (retval);
11666	}
11667
11668	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11669	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11670
11671	/*
11672	 * Check to see whether we can send this command to LUNs that don't
11673	 * exist.  This should pretty much only be the case for inquiry
11674	 * and request sense.  Further checks, below, really require having
11675	 * a LUN, so we can't really check the command anymore.  Just put
11676	 * it on the rtr queue.
11677	 */
11678	if (lun == NULL) {
11679		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11680			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11681			ctl_enqueue_rtr((union ctl_io *)ctsio);
11682			return (retval);
11683		}
11684
11685		ctl_set_unsupported_lun(ctsio);
11686		ctl_done((union ctl_io *)ctsio);
11687		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11688		return (retval);
11689	} else {
11690		/*
11691		 * Make sure we support this particular command on this LUN.
11692		 * e.g., we don't support writes to the control LUN.
11693		 */
11694		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11695			mtx_unlock(&lun->lun_lock);
11696			ctl_set_invalid_opcode(ctsio);
11697			ctl_done((union ctl_io *)ctsio);
11698			return (retval);
11699		}
11700	}
11701
11702	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11703
11704#ifdef CTL_WITH_CA
11705	/*
11706	 * If we've got a request sense, it'll clear the contingent
11707	 * allegiance condition.  Otherwise, if we have a CA condition for
11708	 * this initiator, clear it, because it sent down a command other
11709	 * than request sense.
11710	 */
11711	if ((ctsio->cdb[0] != REQUEST_SENSE)
11712	 && (ctl_is_set(lun->have_ca, initidx)))
11713		ctl_clear_mask(lun->have_ca, initidx);
11714#endif
11715
11716	/*
11717	 * If the command has this flag set, it handles its own unit
11718	 * attention reporting, we shouldn't do anything.  Otherwise we
11719	 * check for any pending unit attentions, and send them back to the
11720	 * initiator.  We only do this when a command initially comes in,
11721	 * not when we pull it off the blocked queue.
11722	 *
11723	 * According to SAM-3, section 5.3.2, the order that things get
11724	 * presented back to the host is basically unit attentions caused
11725	 * by some sort of reset event, busy status, reservation conflicts
11726	 * or task set full, and finally any other status.
11727	 *
11728	 * One issue here is that some of the unit attentions we report
11729	 * don't fall into the "reset" category (e.g. "reported luns data
11730	 * has changed").  So reporting it here, before the reservation
11731	 * check, may be technically wrong.  I guess the only thing to do
11732	 * would be to check for and report the reset events here, and then
11733	 * check for the other unit attention types after we check for a
11734	 * reservation conflict.
11735	 *
11736	 * XXX KDM need to fix this
11737	 */
11738	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11739		ctl_ua_type ua_type;
11740
11741		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11742			scsi_sense_data_type sense_format;
11743
11744			if (lun != NULL)
11745				sense_format = (lun->flags &
11746				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11747				    SSD_TYPE_FIXED;
11748			else
11749				sense_format = SSD_TYPE_FIXED;
11750
11751			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11752			    &ctsio->sense_data, sense_format);
11753			if (ua_type != CTL_UA_NONE) {
11754				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11755				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11756						       CTL_AUTOSENSE;
11757				ctsio->sense_len = SSD_FULL_SIZE;
11758				mtx_unlock(&lun->lun_lock);
11759				ctl_done((union ctl_io *)ctsio);
11760				return (retval);
11761			}
11762		}
11763	}
11764
11765
11766	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11767		mtx_unlock(&lun->lun_lock);
11768		ctl_done((union ctl_io *)ctsio);
11769		return (retval);
11770	}
11771
11772	/*
11773	 * XXX CHD this is where we want to send IO to other side if
11774	 * this LUN is secondary on this SC. We will need to make a copy
11775	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11776	 * the copy we send as FROM_OTHER.
11777	 * We also need to stuff the address of the original IO so we can
11778	 * find it easily. Something similar will need be done on the other
11779	 * side so when we are done we can find the copy.
11780	 */
11781	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11782		union ctl_ha_msg msg_info;
11783		int isc_retval;
11784
11785		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11786
11787		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11788		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11789#if 0
11790		printf("1. ctsio %p\n", ctsio);
11791#endif
11792		msg_info.hdr.serializing_sc = NULL;
11793		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11794		msg_info.scsi.tag_num = ctsio->tag_num;
11795		msg_info.scsi.tag_type = ctsio->tag_type;
11796		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11797
11798		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11799
11800		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11801		    (void *)&msg_info, sizeof(msg_info), 0)) >
11802		    CTL_HA_STATUS_SUCCESS) {
11803			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11804			       isc_retval);
11805			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11806		} else {
11807#if 0
11808			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11809#endif
11810		}
11811
11812		/*
11813		 * XXX KDM this I/O is off the incoming queue, but hasn't
11814		 * been inserted on any other queue.  We may need to come
11815		 * up with a holding queue while we wait for serialization
11816		 * so that we have an idea of what we're waiting for from
11817		 * the other side.
11818		 */
11819		mtx_unlock(&lun->lun_lock);
11820		return (retval);
11821	}
11822
11823	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11824			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11825			      ctl_ooaq, ooa_links))) {
11826	case CTL_ACTION_BLOCK:
11827		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11828		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11829				  blocked_links);
11830		mtx_unlock(&lun->lun_lock);
11831		return (retval);
11832	case CTL_ACTION_PASS:
11833	case CTL_ACTION_SKIP:
11834		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11835		mtx_unlock(&lun->lun_lock);
11836		ctl_enqueue_rtr((union ctl_io *)ctsio);
11837		break;
11838	case CTL_ACTION_OVERLAP:
11839		mtx_unlock(&lun->lun_lock);
11840		ctl_set_overlapped_cmd(ctsio);
11841		ctl_done((union ctl_io *)ctsio);
11842		break;
11843	case CTL_ACTION_OVERLAP_TAG:
11844		mtx_unlock(&lun->lun_lock);
11845		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11846		ctl_done((union ctl_io *)ctsio);
11847		break;
11848	case CTL_ACTION_ERROR:
11849	default:
11850		mtx_unlock(&lun->lun_lock);
11851		ctl_set_internal_failure(ctsio,
11852					 /*sks_valid*/ 0,
11853					 /*retry_count*/ 0);
11854		ctl_done((union ctl_io *)ctsio);
11855		break;
11856	}
11857	return (retval);
11858}
11859
11860const struct ctl_cmd_entry *
11861ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11862{
11863	const struct ctl_cmd_entry *entry;
11864	int service_action;
11865
11866	entry = &ctl_cmd_table[ctsio->cdb[0]];
11867	if (sa)
11868		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11869	if (entry->flags & CTL_CMD_FLAG_SA5) {
11870		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11871		entry = &((const struct ctl_cmd_entry *)
11872		    entry->execute)[service_action];
11873	}
11874	return (entry);
11875}
11876
11877const struct ctl_cmd_entry *
11878ctl_validate_command(struct ctl_scsiio *ctsio)
11879{
11880	const struct ctl_cmd_entry *entry;
11881	int i, sa;
11882	uint8_t diff;
11883
11884	entry = ctl_get_cmd_entry(ctsio, &sa);
11885	if (entry->execute == NULL) {
11886		if (sa)
11887			ctl_set_invalid_field(ctsio,
11888					      /*sks_valid*/ 1,
11889					      /*command*/ 1,
11890					      /*field*/ 1,
11891					      /*bit_valid*/ 1,
11892					      /*bit*/ 4);
11893		else
11894			ctl_set_invalid_opcode(ctsio);
11895		ctl_done((union ctl_io *)ctsio);
11896		return (NULL);
11897	}
11898	KASSERT(entry->length > 0,
11899	    ("Not defined length for command 0x%02x/0x%02x",
11900	     ctsio->cdb[0], ctsio->cdb[1]));
11901	for (i = 1; i < entry->length; i++) {
11902		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11903		if (diff == 0)
11904			continue;
11905		ctl_set_invalid_field(ctsio,
11906				      /*sks_valid*/ 1,
11907				      /*command*/ 1,
11908				      /*field*/ i,
11909				      /*bit_valid*/ 1,
11910				      /*bit*/ fls(diff) - 1);
11911		ctl_done((union ctl_io *)ctsio);
11912		return (NULL);
11913	}
11914	return (entry);
11915}
11916
11917static int
11918ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11919{
11920
11921	switch (lun_type) {
11922	case T_PROCESSOR:
11923		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11924		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11925			return (0);
11926		break;
11927	case T_DIRECT:
11928		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11929		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11930			return (0);
11931		break;
11932	default:
11933		return (0);
11934	}
11935	return (1);
11936}
11937
11938static int
11939ctl_scsiio(struct ctl_scsiio *ctsio)
11940{
11941	int retval;
11942	const struct ctl_cmd_entry *entry;
11943
11944	retval = CTL_RETVAL_COMPLETE;
11945
11946	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11947
11948	entry = ctl_get_cmd_entry(ctsio, NULL);
11949
11950	/*
11951	 * If this I/O has been aborted, just send it straight to
11952	 * ctl_done() without executing it.
11953	 */
11954	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11955		ctl_done((union ctl_io *)ctsio);
11956		goto bailout;
11957	}
11958
11959	/*
11960	 * All the checks should have been handled by ctl_scsiio_precheck().
11961	 * We should be clear now to just execute the I/O.
11962	 */
11963	retval = entry->execute(ctsio);
11964
11965bailout:
11966	return (retval);
11967}
11968
11969/*
11970 * Since we only implement one target right now, a bus reset simply resets
11971 * our single target.
11972 */
11973static int
11974ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11975{
11976	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11977}
11978
11979static int
11980ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11981		 ctl_ua_type ua_type)
11982{
11983	struct ctl_lun *lun;
11984	int retval;
11985
11986	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11987		union ctl_ha_msg msg_info;
11988
11989		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11990		msg_info.hdr.nexus = io->io_hdr.nexus;
11991		if (ua_type==CTL_UA_TARG_RESET)
11992			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11993		else
11994			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11995		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11996		msg_info.hdr.original_sc = NULL;
11997		msg_info.hdr.serializing_sc = NULL;
11998		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11999		    (void *)&msg_info, sizeof(msg_info), 0)) {
12000		}
12001	}
12002	retval = 0;
12003
12004	mtx_lock(&ctl_softc->ctl_lock);
12005	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12006		retval += ctl_lun_reset(lun, io, ua_type);
12007	mtx_unlock(&ctl_softc->ctl_lock);
12008
12009	return (retval);
12010}
12011
12012/*
12013 * The LUN should always be set.  The I/O is optional, and is used to
12014 * distinguish between I/Os sent by this initiator, and by other
12015 * initiators.  We set unit attention for initiators other than this one.
12016 * SAM-3 is vague on this point.  It does say that a unit attention should
12017 * be established for other initiators when a LUN is reset (see section
12018 * 5.7.3), but it doesn't specifically say that the unit attention should
12019 * be established for this particular initiator when a LUN is reset.  Here
12020 * is the relevant text, from SAM-3 rev 8:
12021 *
12022 * 5.7.2 When a SCSI initiator port aborts its own tasks
12023 *
12024 * When a SCSI initiator port causes its own task(s) to be aborted, no
12025 * notification that the task(s) have been aborted shall be returned to
12026 * the SCSI initiator port other than the completion response for the
12027 * command or task management function action that caused the task(s) to
12028 * be aborted and notification(s) associated with related effects of the
12029 * action (e.g., a reset unit attention condition).
12030 *
12031 * XXX KDM for now, we're setting unit attention for all initiators.
12032 */
12033static int
12034ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12035{
12036	union ctl_io *xio;
12037#if 0
12038	uint32_t initindex;
12039#endif
12040	int i;
12041
12042	mtx_lock(&lun->lun_lock);
12043	/*
12044	 * Run through the OOA queue and abort each I/O.
12045	 */
12046#if 0
12047	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12048#endif
12049	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12050	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12051		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12052	}
12053
12054	/*
12055	 * This version sets unit attention for every
12056	 */
12057#if 0
12058	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12059	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12060		if (initindex == i)
12061			continue;
12062		lun->pending_ua[i] |= ua_type;
12063	}
12064#endif
12065
12066	/*
12067	 * A reset (any kind, really) clears reservations established with
12068	 * RESERVE/RELEASE.  It does not clear reservations established
12069	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12070	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12071	 * reservations made with the RESERVE/RELEASE commands, because
12072	 * those commands are obsolete in SPC-3.
12073	 */
12074	lun->flags &= ~CTL_LUN_RESERVED;
12075
12076	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12077#ifdef CTL_WITH_CA
12078		ctl_clear_mask(lun->have_ca, i);
12079#endif
12080		lun->pending_ua[i] |= ua_type;
12081	}
12082	mtx_unlock(&lun->lun_lock);
12083
12084	return (0);
12085}
12086
12087static void
12088ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12089    int other_sc)
12090{
12091	union ctl_io *xio;
12092
12093	mtx_assert(&lun->lun_lock, MA_OWNED);
12094
12095	/*
12096	 * Run through the OOA queue and attempt to find the given I/O.
12097	 * The target port, initiator ID, tag type and tag number have to
12098	 * match the values that we got from the initiator.  If we have an
12099	 * untagged command to abort, simply abort the first untagged command
12100	 * we come to.  We only allow one untagged command at a time of course.
12101	 */
12102	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12103	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12104
12105		if ((targ_port == UINT32_MAX ||
12106		     targ_port == xio->io_hdr.nexus.targ_port) &&
12107		    (init_id == UINT32_MAX ||
12108		     init_id == xio->io_hdr.nexus.initid.id)) {
12109			if (targ_port != xio->io_hdr.nexus.targ_port ||
12110			    init_id != xio->io_hdr.nexus.initid.id)
12111				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12112			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12113			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12114				union ctl_ha_msg msg_info;
12115
12116				msg_info.hdr.nexus = xio->io_hdr.nexus;
12117				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12118				msg_info.task.tag_num = xio->scsiio.tag_num;
12119				msg_info.task.tag_type = xio->scsiio.tag_type;
12120				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12121				msg_info.hdr.original_sc = NULL;
12122				msg_info.hdr.serializing_sc = NULL;
12123				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12124				    (void *)&msg_info, sizeof(msg_info), 0);
12125			}
12126		}
12127	}
12128}
12129
12130static int
12131ctl_abort_task_set(union ctl_io *io)
12132{
12133	struct ctl_softc *softc = control_softc;
12134	struct ctl_lun *lun;
12135	uint32_t targ_lun;
12136
12137	/*
12138	 * Look up the LUN.
12139	 */
12140	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12141	mtx_lock(&softc->ctl_lock);
12142	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12143		lun = softc->ctl_luns[targ_lun];
12144	else {
12145		mtx_unlock(&softc->ctl_lock);
12146		return (1);
12147	}
12148
12149	mtx_lock(&lun->lun_lock);
12150	mtx_unlock(&softc->ctl_lock);
12151	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12152		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12153		    io->io_hdr.nexus.initid.id,
12154		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12155	} else { /* CTL_TASK_CLEAR_TASK_SET */
12156		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12157		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12158	}
12159	mtx_unlock(&lun->lun_lock);
12160	return (0);
12161}
12162
12163static int
12164ctl_i_t_nexus_reset(union ctl_io *io)
12165{
12166	struct ctl_softc *softc = control_softc;
12167	struct ctl_lun *lun;
12168	uint32_t initindex, residx;
12169
12170	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12171	residx = ctl_get_resindex(&io->io_hdr.nexus);
12172	mtx_lock(&softc->ctl_lock);
12173	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12174		mtx_lock(&lun->lun_lock);
12175		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12176		    io->io_hdr.nexus.initid.id,
12177		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12178#ifdef CTL_WITH_CA
12179		ctl_clear_mask(lun->have_ca, initindex);
12180#endif
12181		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12182			lun->flags &= ~CTL_LUN_RESERVED;
12183		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12184		mtx_unlock(&lun->lun_lock);
12185	}
12186	mtx_unlock(&softc->ctl_lock);
12187	return (0);
12188}
12189
12190static int
12191ctl_abort_task(union ctl_io *io)
12192{
12193	union ctl_io *xio;
12194	struct ctl_lun *lun;
12195	struct ctl_softc *ctl_softc;
12196#if 0
12197	struct sbuf sb;
12198	char printbuf[128];
12199#endif
12200	int found;
12201	uint32_t targ_lun;
12202
12203	ctl_softc = control_softc;
12204	found = 0;
12205
12206	/*
12207	 * Look up the LUN.
12208	 */
12209	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12210	mtx_lock(&ctl_softc->ctl_lock);
12211	if ((targ_lun < CTL_MAX_LUNS)
12212	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12213		lun = ctl_softc->ctl_luns[targ_lun];
12214	else {
12215		mtx_unlock(&ctl_softc->ctl_lock);
12216		return (1);
12217	}
12218
12219#if 0
12220	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12221	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12222#endif
12223
12224	mtx_lock(&lun->lun_lock);
12225	mtx_unlock(&ctl_softc->ctl_lock);
12226	/*
12227	 * Run through the OOA queue and attempt to find the given I/O.
12228	 * The target port, initiator ID, tag type and tag number have to
12229	 * match the values that we got from the initiator.  If we have an
12230	 * untagged command to abort, simply abort the first untagged command
12231	 * we come to.  We only allow one untagged command at a time of course.
12232	 */
12233#if 0
12234	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12235#endif
12236	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12237	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12238#if 0
12239		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12240
12241		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12242			    lun->lun, xio->scsiio.tag_num,
12243			    xio->scsiio.tag_type,
12244			    (xio->io_hdr.blocked_links.tqe_prev
12245			    == NULL) ? "" : " BLOCKED",
12246			    (xio->io_hdr.flags &
12247			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12248			    (xio->io_hdr.flags &
12249			    CTL_FLAG_ABORT) ? " ABORT" : "",
12250			    (xio->io_hdr.flags &
12251			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12252		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12253		sbuf_finish(&sb);
12254		printf("%s\n", sbuf_data(&sb));
12255#endif
12256
12257		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12258		 && (xio->io_hdr.nexus.initid.id ==
12259		     io->io_hdr.nexus.initid.id)) {
12260			/*
12261			 * If the abort says that the task is untagged, the
12262			 * task in the queue must be untagged.  Otherwise,
12263			 * we just check to see whether the tag numbers
12264			 * match.  This is because the QLogic firmware
12265			 * doesn't pass back the tag type in an abort
12266			 * request.
12267			 */
12268#if 0
12269			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12270			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12271			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12272#endif
12273			/*
12274			 * XXX KDM we've got problems with FC, because it
12275			 * doesn't send down a tag type with aborts.  So we
12276			 * can only really go by the tag number...
12277			 * This may cause problems with parallel SCSI.
12278			 * Need to figure that out!!
12279			 */
12280			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12281				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12282				found = 1;
12283				if ((io->io_hdr.flags &
12284				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12285				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12286					union ctl_ha_msg msg_info;
12287
12288					io->io_hdr.flags |=
12289					                CTL_FLAG_SENT_2OTHER_SC;
12290					msg_info.hdr.nexus = io->io_hdr.nexus;
12291					msg_info.task.task_action =
12292						CTL_TASK_ABORT_TASK;
12293					msg_info.task.tag_num =
12294						io->taskio.tag_num;
12295					msg_info.task.tag_type =
12296						io->taskio.tag_type;
12297					msg_info.hdr.msg_type =
12298						CTL_MSG_MANAGE_TASKS;
12299					msg_info.hdr.original_sc = NULL;
12300					msg_info.hdr.serializing_sc = NULL;
12301#if 0
12302					printf("Sent Abort to other side\n");
12303#endif
12304					if (CTL_HA_STATUS_SUCCESS !=
12305					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12306		    				(void *)&msg_info,
12307						sizeof(msg_info), 0)) {
12308					}
12309				}
12310#if 0
12311				printf("ctl_abort_task: found I/O to abort\n");
12312#endif
12313				break;
12314			}
12315		}
12316	}
12317	mtx_unlock(&lun->lun_lock);
12318
12319	if (found == 0) {
12320		/*
12321		 * This isn't really an error.  It's entirely possible for
12322		 * the abort and command completion to cross on the wire.
12323		 * This is more of an informative/diagnostic error.
12324		 */
12325#if 0
12326		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12327		       "%d:%d:%d:%d tag %d type %d\n",
12328		       io->io_hdr.nexus.initid.id,
12329		       io->io_hdr.nexus.targ_port,
12330		       io->io_hdr.nexus.targ_target.id,
12331		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12332		       io->taskio.tag_type);
12333#endif
12334	}
12335	return (0);
12336}
12337
12338static void
12339ctl_run_task(union ctl_io *io)
12340{
12341	struct ctl_softc *ctl_softc = control_softc;
12342	int retval = 1;
12343	const char *task_desc;
12344
12345	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12346
12347	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12348	    ("ctl_run_task: Unextected io_type %d\n",
12349	     io->io_hdr.io_type));
12350
12351	task_desc = ctl_scsi_task_string(&io->taskio);
12352	if (task_desc != NULL) {
12353#ifdef NEEDTOPORT
12354		csevent_log(CSC_CTL | CSC_SHELF_SW |
12355			    CTL_TASK_REPORT,
12356			    csevent_LogType_Trace,
12357			    csevent_Severity_Information,
12358			    csevent_AlertLevel_Green,
12359			    csevent_FRU_Firmware,
12360			    csevent_FRU_Unknown,
12361			    "CTL: received task: %s",task_desc);
12362#endif
12363	} else {
12364#ifdef NEEDTOPORT
12365		csevent_log(CSC_CTL | CSC_SHELF_SW |
12366			    CTL_TASK_REPORT,
12367			    csevent_LogType_Trace,
12368			    csevent_Severity_Information,
12369			    csevent_AlertLevel_Green,
12370			    csevent_FRU_Firmware,
12371			    csevent_FRU_Unknown,
12372			    "CTL: received unknown task "
12373			    "type: %d (%#x)",
12374			    io->taskio.task_action,
12375			    io->taskio.task_action);
12376#endif
12377	}
12378	switch (io->taskio.task_action) {
12379	case CTL_TASK_ABORT_TASK:
12380		retval = ctl_abort_task(io);
12381		break;
12382	case CTL_TASK_ABORT_TASK_SET:
12383	case CTL_TASK_CLEAR_TASK_SET:
12384		retval = ctl_abort_task_set(io);
12385		break;
12386	case CTL_TASK_CLEAR_ACA:
12387		break;
12388	case CTL_TASK_I_T_NEXUS_RESET:
12389		retval = ctl_i_t_nexus_reset(io);
12390		break;
12391	case CTL_TASK_LUN_RESET: {
12392		struct ctl_lun *lun;
12393		uint32_t targ_lun;
12394
12395		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12396		mtx_lock(&ctl_softc->ctl_lock);
12397		if ((targ_lun < CTL_MAX_LUNS)
12398		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12399			lun = ctl_softc->ctl_luns[targ_lun];
12400		else {
12401			mtx_unlock(&ctl_softc->ctl_lock);
12402			retval = 1;
12403			break;
12404		}
12405
12406		if (!(io->io_hdr.flags &
12407		    CTL_FLAG_FROM_OTHER_SC)) {
12408			union ctl_ha_msg msg_info;
12409
12410			io->io_hdr.flags |=
12411				CTL_FLAG_SENT_2OTHER_SC;
12412			msg_info.hdr.msg_type =
12413				CTL_MSG_MANAGE_TASKS;
12414			msg_info.hdr.nexus = io->io_hdr.nexus;
12415			msg_info.task.task_action =
12416				CTL_TASK_LUN_RESET;
12417			msg_info.hdr.original_sc = NULL;
12418			msg_info.hdr.serializing_sc = NULL;
12419			if (CTL_HA_STATUS_SUCCESS !=
12420			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12421			    (void *)&msg_info,
12422			    sizeof(msg_info), 0)) {
12423			}
12424		}
12425
12426		retval = ctl_lun_reset(lun, io,
12427				       CTL_UA_LUN_RESET);
12428		mtx_unlock(&ctl_softc->ctl_lock);
12429		break;
12430	}
12431	case CTL_TASK_TARGET_RESET:
12432		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12433		break;
12434	case CTL_TASK_BUS_RESET:
12435		retval = ctl_bus_reset(ctl_softc, io);
12436		break;
12437	case CTL_TASK_PORT_LOGIN:
12438		break;
12439	case CTL_TASK_PORT_LOGOUT:
12440		break;
12441	default:
12442		printf("ctl_run_task: got unknown task management event %d\n",
12443		       io->taskio.task_action);
12444		break;
12445	}
12446	if (retval == 0)
12447		io->io_hdr.status = CTL_SUCCESS;
12448	else
12449		io->io_hdr.status = CTL_ERROR;
12450	ctl_done(io);
12451}
12452
12453/*
12454 * For HA operation.  Handle commands that come in from the other
12455 * controller.
12456 */
12457static void
12458ctl_handle_isc(union ctl_io *io)
12459{
12460	int free_io;
12461	struct ctl_lun *lun;
12462	struct ctl_softc *ctl_softc;
12463	uint32_t targ_lun;
12464
12465	ctl_softc = control_softc;
12466
12467	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12468	lun = ctl_softc->ctl_luns[targ_lun];
12469
12470	switch (io->io_hdr.msg_type) {
12471	case CTL_MSG_SERIALIZE:
12472		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12473		break;
12474	case CTL_MSG_R2R: {
12475		const struct ctl_cmd_entry *entry;
12476
12477		/*
12478		 * This is only used in SER_ONLY mode.
12479		 */
12480		free_io = 0;
12481		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12482		mtx_lock(&lun->lun_lock);
12483		if (ctl_scsiio_lun_check(ctl_softc, lun,
12484		    entry, (struct ctl_scsiio *)io) != 0) {
12485			mtx_unlock(&lun->lun_lock);
12486			ctl_done(io);
12487			break;
12488		}
12489		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12490		mtx_unlock(&lun->lun_lock);
12491		ctl_enqueue_rtr(io);
12492		break;
12493	}
12494	case CTL_MSG_FINISH_IO:
12495		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12496			free_io = 0;
12497			ctl_done(io);
12498		} else {
12499			free_io = 1;
12500			mtx_lock(&lun->lun_lock);
12501			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12502				     ooa_links);
12503			ctl_check_blocked(lun);
12504			mtx_unlock(&lun->lun_lock);
12505		}
12506		break;
12507	case CTL_MSG_PERS_ACTION:
12508		ctl_hndl_per_res_out_on_other_sc(
12509			(union ctl_ha_msg *)&io->presio.pr_msg);
12510		free_io = 1;
12511		break;
12512	case CTL_MSG_BAD_JUJU:
12513		free_io = 0;
12514		ctl_done(io);
12515		break;
12516	case CTL_MSG_DATAMOVE:
12517		/* Only used in XFER mode */
12518		free_io = 0;
12519		ctl_datamove_remote(io);
12520		break;
12521	case CTL_MSG_DATAMOVE_DONE:
12522		/* Only used in XFER mode */
12523		free_io = 0;
12524		io->scsiio.be_move_done(io);
12525		break;
12526	default:
12527		free_io = 1;
12528		printf("%s: Invalid message type %d\n",
12529		       __func__, io->io_hdr.msg_type);
12530		break;
12531	}
12532	if (free_io)
12533		ctl_free_io(io);
12534
12535}
12536
12537
12538/*
12539 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12540 * there is no match.
12541 */
12542static ctl_lun_error_pattern
12543ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12544{
12545	const struct ctl_cmd_entry *entry;
12546	ctl_lun_error_pattern filtered_pattern, pattern;
12547
12548	pattern = desc->error_pattern;
12549
12550	/*
12551	 * XXX KDM we need more data passed into this function to match a
12552	 * custom pattern, and we actually need to implement custom pattern
12553	 * matching.
12554	 */
12555	if (pattern & CTL_LUN_PAT_CMD)
12556		return (CTL_LUN_PAT_CMD);
12557
12558	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12559		return (CTL_LUN_PAT_ANY);
12560
12561	entry = ctl_get_cmd_entry(ctsio, NULL);
12562
12563	filtered_pattern = entry->pattern & pattern;
12564
12565	/*
12566	 * If the user requested specific flags in the pattern (e.g.
12567	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12568	 * flags.
12569	 *
12570	 * If the user did not specify any flags, it doesn't matter whether
12571	 * or not the command supports the flags.
12572	 */
12573	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12574	     (pattern & ~CTL_LUN_PAT_MASK))
12575		return (CTL_LUN_PAT_NONE);
12576
12577	/*
12578	 * If the user asked for a range check, see if the requested LBA
12579	 * range overlaps with this command's LBA range.
12580	 */
12581	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12582		uint64_t lba1;
12583		uint64_t len1;
12584		ctl_action action;
12585		int retval;
12586
12587		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12588		if (retval != 0)
12589			return (CTL_LUN_PAT_NONE);
12590
12591		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12592					      desc->lba_range.len);
12593		/*
12594		 * A "pass" means that the LBA ranges don't overlap, so
12595		 * this doesn't match the user's range criteria.
12596		 */
12597		if (action == CTL_ACTION_PASS)
12598			return (CTL_LUN_PAT_NONE);
12599	}
12600
12601	return (filtered_pattern);
12602}
12603
12604static void
12605ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12606{
12607	struct ctl_error_desc *desc, *desc2;
12608
12609	mtx_assert(&lun->lun_lock, MA_OWNED);
12610
12611	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12612		ctl_lun_error_pattern pattern;
12613		/*
12614		 * Check to see whether this particular command matches
12615		 * the pattern in the descriptor.
12616		 */
12617		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12618		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12619			continue;
12620
12621		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12622		case CTL_LUN_INJ_ABORTED:
12623			ctl_set_aborted(&io->scsiio);
12624			break;
12625		case CTL_LUN_INJ_MEDIUM_ERR:
12626			ctl_set_medium_error(&io->scsiio);
12627			break;
12628		case CTL_LUN_INJ_UA:
12629			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12630			 * OCCURRED */
12631			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12632			break;
12633		case CTL_LUN_INJ_CUSTOM:
12634			/*
12635			 * We're assuming the user knows what he is doing.
12636			 * Just copy the sense information without doing
12637			 * checks.
12638			 */
12639			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12640			      ctl_min(sizeof(desc->custom_sense),
12641				      sizeof(io->scsiio.sense_data)));
12642			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12643			io->scsiio.sense_len = SSD_FULL_SIZE;
12644			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12645			break;
12646		case CTL_LUN_INJ_NONE:
12647		default:
12648			/*
12649			 * If this is an error injection type we don't know
12650			 * about, clear the continuous flag (if it is set)
12651			 * so it will get deleted below.
12652			 */
12653			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12654			break;
12655		}
12656		/*
12657		 * By default, each error injection action is a one-shot
12658		 */
12659		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12660			continue;
12661
12662		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12663
12664		free(desc, M_CTL);
12665	}
12666}
12667
12668#ifdef CTL_IO_DELAY
12669static void
12670ctl_datamove_timer_wakeup(void *arg)
12671{
12672	union ctl_io *io;
12673
12674	io = (union ctl_io *)arg;
12675
12676	ctl_datamove(io);
12677}
12678#endif /* CTL_IO_DELAY */
12679
12680void
12681ctl_datamove(union ctl_io *io)
12682{
12683	void (*fe_datamove)(union ctl_io *io);
12684
12685	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12686
12687	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12688
12689#ifdef CTL_TIME_IO
12690	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12691		char str[256];
12692		char path_str[64];
12693		struct sbuf sb;
12694
12695		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12696		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12697
12698		sbuf_cat(&sb, path_str);
12699		switch (io->io_hdr.io_type) {
12700		case CTL_IO_SCSI:
12701			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12702			sbuf_printf(&sb, "\n");
12703			sbuf_cat(&sb, path_str);
12704			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12705				    io->scsiio.tag_num, io->scsiio.tag_type);
12706			break;
12707		case CTL_IO_TASK:
12708			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12709				    "Tag Type: %d\n", io->taskio.task_action,
12710				    io->taskio.tag_num, io->taskio.tag_type);
12711			break;
12712		default:
12713			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12714			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12715			break;
12716		}
12717		sbuf_cat(&sb, path_str);
12718		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12719			    (intmax_t)time_uptime - io->io_hdr.start_time);
12720		sbuf_finish(&sb);
12721		printf("%s", sbuf_data(&sb));
12722	}
12723#endif /* CTL_TIME_IO */
12724
12725#ifdef CTL_IO_DELAY
12726	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12727		struct ctl_lun *lun;
12728
12729		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12730
12731		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12732	} else {
12733		struct ctl_lun *lun;
12734
12735		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12736		if ((lun != NULL)
12737		 && (lun->delay_info.datamove_delay > 0)) {
12738			struct callout *callout;
12739
12740			callout = (struct callout *)&io->io_hdr.timer_bytes;
12741			callout_init(callout, /*mpsafe*/ 1);
12742			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12743			callout_reset(callout,
12744				      lun->delay_info.datamove_delay * hz,
12745				      ctl_datamove_timer_wakeup, io);
12746			if (lun->delay_info.datamove_type ==
12747			    CTL_DELAY_TYPE_ONESHOT)
12748				lun->delay_info.datamove_delay = 0;
12749			return;
12750		}
12751	}
12752#endif
12753
12754	/*
12755	 * This command has been aborted.  Set the port status, so we fail
12756	 * the data move.
12757	 */
12758	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12759		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12760		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12761		       io->io_hdr.nexus.targ_port,
12762		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12763		       io->io_hdr.nexus.targ_lun);
12764		io->io_hdr.port_status = 31337;
12765		/*
12766		 * Note that the backend, in this case, will get the
12767		 * callback in its context.  In other cases it may get
12768		 * called in the frontend's interrupt thread context.
12769		 */
12770		io->scsiio.be_move_done(io);
12771		return;
12772	}
12773
12774	/*
12775	 * If we're in XFER mode and this I/O is from the other shelf
12776	 * controller, we need to send the DMA to the other side to
12777	 * actually transfer the data to/from the host.  In serialize only
12778	 * mode the transfer happens below CTL and ctl_datamove() is only
12779	 * called on the machine that originally received the I/O.
12780	 */
12781	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12782	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12783		union ctl_ha_msg msg;
12784		uint32_t sg_entries_sent;
12785		int do_sg_copy;
12786		int i;
12787
12788		memset(&msg, 0, sizeof(msg));
12789		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12790		msg.hdr.original_sc = io->io_hdr.original_sc;
12791		msg.hdr.serializing_sc = io;
12792		msg.hdr.nexus = io->io_hdr.nexus;
12793		msg.dt.flags = io->io_hdr.flags;
12794		/*
12795		 * We convert everything into a S/G list here.  We can't
12796		 * pass by reference, only by value between controllers.
12797		 * So we can't pass a pointer to the S/G list, only as many
12798		 * S/G entries as we can fit in here.  If it's possible for
12799		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12800		 * then we need to break this up into multiple transfers.
12801		 */
12802		if (io->scsiio.kern_sg_entries == 0) {
12803			msg.dt.kern_sg_entries = 1;
12804			/*
12805			 * If this is in cached memory, flush the cache
12806			 * before we send the DMA request to the other
12807			 * controller.  We want to do this in either the
12808			 * read or the write case.  The read case is
12809			 * straightforward.  In the write case, we want to
12810			 * make sure nothing is in the local cache that
12811			 * could overwrite the DMAed data.
12812			 */
12813			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12814				/*
12815				 * XXX KDM use bus_dmamap_sync() here.
12816				 */
12817			}
12818
12819			/*
12820			 * Convert to a physical address if this is a
12821			 * virtual address.
12822			 */
12823			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12824				msg.dt.sg_list[0].addr =
12825					io->scsiio.kern_data_ptr;
12826			} else {
12827				/*
12828				 * XXX KDM use busdma here!
12829				 */
12830#if 0
12831				msg.dt.sg_list[0].addr = (void *)
12832					vtophys(io->scsiio.kern_data_ptr);
12833#endif
12834			}
12835
12836			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12837			do_sg_copy = 0;
12838		} else {
12839			struct ctl_sg_entry *sgl;
12840
12841			do_sg_copy = 1;
12842			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12843			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12844			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12845				/*
12846				 * XXX KDM use bus_dmamap_sync() here.
12847				 */
12848			}
12849		}
12850
12851		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12852		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12853		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12854		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12855		msg.dt.sg_sequence = 0;
12856
12857		/*
12858		 * Loop until we've sent all of the S/G entries.  On the
12859		 * other end, we'll recompose these S/G entries into one
12860		 * contiguous list before passing it to the
12861		 */
12862		for (sg_entries_sent = 0; sg_entries_sent <
12863		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12864			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12865				sizeof(msg.dt.sg_list[0])),
12866				msg.dt.kern_sg_entries - sg_entries_sent);
12867
12868			if (do_sg_copy != 0) {
12869				struct ctl_sg_entry *sgl;
12870				int j;
12871
12872				sgl = (struct ctl_sg_entry *)
12873					io->scsiio.kern_data_ptr;
12874				/*
12875				 * If this is in cached memory, flush the cache
12876				 * before we send the DMA request to the other
12877				 * controller.  We want to do this in either
12878				 * the * read or the write case.  The read
12879				 * case is straightforward.  In the write
12880				 * case, we want to make sure nothing is
12881				 * in the local cache that could overwrite
12882				 * the DMAed data.
12883				 */
12884
12885				for (i = sg_entries_sent, j = 0;
12886				     i < msg.dt.cur_sg_entries; i++, j++) {
12887					if ((io->io_hdr.flags &
12888					     CTL_FLAG_NO_DATASYNC) == 0) {
12889						/*
12890						 * XXX KDM use bus_dmamap_sync()
12891						 */
12892					}
12893					if ((io->io_hdr.flags &
12894					     CTL_FLAG_BUS_ADDR) == 0) {
12895						/*
12896						 * XXX KDM use busdma.
12897						 */
12898#if 0
12899						msg.dt.sg_list[j].addr =(void *)
12900						       vtophys(sgl[i].addr);
12901#endif
12902					} else {
12903						msg.dt.sg_list[j].addr =
12904							sgl[i].addr;
12905					}
12906					msg.dt.sg_list[j].len = sgl[i].len;
12907				}
12908			}
12909
12910			sg_entries_sent += msg.dt.cur_sg_entries;
12911			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12912				msg.dt.sg_last = 1;
12913			else
12914				msg.dt.sg_last = 0;
12915
12916			/*
12917			 * XXX KDM drop and reacquire the lock here?
12918			 */
12919			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12920			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12921				/*
12922				 * XXX do something here.
12923				 */
12924			}
12925
12926			msg.dt.sent_sg_entries = sg_entries_sent;
12927		}
12928		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12929		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12930			ctl_failover_io(io, /*have_lock*/ 0);
12931
12932	} else {
12933
12934		/*
12935		 * Lookup the fe_datamove() function for this particular
12936		 * front end.
12937		 */
12938		fe_datamove =
12939		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12940
12941		fe_datamove(io);
12942	}
12943}
12944
12945static void
12946ctl_send_datamove_done(union ctl_io *io, int have_lock)
12947{
12948	union ctl_ha_msg msg;
12949	int isc_status;
12950
12951	memset(&msg, 0, sizeof(msg));
12952
12953	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12954	msg.hdr.original_sc = io;
12955	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12956	msg.hdr.nexus = io->io_hdr.nexus;
12957	msg.hdr.status = io->io_hdr.status;
12958	msg.scsi.tag_num = io->scsiio.tag_num;
12959	msg.scsi.tag_type = io->scsiio.tag_type;
12960	msg.scsi.scsi_status = io->scsiio.scsi_status;
12961	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12962	       sizeof(io->scsiio.sense_data));
12963	msg.scsi.sense_len = io->scsiio.sense_len;
12964	msg.scsi.sense_residual = io->scsiio.sense_residual;
12965	msg.scsi.fetd_status = io->io_hdr.port_status;
12966	msg.scsi.residual = io->scsiio.residual;
12967	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12968
12969	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12970		ctl_failover_io(io, /*have_lock*/ have_lock);
12971		return;
12972	}
12973
12974	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12975	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12976		/* XXX do something if this fails */
12977	}
12978
12979}
12980
12981/*
12982 * The DMA to the remote side is done, now we need to tell the other side
12983 * we're done so it can continue with its data movement.
12984 */
12985static void
12986ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12987{
12988	union ctl_io *io;
12989
12990	io = rq->context;
12991
12992	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12993		printf("%s: ISC DMA write failed with error %d", __func__,
12994		       rq->ret);
12995		ctl_set_internal_failure(&io->scsiio,
12996					 /*sks_valid*/ 1,
12997					 /*retry_count*/ rq->ret);
12998	}
12999
13000	ctl_dt_req_free(rq);
13001
13002	/*
13003	 * In this case, we had to malloc the memory locally.  Free it.
13004	 */
13005	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13006		int i;
13007		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13008			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13009	}
13010	/*
13011	 * The data is in local and remote memory, so now we need to send
13012	 * status (good or back) back to the other side.
13013	 */
13014	ctl_send_datamove_done(io, /*have_lock*/ 0);
13015}
13016
13017/*
13018 * We've moved the data from the host/controller into local memory.  Now we
13019 * need to push it over to the remote controller's memory.
13020 */
13021static int
13022ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13023{
13024	int retval;
13025
13026	retval = 0;
13027
13028	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13029					  ctl_datamove_remote_write_cb);
13030
13031	return (retval);
13032}
13033
13034static void
13035ctl_datamove_remote_write(union ctl_io *io)
13036{
13037	int retval;
13038	void (*fe_datamove)(union ctl_io *io);
13039
13040	/*
13041	 * - Get the data from the host/HBA into local memory.
13042	 * - DMA memory from the local controller to the remote controller.
13043	 * - Send status back to the remote controller.
13044	 */
13045
13046	retval = ctl_datamove_remote_sgl_setup(io);
13047	if (retval != 0)
13048		return;
13049
13050	/* Switch the pointer over so the FETD knows what to do */
13051	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13052
13053	/*
13054	 * Use a custom move done callback, since we need to send completion
13055	 * back to the other controller, not to the backend on this side.
13056	 */
13057	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13058
13059	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13060
13061	fe_datamove(io);
13062
13063	return;
13064
13065}
13066
13067static int
13068ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13069{
13070#if 0
13071	char str[256];
13072	char path_str[64];
13073	struct sbuf sb;
13074#endif
13075
13076	/*
13077	 * In this case, we had to malloc the memory locally.  Free it.
13078	 */
13079	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13080		int i;
13081		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13082			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13083	}
13084
13085#if 0
13086	scsi_path_string(io, path_str, sizeof(path_str));
13087	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13088	sbuf_cat(&sb, path_str);
13089	scsi_command_string(&io->scsiio, NULL, &sb);
13090	sbuf_printf(&sb, "\n");
13091	sbuf_cat(&sb, path_str);
13092	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13093		    io->scsiio.tag_num, io->scsiio.tag_type);
13094	sbuf_cat(&sb, path_str);
13095	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13096		    io->io_hdr.flags, io->io_hdr.status);
13097	sbuf_finish(&sb);
13098	printk("%s", sbuf_data(&sb));
13099#endif
13100
13101
13102	/*
13103	 * The read is done, now we need to send status (good or bad) back
13104	 * to the other side.
13105	 */
13106	ctl_send_datamove_done(io, /*have_lock*/ 0);
13107
13108	return (0);
13109}
13110
13111static void
13112ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13113{
13114	union ctl_io *io;
13115	void (*fe_datamove)(union ctl_io *io);
13116
13117	io = rq->context;
13118
13119	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13120		printf("%s: ISC DMA read failed with error %d", __func__,
13121		       rq->ret);
13122		ctl_set_internal_failure(&io->scsiio,
13123					 /*sks_valid*/ 1,
13124					 /*retry_count*/ rq->ret);
13125	}
13126
13127	ctl_dt_req_free(rq);
13128
13129	/* Switch the pointer over so the FETD knows what to do */
13130	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13131
13132	/*
13133	 * Use a custom move done callback, since we need to send completion
13134	 * back to the other controller, not to the backend on this side.
13135	 */
13136	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13137
13138	/* XXX KDM add checks like the ones in ctl_datamove? */
13139
13140	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13141
13142	fe_datamove(io);
13143}
13144
13145static int
13146ctl_datamove_remote_sgl_setup(union ctl_io *io)
13147{
13148	struct ctl_sg_entry *local_sglist, *remote_sglist;
13149	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13150	struct ctl_softc *softc;
13151	int retval;
13152	int i;
13153
13154	retval = 0;
13155	softc = control_softc;
13156
13157	local_sglist = io->io_hdr.local_sglist;
13158	local_dma_sglist = io->io_hdr.local_dma_sglist;
13159	remote_sglist = io->io_hdr.remote_sglist;
13160	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13161
13162	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13163		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13164			local_sglist[i].len = remote_sglist[i].len;
13165
13166			/*
13167			 * XXX Detect the situation where the RS-level I/O
13168			 * redirector on the other side has already read the
13169			 * data off of the AOR RS on this side, and
13170			 * transferred it to remote (mirror) memory on the
13171			 * other side.  Since we already have the data in
13172			 * memory here, we just need to use it.
13173			 *
13174			 * XXX KDM this can probably be removed once we
13175			 * get the cache device code in and take the
13176			 * current AOR implementation out.
13177			 */
13178#ifdef NEEDTOPORT
13179			if ((remote_sglist[i].addr >=
13180			     (void *)vtophys(softc->mirr->addr))
13181			 && (remote_sglist[i].addr <
13182			     ((void *)vtophys(softc->mirr->addr) +
13183			     CacheMirrorOffset))) {
13184				local_sglist[i].addr = remote_sglist[i].addr -
13185					CacheMirrorOffset;
13186				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13187				     CTL_FLAG_DATA_IN)
13188					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13189			} else {
13190				local_sglist[i].addr = remote_sglist[i].addr +
13191					CacheMirrorOffset;
13192			}
13193#endif
13194#if 0
13195			printf("%s: local %p, remote %p, len %d\n",
13196			       __func__, local_sglist[i].addr,
13197			       remote_sglist[i].addr, local_sglist[i].len);
13198#endif
13199		}
13200	} else {
13201		uint32_t len_to_go;
13202
13203		/*
13204		 * In this case, we don't have automatically allocated
13205		 * memory for this I/O on this controller.  This typically
13206		 * happens with internal CTL I/O -- e.g. inquiry, mode
13207		 * sense, etc.  Anything coming from RAIDCore will have
13208		 * a mirror area available.
13209		 */
13210		len_to_go = io->scsiio.kern_data_len;
13211
13212		/*
13213		 * Clear the no datasync flag, we have to use malloced
13214		 * buffers.
13215		 */
13216		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13217
13218		/*
13219		 * The difficult thing here is that the size of the various
13220		 * S/G segments may be different than the size from the
13221		 * remote controller.  That'll make it harder when DMAing
13222		 * the data back to the other side.
13223		 */
13224		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13225		     sizeof(io->io_hdr.remote_sglist[0])) &&
13226		     (len_to_go > 0); i++) {
13227			local_sglist[i].len = ctl_min(len_to_go, 131072);
13228			CTL_SIZE_8B(local_dma_sglist[i].len,
13229				    local_sglist[i].len);
13230			local_sglist[i].addr =
13231				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13232
13233			local_dma_sglist[i].addr = local_sglist[i].addr;
13234
13235			if (local_sglist[i].addr == NULL) {
13236				int j;
13237
13238				printf("malloc failed for %zd bytes!",
13239				       local_dma_sglist[i].len);
13240				for (j = 0; j < i; j++) {
13241					free(local_sglist[j].addr, M_CTL);
13242				}
13243				ctl_set_internal_failure(&io->scsiio,
13244							 /*sks_valid*/ 1,
13245							 /*retry_count*/ 4857);
13246				retval = 1;
13247				goto bailout_error;
13248
13249			}
13250			/* XXX KDM do we need a sync here? */
13251
13252			len_to_go -= local_sglist[i].len;
13253		}
13254		/*
13255		 * Reset the number of S/G entries accordingly.  The
13256		 * original number of S/G entries is available in
13257		 * rem_sg_entries.
13258		 */
13259		io->scsiio.kern_sg_entries = i;
13260
13261#if 0
13262		printf("%s: kern_sg_entries = %d\n", __func__,
13263		       io->scsiio.kern_sg_entries);
13264		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13265			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13266			       local_sglist[i].addr, local_sglist[i].len,
13267			       local_dma_sglist[i].len);
13268#endif
13269	}
13270
13271
13272	return (retval);
13273
13274bailout_error:
13275
13276	ctl_send_datamove_done(io, /*have_lock*/ 0);
13277
13278	return (retval);
13279}
13280
13281static int
13282ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13283			 ctl_ha_dt_cb callback)
13284{
13285	struct ctl_ha_dt_req *rq;
13286	struct ctl_sg_entry *remote_sglist, *local_sglist;
13287	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13288	uint32_t local_used, remote_used, total_used;
13289	int retval;
13290	int i, j;
13291
13292	retval = 0;
13293
13294	rq = ctl_dt_req_alloc();
13295
13296	/*
13297	 * If we failed to allocate the request, and if the DMA didn't fail
13298	 * anyway, set busy status.  This is just a resource allocation
13299	 * failure.
13300	 */
13301	if ((rq == NULL)
13302	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13303		ctl_set_busy(&io->scsiio);
13304
13305	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13306
13307		if (rq != NULL)
13308			ctl_dt_req_free(rq);
13309
13310		/*
13311		 * The data move failed.  We need to return status back
13312		 * to the other controller.  No point in trying to DMA
13313		 * data to the remote controller.
13314		 */
13315
13316		ctl_send_datamove_done(io, /*have_lock*/ 0);
13317
13318		retval = 1;
13319
13320		goto bailout;
13321	}
13322
13323	local_sglist = io->io_hdr.local_sglist;
13324	local_dma_sglist = io->io_hdr.local_dma_sglist;
13325	remote_sglist = io->io_hdr.remote_sglist;
13326	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13327	local_used = 0;
13328	remote_used = 0;
13329	total_used = 0;
13330
13331	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13332		rq->ret = CTL_HA_STATUS_SUCCESS;
13333		rq->context = io;
13334		callback(rq);
13335		goto bailout;
13336	}
13337
13338	/*
13339	 * Pull/push the data over the wire from/to the other controller.
13340	 * This takes into account the possibility that the local and
13341	 * remote sglists may not be identical in terms of the size of
13342	 * the elements and the number of elements.
13343	 *
13344	 * One fundamental assumption here is that the length allocated for
13345	 * both the local and remote sglists is identical.  Otherwise, we've
13346	 * essentially got a coding error of some sort.
13347	 */
13348	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13349		int isc_ret;
13350		uint32_t cur_len, dma_length;
13351		uint8_t *tmp_ptr;
13352
13353		rq->id = CTL_HA_DATA_CTL;
13354		rq->command = command;
13355		rq->context = io;
13356
13357		/*
13358		 * Both pointers should be aligned.  But it is possible
13359		 * that the allocation length is not.  They should both
13360		 * also have enough slack left over at the end, though,
13361		 * to round up to the next 8 byte boundary.
13362		 */
13363		cur_len = ctl_min(local_sglist[i].len - local_used,
13364				  remote_sglist[j].len - remote_used);
13365
13366		/*
13367		 * In this case, we have a size issue and need to decrease
13368		 * the size, except in the case where we actually have less
13369		 * than 8 bytes left.  In that case, we need to increase
13370		 * the DMA length to get the last bit.
13371		 */
13372		if ((cur_len & 0x7) != 0) {
13373			if (cur_len > 0x7) {
13374				cur_len = cur_len - (cur_len & 0x7);
13375				dma_length = cur_len;
13376			} else {
13377				CTL_SIZE_8B(dma_length, cur_len);
13378			}
13379
13380		} else
13381			dma_length = cur_len;
13382
13383		/*
13384		 * If we had to allocate memory for this I/O, instead of using
13385		 * the non-cached mirror memory, we'll need to flush the cache
13386		 * before trying to DMA to the other controller.
13387		 *
13388		 * We could end up doing this multiple times for the same
13389		 * segment if we have a larger local segment than remote
13390		 * segment.  That shouldn't be an issue.
13391		 */
13392		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13393			/*
13394			 * XXX KDM use bus_dmamap_sync() here.
13395			 */
13396		}
13397
13398		rq->size = dma_length;
13399
13400		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13401		tmp_ptr += local_used;
13402
13403		/* Use physical addresses when talking to ISC hardware */
13404		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13405			/* XXX KDM use busdma */
13406#if 0
13407			rq->local = vtophys(tmp_ptr);
13408#endif
13409		} else
13410			rq->local = tmp_ptr;
13411
13412		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13413		tmp_ptr += remote_used;
13414		rq->remote = tmp_ptr;
13415
13416		rq->callback = NULL;
13417
13418		local_used += cur_len;
13419		if (local_used >= local_sglist[i].len) {
13420			i++;
13421			local_used = 0;
13422		}
13423
13424		remote_used += cur_len;
13425		if (remote_used >= remote_sglist[j].len) {
13426			j++;
13427			remote_used = 0;
13428		}
13429		total_used += cur_len;
13430
13431		if (total_used >= io->scsiio.kern_data_len)
13432			rq->callback = callback;
13433
13434		if ((rq->size & 0x7) != 0) {
13435			printf("%s: warning: size %d is not on 8b boundary\n",
13436			       __func__, rq->size);
13437		}
13438		if (((uintptr_t)rq->local & 0x7) != 0) {
13439			printf("%s: warning: local %p not on 8b boundary\n",
13440			       __func__, rq->local);
13441		}
13442		if (((uintptr_t)rq->remote & 0x7) != 0) {
13443			printf("%s: warning: remote %p not on 8b boundary\n",
13444			       __func__, rq->local);
13445		}
13446#if 0
13447		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13448		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13449		       rq->local, rq->remote, rq->size);
13450#endif
13451
13452		isc_ret = ctl_dt_single(rq);
13453		if (isc_ret == CTL_HA_STATUS_WAIT)
13454			continue;
13455
13456		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13457			rq->ret = CTL_HA_STATUS_SUCCESS;
13458		} else {
13459			rq->ret = isc_ret;
13460		}
13461		callback(rq);
13462		goto bailout;
13463	}
13464
13465bailout:
13466	return (retval);
13467
13468}
13469
13470static void
13471ctl_datamove_remote_read(union ctl_io *io)
13472{
13473	int retval;
13474	int i;
13475
13476	/*
13477	 * This will send an error to the other controller in the case of a
13478	 * failure.
13479	 */
13480	retval = ctl_datamove_remote_sgl_setup(io);
13481	if (retval != 0)
13482		return;
13483
13484	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13485					  ctl_datamove_remote_read_cb);
13486	if ((retval != 0)
13487	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13488		/*
13489		 * Make sure we free memory if there was an error..  The
13490		 * ctl_datamove_remote_xfer() function will send the
13491		 * datamove done message, or call the callback with an
13492		 * error if there is a problem.
13493		 */
13494		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13495			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13496	}
13497
13498	return;
13499}
13500
13501/*
13502 * Process a datamove request from the other controller.  This is used for
13503 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13504 * first.  Once that is complete, the data gets DMAed into the remote
13505 * controller's memory.  For reads, we DMA from the remote controller's
13506 * memory into our memory first, and then move it out to the FETD.
13507 */
13508static void
13509ctl_datamove_remote(union ctl_io *io)
13510{
13511	struct ctl_softc *softc;
13512
13513	softc = control_softc;
13514
13515	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13516
13517	/*
13518	 * Note that we look for an aborted I/O here, but don't do some of
13519	 * the other checks that ctl_datamove() normally does.
13520	 * We don't need to run the datamove delay code, since that should
13521	 * have been done if need be on the other controller.
13522	 */
13523	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13524		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13525		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13526		       io->io_hdr.nexus.targ_port,
13527		       io->io_hdr.nexus.targ_target.id,
13528		       io->io_hdr.nexus.targ_lun);
13529		io->io_hdr.port_status = 31338;
13530		ctl_send_datamove_done(io, /*have_lock*/ 0);
13531		return;
13532	}
13533
13534	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13535		ctl_datamove_remote_write(io);
13536	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13537		ctl_datamove_remote_read(io);
13538	} else {
13539		union ctl_ha_msg msg;
13540		struct scsi_sense_data *sense;
13541		uint8_t sks[3];
13542		int retry_count;
13543
13544		memset(&msg, 0, sizeof(msg));
13545
13546		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13547		msg.hdr.status = CTL_SCSI_ERROR;
13548		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13549
13550		retry_count = 4243;
13551
13552		sense = &msg.scsi.sense_data;
13553		sks[0] = SSD_SCS_VALID;
13554		sks[1] = (retry_count >> 8) & 0xff;
13555		sks[2] = retry_count & 0xff;
13556
13557		/* "Internal target failure" */
13558		scsi_set_sense_data(sense,
13559				    /*sense_format*/ SSD_TYPE_NONE,
13560				    /*current_error*/ 1,
13561				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13562				    /*asc*/ 0x44,
13563				    /*ascq*/ 0x00,
13564				    /*type*/ SSD_ELEM_SKS,
13565				    /*size*/ sizeof(sks),
13566				    /*data*/ sks,
13567				    SSD_ELEM_NONE);
13568
13569		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13570		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13571			ctl_failover_io(io, /*have_lock*/ 1);
13572			return;
13573		}
13574
13575		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13576		    CTL_HA_STATUS_SUCCESS) {
13577			/* XXX KDM what to do if this fails? */
13578		}
13579		return;
13580	}
13581
13582}
13583
13584static int
13585ctl_process_done(union ctl_io *io)
13586{
13587	struct ctl_lun *lun;
13588	struct ctl_softc *ctl_softc;
13589	void (*fe_done)(union ctl_io *io);
13590	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13591
13592	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13593
13594	fe_done =
13595	    control_softc->ctl_ports[targ_port]->fe_done;
13596
13597#ifdef CTL_TIME_IO
13598	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13599		char str[256];
13600		char path_str[64];
13601		struct sbuf sb;
13602
13603		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13604		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13605
13606		sbuf_cat(&sb, path_str);
13607		switch (io->io_hdr.io_type) {
13608		case CTL_IO_SCSI:
13609			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13610			sbuf_printf(&sb, "\n");
13611			sbuf_cat(&sb, path_str);
13612			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13613				    io->scsiio.tag_num, io->scsiio.tag_type);
13614			break;
13615		case CTL_IO_TASK:
13616			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13617				    "Tag Type: %d\n", io->taskio.task_action,
13618				    io->taskio.tag_num, io->taskio.tag_type);
13619			break;
13620		default:
13621			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13622			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13623			break;
13624		}
13625		sbuf_cat(&sb, path_str);
13626		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13627			    (intmax_t)time_uptime - io->io_hdr.start_time);
13628		sbuf_finish(&sb);
13629		printf("%s", sbuf_data(&sb));
13630	}
13631#endif /* CTL_TIME_IO */
13632
13633	switch (io->io_hdr.io_type) {
13634	case CTL_IO_SCSI:
13635		break;
13636	case CTL_IO_TASK:
13637		if (bootverbose || verbose > 0)
13638			ctl_io_error_print(io, NULL);
13639		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13640			ctl_free_io(io);
13641		else
13642			fe_done(io);
13643		return (CTL_RETVAL_COMPLETE);
13644		break;
13645	default:
13646		printf("ctl_process_done: invalid io type %d\n",
13647		       io->io_hdr.io_type);
13648		panic("ctl_process_done: invalid io type %d\n",
13649		      io->io_hdr.io_type);
13650		break; /* NOTREACHED */
13651	}
13652
13653	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13654	if (lun == NULL) {
13655		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13656				 io->io_hdr.nexus.targ_mapped_lun));
13657		fe_done(io);
13658		goto bailout;
13659	}
13660	ctl_softc = lun->ctl_softc;
13661
13662	mtx_lock(&lun->lun_lock);
13663
13664	/*
13665	 * Check to see if we have any errors to inject here.  We only
13666	 * inject errors for commands that don't already have errors set.
13667	 */
13668	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13669	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13670		ctl_inject_error(lun, io);
13671
13672	/*
13673	 * XXX KDM how do we treat commands that aren't completed
13674	 * successfully?
13675	 *
13676	 * XXX KDM should we also track I/O latency?
13677	 */
13678	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13679	    io->io_hdr.io_type == CTL_IO_SCSI) {
13680#ifdef CTL_TIME_IO
13681		struct bintime cur_bt;
13682#endif
13683		int type;
13684
13685		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13686		    CTL_FLAG_DATA_IN)
13687			type = CTL_STATS_READ;
13688		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13689		    CTL_FLAG_DATA_OUT)
13690			type = CTL_STATS_WRITE;
13691		else
13692			type = CTL_STATS_NO_IO;
13693
13694		lun->stats.ports[targ_port].bytes[type] +=
13695		    io->scsiio.kern_total_len;
13696		lun->stats.ports[targ_port].operations[type]++;
13697#ifdef CTL_TIME_IO
13698		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13699		   &io->io_hdr.dma_bt);
13700		lun->stats.ports[targ_port].num_dmas[type] +=
13701		    io->io_hdr.num_dmas;
13702		getbintime(&cur_bt);
13703		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13704		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13705#endif
13706	}
13707
13708	/*
13709	 * Remove this from the OOA queue.
13710	 */
13711	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13712
13713	/*
13714	 * Run through the blocked queue on this LUN and see if anything
13715	 * has become unblocked, now that this transaction is done.
13716	 */
13717	ctl_check_blocked(lun);
13718
13719	/*
13720	 * If the LUN has been invalidated, free it if there is nothing
13721	 * left on its OOA queue.
13722	 */
13723	if ((lun->flags & CTL_LUN_INVALID)
13724	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13725		mtx_unlock(&lun->lun_lock);
13726		mtx_lock(&ctl_softc->ctl_lock);
13727		ctl_free_lun(lun);
13728		mtx_unlock(&ctl_softc->ctl_lock);
13729	} else
13730		mtx_unlock(&lun->lun_lock);
13731
13732	/*
13733	 * If this command has been aborted, make sure we set the status
13734	 * properly.  The FETD is responsible for freeing the I/O and doing
13735	 * whatever it needs to do to clean up its state.
13736	 */
13737	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13738		ctl_set_task_aborted(&io->scsiio);
13739
13740	/*
13741	 * We print out status for every task management command.  For SCSI
13742	 * commands, we filter out any unit attention errors; they happen
13743	 * on every boot, and would clutter up the log.  Note:  task
13744	 * management commands aren't printed here, they are printed above,
13745	 * since they should never even make it down here.
13746	 */
13747	switch (io->io_hdr.io_type) {
13748	case CTL_IO_SCSI: {
13749		int error_code, sense_key, asc, ascq;
13750
13751		sense_key = 0;
13752
13753		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13754		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13755			/*
13756			 * Since this is just for printing, no need to
13757			 * show errors here.
13758			 */
13759			scsi_extract_sense_len(&io->scsiio.sense_data,
13760					       io->scsiio.sense_len,
13761					       &error_code,
13762					       &sense_key,
13763					       &asc,
13764					       &ascq,
13765					       /*show_errors*/ 0);
13766		}
13767
13768		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13769		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13770		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13771		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13772
13773			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13774				ctl_softc->skipped_prints++;
13775			} else {
13776				uint32_t skipped_prints;
13777
13778				skipped_prints = ctl_softc->skipped_prints;
13779
13780				ctl_softc->skipped_prints = 0;
13781				ctl_softc->last_print_jiffies = time_uptime;
13782
13783				if (skipped_prints > 0) {
13784#ifdef NEEDTOPORT
13785					csevent_log(CSC_CTL | CSC_SHELF_SW |
13786					    CTL_ERROR_REPORT,
13787					    csevent_LogType_Trace,
13788					    csevent_Severity_Information,
13789					    csevent_AlertLevel_Green,
13790					    csevent_FRU_Firmware,
13791					    csevent_FRU_Unknown,
13792					    "High CTL error volume, %d prints "
13793					    "skipped", skipped_prints);
13794#endif
13795				}
13796				if (bootverbose || verbose > 0)
13797					ctl_io_error_print(io, NULL);
13798			}
13799		}
13800		break;
13801	}
13802	case CTL_IO_TASK:
13803		if (bootverbose || verbose > 0)
13804			ctl_io_error_print(io, NULL);
13805		break;
13806	default:
13807		break;
13808	}
13809
13810	/*
13811	 * Tell the FETD or the other shelf controller we're done with this
13812	 * command.  Note that only SCSI commands get to this point.  Task
13813	 * management commands are completed above.
13814	 *
13815	 * We only send status to the other controller if we're in XFER
13816	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13817	 * received the I/O (from CTL's perspective), and so the status is
13818	 * generated there.
13819	 *
13820	 * XXX KDM if we hold the lock here, we could cause a deadlock
13821	 * if the frontend comes back in in this context to queue
13822	 * something.
13823	 */
13824	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13825	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13826		union ctl_ha_msg msg;
13827
13828		memset(&msg, 0, sizeof(msg));
13829		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13830		msg.hdr.original_sc = io->io_hdr.original_sc;
13831		msg.hdr.nexus = io->io_hdr.nexus;
13832		msg.hdr.status = io->io_hdr.status;
13833		msg.scsi.scsi_status = io->scsiio.scsi_status;
13834		msg.scsi.tag_num = io->scsiio.tag_num;
13835		msg.scsi.tag_type = io->scsiio.tag_type;
13836		msg.scsi.sense_len = io->scsiio.sense_len;
13837		msg.scsi.sense_residual = io->scsiio.sense_residual;
13838		msg.scsi.residual = io->scsiio.residual;
13839		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13840		       sizeof(io->scsiio.sense_data));
13841		/*
13842		 * We copy this whether or not this is an I/O-related
13843		 * command.  Otherwise, we'd have to go and check to see
13844		 * whether it's a read/write command, and it really isn't
13845		 * worth it.
13846		 */
13847		memcpy(&msg.scsi.lbalen,
13848		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13849		       sizeof(msg.scsi.lbalen));
13850
13851		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13852				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13853			/* XXX do something here */
13854		}
13855
13856		ctl_free_io(io);
13857	} else
13858		fe_done(io);
13859
13860bailout:
13861
13862	return (CTL_RETVAL_COMPLETE);
13863}
13864
13865#ifdef CTL_WITH_CA
13866/*
13867 * Front end should call this if it doesn't do autosense.  When the request
13868 * sense comes back in from the initiator, we'll dequeue this and send it.
13869 */
13870int
13871ctl_queue_sense(union ctl_io *io)
13872{
13873	struct ctl_lun *lun;
13874	struct ctl_softc *ctl_softc;
13875	uint32_t initidx, targ_lun;
13876
13877	ctl_softc = control_softc;
13878
13879	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13880
13881	/*
13882	 * LUN lookup will likely move to the ctl_work_thread() once we
13883	 * have our new queueing infrastructure (that doesn't put things on
13884	 * a per-LUN queue initially).  That is so that we can handle
13885	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13886	 * can't deal with that right now.
13887	 */
13888	mtx_lock(&ctl_softc->ctl_lock);
13889
13890	/*
13891	 * If we don't have a LUN for this, just toss the sense
13892	 * information.
13893	 */
13894	targ_lun = io->io_hdr.nexus.targ_lun;
13895	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13896	if ((targ_lun < CTL_MAX_LUNS)
13897	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13898		lun = ctl_softc->ctl_luns[targ_lun];
13899	else
13900		goto bailout;
13901
13902	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13903
13904	mtx_lock(&lun->lun_lock);
13905	/*
13906	 * Already have CA set for this LUN...toss the sense information.
13907	 */
13908	if (ctl_is_set(lun->have_ca, initidx)) {
13909		mtx_unlock(&lun->lun_lock);
13910		goto bailout;
13911	}
13912
13913	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13914	       ctl_min(sizeof(lun->pending_sense[initidx]),
13915	       sizeof(io->scsiio.sense_data)));
13916	ctl_set_mask(lun->have_ca, initidx);
13917	mtx_unlock(&lun->lun_lock);
13918
13919bailout:
13920	mtx_unlock(&ctl_softc->ctl_lock);
13921
13922	ctl_free_io(io);
13923
13924	return (CTL_RETVAL_COMPLETE);
13925}
13926#endif
13927
13928/*
13929 * Primary command inlet from frontend ports.  All SCSI and task I/O
13930 * requests must go through this function.
13931 */
13932int
13933ctl_queue(union ctl_io *io)
13934{
13935	struct ctl_softc *ctl_softc;
13936
13937	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13938
13939	ctl_softc = control_softc;
13940
13941#ifdef CTL_TIME_IO
13942	io->io_hdr.start_time = time_uptime;
13943	getbintime(&io->io_hdr.start_bt);
13944#endif /* CTL_TIME_IO */
13945
13946	/* Map FE-specific LUN ID into global one. */
13947	io->io_hdr.nexus.targ_mapped_lun =
13948	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13949
13950	switch (io->io_hdr.io_type) {
13951	case CTL_IO_SCSI:
13952	case CTL_IO_TASK:
13953		ctl_enqueue_incoming(io);
13954		break;
13955	default:
13956		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13957		return (EINVAL);
13958	}
13959
13960	return (CTL_RETVAL_COMPLETE);
13961}
13962
13963#ifdef CTL_IO_DELAY
13964static void
13965ctl_done_timer_wakeup(void *arg)
13966{
13967	union ctl_io *io;
13968
13969	io = (union ctl_io *)arg;
13970	ctl_done(io);
13971}
13972#endif /* CTL_IO_DELAY */
13973
13974void
13975ctl_done(union ctl_io *io)
13976{
13977	struct ctl_softc *ctl_softc;
13978
13979	ctl_softc = control_softc;
13980
13981	/*
13982	 * Enable this to catch duplicate completion issues.
13983	 */
13984#if 0
13985	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13986		printf("%s: type %d msg %d cdb %x iptl: "
13987		       "%d:%d:%d:%d tag 0x%04x "
13988		       "flag %#x status %x\n",
13989			__func__,
13990			io->io_hdr.io_type,
13991			io->io_hdr.msg_type,
13992			io->scsiio.cdb[0],
13993			io->io_hdr.nexus.initid.id,
13994			io->io_hdr.nexus.targ_port,
13995			io->io_hdr.nexus.targ_target.id,
13996			io->io_hdr.nexus.targ_lun,
13997			(io->io_hdr.io_type ==
13998			CTL_IO_TASK) ?
13999			io->taskio.tag_num :
14000			io->scsiio.tag_num,
14001		        io->io_hdr.flags,
14002			io->io_hdr.status);
14003	} else
14004		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14005#endif
14006
14007	/*
14008	 * This is an internal copy of an I/O, and should not go through
14009	 * the normal done processing logic.
14010	 */
14011	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14012		return;
14013
14014	/*
14015	 * We need to send a msg to the serializing shelf to finish the IO
14016	 * as well.  We don't send a finish message to the other shelf if
14017	 * this is a task management command.  Task management commands
14018	 * aren't serialized in the OOA queue, but rather just executed on
14019	 * both shelf controllers for commands that originated on that
14020	 * controller.
14021	 */
14022	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14023	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14024		union ctl_ha_msg msg_io;
14025
14026		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14027		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14028		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14029		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14030		}
14031		/* continue on to finish IO */
14032	}
14033#ifdef CTL_IO_DELAY
14034	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14035		struct ctl_lun *lun;
14036
14037		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14038
14039		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14040	} else {
14041		struct ctl_lun *lun;
14042
14043		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14044
14045		if ((lun != NULL)
14046		 && (lun->delay_info.done_delay > 0)) {
14047			struct callout *callout;
14048
14049			callout = (struct callout *)&io->io_hdr.timer_bytes;
14050			callout_init(callout, /*mpsafe*/ 1);
14051			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14052			callout_reset(callout,
14053				      lun->delay_info.done_delay * hz,
14054				      ctl_done_timer_wakeup, io);
14055			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14056				lun->delay_info.done_delay = 0;
14057			return;
14058		}
14059	}
14060#endif /* CTL_IO_DELAY */
14061
14062	ctl_enqueue_done(io);
14063}
14064
14065int
14066ctl_isc(struct ctl_scsiio *ctsio)
14067{
14068	struct ctl_lun *lun;
14069	int retval;
14070
14071	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14072
14073	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14074
14075	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14076
14077	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14078
14079	return (retval);
14080}
14081
14082
14083static void
14084ctl_work_thread(void *arg)
14085{
14086	struct ctl_thread *thr = (struct ctl_thread *)arg;
14087	struct ctl_softc *softc = thr->ctl_softc;
14088	union ctl_io *io;
14089	int retval;
14090
14091	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14092
14093	for (;;) {
14094		retval = 0;
14095
14096		/*
14097		 * We handle the queues in this order:
14098		 * - ISC
14099		 * - done queue (to free up resources, unblock other commands)
14100		 * - RtR queue
14101		 * - incoming queue
14102		 *
14103		 * If those queues are empty, we break out of the loop and
14104		 * go to sleep.
14105		 */
14106		mtx_lock(&thr->queue_lock);
14107		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14108		if (io != NULL) {
14109			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14110			mtx_unlock(&thr->queue_lock);
14111			ctl_handle_isc(io);
14112			continue;
14113		}
14114		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14115		if (io != NULL) {
14116			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14117			/* clear any blocked commands, call fe_done */
14118			mtx_unlock(&thr->queue_lock);
14119			retval = ctl_process_done(io);
14120			continue;
14121		}
14122		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14123		if (io != NULL) {
14124			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14125			mtx_unlock(&thr->queue_lock);
14126			if (io->io_hdr.io_type == CTL_IO_TASK)
14127				ctl_run_task(io);
14128			else
14129				ctl_scsiio_precheck(softc, &io->scsiio);
14130			continue;
14131		}
14132		if (!ctl_pause_rtr) {
14133			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14134			if (io != NULL) {
14135				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14136				mtx_unlock(&thr->queue_lock);
14137				retval = ctl_scsiio(&io->scsiio);
14138				if (retval != CTL_RETVAL_COMPLETE)
14139					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14140				continue;
14141			}
14142		}
14143
14144		/* Sleep until we have something to do. */
14145		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14146	}
14147}
14148
14149static void
14150ctl_lun_thread(void *arg)
14151{
14152	struct ctl_softc *softc = (struct ctl_softc *)arg;
14153	struct ctl_be_lun *be_lun;
14154	int retval;
14155
14156	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14157
14158	for (;;) {
14159		retval = 0;
14160		mtx_lock(&softc->ctl_lock);
14161		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14162		if (be_lun != NULL) {
14163			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14164			mtx_unlock(&softc->ctl_lock);
14165			ctl_create_lun(be_lun);
14166			continue;
14167		}
14168
14169		/* Sleep until we have something to do. */
14170		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14171		    PDROP | PRIBIO, "-", 0);
14172	}
14173}
14174
14175static void
14176ctl_enqueue_incoming(union ctl_io *io)
14177{
14178	struct ctl_softc *softc = control_softc;
14179	struct ctl_thread *thr;
14180	u_int idx;
14181
14182	idx = (io->io_hdr.nexus.targ_port * 127 +
14183	       io->io_hdr.nexus.initid.id) % worker_threads;
14184	thr = &softc->threads[idx];
14185	mtx_lock(&thr->queue_lock);
14186	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14187	mtx_unlock(&thr->queue_lock);
14188	wakeup(thr);
14189}
14190
14191static void
14192ctl_enqueue_rtr(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->rtr_queue, &io->io_hdr, links);
14200	mtx_unlock(&thr->queue_lock);
14201	wakeup(thr);
14202}
14203
14204static void
14205ctl_enqueue_done(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->done_queue, &io->io_hdr, links);
14213	mtx_unlock(&thr->queue_lock);
14214	wakeup(thr);
14215}
14216
14217static void
14218ctl_enqueue_isc(union ctl_io *io)
14219{
14220	struct ctl_softc *softc = control_softc;
14221	struct ctl_thread *thr;
14222
14223	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14224	mtx_lock(&thr->queue_lock);
14225	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14226	mtx_unlock(&thr->queue_lock);
14227	wakeup(thr);
14228}
14229
14230/* Initialization and failover */
14231
14232void
14233ctl_init_isc_msg(void)
14234{
14235	printf("CTL: Still calling this thing\n");
14236}
14237
14238/*
14239 * Init component
14240 * 	Initializes component into configuration defined by bootMode
14241 *	(see hasc-sv.c)
14242 *  	returns hasc_Status:
14243 * 		OK
14244 *		ERROR - fatal error
14245 */
14246static ctl_ha_comp_status
14247ctl_isc_init(struct ctl_ha_component *c)
14248{
14249	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14250
14251	c->status = ret;
14252	return ret;
14253}
14254
14255/* Start component
14256 * 	Starts component in state requested. If component starts successfully,
14257 *	it must set its own state to the requestrd state
14258 *	When requested state is HASC_STATE_HA, the component may refine it
14259 * 	by adding _SLAVE or _MASTER flags.
14260 *	Currently allowed state transitions are:
14261 *	UNKNOWN->HA		- initial startup
14262 *	UNKNOWN->SINGLE - initial startup when no parter detected
14263 *	HA->SINGLE		- failover
14264 * returns ctl_ha_comp_status:
14265 * 		OK	- component successfully started in requested state
14266 *		FAILED  - could not start the requested state, failover may
14267 * 			  be possible
14268 *		ERROR	- fatal error detected, no future startup possible
14269 */
14270static ctl_ha_comp_status
14271ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14272{
14273	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14274
14275	printf("%s: go\n", __func__);
14276
14277	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14278	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14279		ctl_is_single = 0;
14280		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14281		    != CTL_HA_STATUS_SUCCESS) {
14282			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14283			ret = CTL_HA_COMP_STATUS_ERROR;
14284		}
14285	} else if (CTL_HA_STATE_IS_HA(c->state)
14286		&& CTL_HA_STATE_IS_SINGLE(state)){
14287		// HA->SINGLE transition
14288	        ctl_failover();
14289		ctl_is_single = 1;
14290	} else {
14291		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14292		       c->state, state);
14293		ret = CTL_HA_COMP_STATUS_ERROR;
14294	}
14295	if (CTL_HA_STATE_IS_SINGLE(state))
14296		ctl_is_single = 1;
14297
14298	c->state = state;
14299	c->status = ret;
14300	return ret;
14301}
14302
14303/*
14304 * Quiesce component
14305 * The component must clear any error conditions (set status to OK) and
14306 * prepare itself to another Start call
14307 * returns ctl_ha_comp_status:
14308 * 	OK
14309 *	ERROR
14310 */
14311static ctl_ha_comp_status
14312ctl_isc_quiesce(struct ctl_ha_component *c)
14313{
14314	int ret = CTL_HA_COMP_STATUS_OK;
14315
14316	ctl_pause_rtr = 1;
14317	c->status = ret;
14318	return ret;
14319}
14320
14321struct ctl_ha_component ctl_ha_component_ctlisc =
14322{
14323	.name = "CTL ISC",
14324	.state = CTL_HA_STATE_UNKNOWN,
14325	.init = ctl_isc_init,
14326	.start = ctl_isc_start,
14327	.quiesce = ctl_isc_quiesce
14328};
14329
14330/*
14331 *  vim: ts=8
14332 */
14333