ctl.c revision 273046
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 273046 2014-10-13 16:15: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*/SCP_SWP,
297	/*flags4*/0,
298	/*aen_holdoff_period*/{0, 0},
299	/*busy_timeout_period*/{0, 0},
300	/*extended_selftest_completion_time*/{0, 0}
301};
302
303
304/*
305 * XXX KDM move these into the softc.
306 */
307static int rcv_sync_msg;
308static int persis_offset;
309static uint8_t ctl_pause_rtr;
310static int     ctl_is_single = 1;
311static int     index_to_aps_page;
312
313SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314static int worker_threads = -1;
315SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316    &worker_threads, 1, "Number of worker threads");
317static int verbose = 0;
318SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319    &verbose, 0, "Show SCSI errors returned to initiator");
320
321/*
322 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
324 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
325 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
326 */
327#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
328
329static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
330				  int param);
331static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
332static int ctl_init(void);
333void ctl_shutdown(void);
334static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
335static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
336static void ctl_ioctl_online(void *arg);
337static void ctl_ioctl_offline(void *arg);
338static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
339static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
340static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
341static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
342static int ctl_ioctl_submit_wait(union ctl_io *io);
343static void ctl_ioctl_datamove(union ctl_io *io);
344static void ctl_ioctl_done(union ctl_io *io);
345static void ctl_ioctl_hard_startstop_callback(void *arg,
346					      struct cfi_metatask *metatask);
347static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
348static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
349			      struct ctl_ooa *ooa_hdr,
350			      struct ctl_ooa_entry *kern_entries);
351static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
352		     struct thread *td);
353static uint32_t ctl_map_lun(int port_num, uint32_t lun);
354static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
355#ifdef unused
356static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
357				   uint32_t targ_target, uint32_t targ_lun,
358				   int can_wait);
359static void ctl_kfree_io(union ctl_io *io);
360#endif /* unused */
361static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
362			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
363static int ctl_free_lun(struct ctl_lun *lun);
364static void ctl_create_lun(struct ctl_be_lun *be_lun);
365/**
366static void ctl_failover_change_pages(struct ctl_softc *softc,
367				      struct ctl_scsiio *ctsio, int master);
368**/
369
370static int ctl_do_mode_select(union ctl_io *io);
371static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
372			   uint64_t res_key, uint64_t sa_res_key,
373			   uint8_t type, uint32_t residx,
374			   struct ctl_scsiio *ctsio,
375			   struct scsi_per_res_out *cdb,
376			   struct scsi_per_res_out_parms* param);
377static void ctl_pro_preempt_other(struct ctl_lun *lun,
378				  union ctl_ha_msg *msg);
379static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
380static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
381static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
382static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
383static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
385static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
386					 int alloc_len);
387static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
388					 int alloc_len);
389static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
390static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
391static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
392static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
393static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
394static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
395static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
396    union ctl_io *pending_io, union ctl_io *ooa_io);
397static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
398				union ctl_io *starting_io);
399static int ctl_check_blocked(struct ctl_lun *lun);
400static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
401				struct ctl_lun *lun,
402				const struct ctl_cmd_entry *entry,
403				struct ctl_scsiio *ctsio);
404//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
405static void ctl_failover(void);
406static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
407			       struct ctl_scsiio *ctsio);
408static int ctl_scsiio(struct ctl_scsiio *ctsio);
409
410static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
411static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
412			    ctl_ua_type ua_type);
413static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
414			 ctl_ua_type ua_type);
415static int ctl_abort_task(union ctl_io *io);
416static int ctl_abort_task_set(union ctl_io *io);
417static int ctl_i_t_nexus_reset(union ctl_io *io);
418static void ctl_run_task(union ctl_io *io);
419#ifdef CTL_IO_DELAY
420static void ctl_datamove_timer_wakeup(void *arg);
421static void ctl_done_timer_wakeup(void *arg);
422#endif /* CTL_IO_DELAY */
423
424static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
425static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
426static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
427static void ctl_datamove_remote_write(union ctl_io *io);
428static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
429static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
430static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
431static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
432				    ctl_ha_dt_cb callback);
433static void ctl_datamove_remote_read(union ctl_io *io);
434static void ctl_datamove_remote(union ctl_io *io);
435static int ctl_process_done(union ctl_io *io);
436static void ctl_lun_thread(void *arg);
437static void ctl_work_thread(void *arg);
438static void ctl_enqueue_incoming(union ctl_io *io);
439static void ctl_enqueue_rtr(union ctl_io *io);
440static void ctl_enqueue_done(union ctl_io *io);
441static void ctl_enqueue_isc(union ctl_io *io);
442static const struct ctl_cmd_entry *
443    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
444static const struct ctl_cmd_entry *
445    ctl_validate_command(struct ctl_scsiio *ctsio);
446static int ctl_cmd_applicable(uint8_t lun_type,
447    const struct ctl_cmd_entry *entry);
448
449/*
450 * Load the serialization table.  This isn't very pretty, but is probably
451 * the easiest way to do it.
452 */
453#include "ctl_ser_table.c"
454
455/*
456 * We only need to define open, close and ioctl routines for this driver.
457 */
458static struct cdevsw ctl_cdevsw = {
459	.d_version =	D_VERSION,
460	.d_flags =	0,
461	.d_open =	ctl_open,
462	.d_close =	ctl_close,
463	.d_ioctl =	ctl_ioctl,
464	.d_name =	"ctl",
465};
466
467
468MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
469MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
470
471static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
472
473static moduledata_t ctl_moduledata = {
474	"ctl",
475	ctl_module_event_handler,
476	NULL
477};
478
479DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
480MODULE_VERSION(ctl, 1);
481
482static struct ctl_frontend ioctl_frontend =
483{
484	.name = "ioctl",
485};
486
487static void
488ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
489			    union ctl_ha_msg *msg_info)
490{
491	struct ctl_scsiio *ctsio;
492
493	if (msg_info->hdr.original_sc == NULL) {
494		printf("%s: original_sc == NULL!\n", __func__);
495		/* XXX KDM now what? */
496		return;
497	}
498
499	ctsio = &msg_info->hdr.original_sc->scsiio;
500	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
501	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
502	ctsio->io_hdr.status = msg_info->hdr.status;
503	ctsio->scsi_status = msg_info->scsi.scsi_status;
504	ctsio->sense_len = msg_info->scsi.sense_len;
505	ctsio->sense_residual = msg_info->scsi.sense_residual;
506	ctsio->residual = msg_info->scsi.residual;
507	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
508	       sizeof(ctsio->sense_data));
509	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
510	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
511	ctl_enqueue_isc((union ctl_io *)ctsio);
512}
513
514static void
515ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
516				union ctl_ha_msg *msg_info)
517{
518	struct ctl_scsiio *ctsio;
519
520	if (msg_info->hdr.serializing_sc == NULL) {
521		printf("%s: serializing_sc == NULL!\n", __func__);
522		/* XXX KDM now what? */
523		return;
524	}
525
526	ctsio = &msg_info->hdr.serializing_sc->scsiio;
527#if 0
528	/*
529	 * Attempt to catch the situation where an I/O has
530	 * been freed, and we're using it again.
531	 */
532	if (ctsio->io_hdr.io_type == 0xff) {
533		union ctl_io *tmp_io;
534		tmp_io = (union ctl_io *)ctsio;
535		printf("%s: %p use after free!\n", __func__,
536		       ctsio);
537		printf("%s: type %d msg %d cdb %x iptl: "
538		       "%d:%d:%d:%d tag 0x%04x "
539		       "flag %#x status %x\n",
540			__func__,
541			tmp_io->io_hdr.io_type,
542			tmp_io->io_hdr.msg_type,
543			tmp_io->scsiio.cdb[0],
544			tmp_io->io_hdr.nexus.initid.id,
545			tmp_io->io_hdr.nexus.targ_port,
546			tmp_io->io_hdr.nexus.targ_target.id,
547			tmp_io->io_hdr.nexus.targ_lun,
548			(tmp_io->io_hdr.io_type ==
549			CTL_IO_TASK) ?
550			tmp_io->taskio.tag_num :
551			tmp_io->scsiio.tag_num,
552		        tmp_io->io_hdr.flags,
553			tmp_io->io_hdr.status);
554	}
555#endif
556	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
557	ctl_enqueue_isc((union ctl_io *)ctsio);
558}
559
560/*
561 * ISC (Inter Shelf Communication) event handler.  Events from the HA
562 * subsystem come in here.
563 */
564static void
565ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
566{
567	struct ctl_softc *ctl_softc;
568	union ctl_io *io;
569	struct ctl_prio *presio;
570	ctl_ha_status isc_status;
571
572	ctl_softc = control_softc;
573	io = NULL;
574
575
576#if 0
577	printf("CTL: Isc Msg event %d\n", event);
578#endif
579	if (event == CTL_HA_EVT_MSG_RECV) {
580		union ctl_ha_msg msg_info;
581
582		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
583					     sizeof(msg_info), /*wait*/ 0);
584#if 0
585		printf("CTL: msg_type %d\n", msg_info.msg_type);
586#endif
587		if (isc_status != 0) {
588			printf("Error receiving message, status = %d\n",
589			       isc_status);
590			return;
591		}
592
593		switch (msg_info.hdr.msg_type) {
594		case CTL_MSG_SERIALIZE:
595#if 0
596			printf("Serialize\n");
597#endif
598			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
599			if (io == NULL) {
600				printf("ctl_isc_event_handler: can't allocate "
601				       "ctl_io!\n");
602				/* Bad Juju */
603				/* Need to set busy and send msg back */
604				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
605				msg_info.hdr.status = CTL_SCSI_ERROR;
606				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
607				msg_info.scsi.sense_len = 0;
608			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
609				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
610				}
611				goto bailout;
612			}
613			ctl_zero_io(io);
614			// populate ctsio from msg_info
615			io->io_hdr.io_type = CTL_IO_SCSI;
616			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
617			io->io_hdr.original_sc = msg_info.hdr.original_sc;
618#if 0
619			printf("pOrig %x\n", (int)msg_info.original_sc);
620#endif
621			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
622					    CTL_FLAG_IO_ACTIVE;
623			/*
624			 * If we're in serialization-only mode, we don't
625			 * want to go through full done processing.  Thus
626			 * the COPY flag.
627			 *
628			 * XXX KDM add another flag that is more specific.
629			 */
630			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
631				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
632			io->io_hdr.nexus = msg_info.hdr.nexus;
633#if 0
634			printf("targ %d, port %d, iid %d, lun %d\n",
635			       io->io_hdr.nexus.targ_target.id,
636			       io->io_hdr.nexus.targ_port,
637			       io->io_hdr.nexus.initid.id,
638			       io->io_hdr.nexus.targ_lun);
639#endif
640			io->scsiio.tag_num = msg_info.scsi.tag_num;
641			io->scsiio.tag_type = msg_info.scsi.tag_type;
642			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
643			       CTL_MAX_CDBLEN);
644			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
645				const struct ctl_cmd_entry *entry;
646
647				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
648				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
649				io->io_hdr.flags |=
650					entry->flags & CTL_FLAG_DATA_MASK;
651			}
652			ctl_enqueue_isc(io);
653			break;
654
655		/* Performed on the Originating SC, XFER mode only */
656		case CTL_MSG_DATAMOVE: {
657			struct ctl_sg_entry *sgl;
658			int i, j;
659
660			io = msg_info.hdr.original_sc;
661			if (io == NULL) {
662				printf("%s: original_sc == NULL!\n", __func__);
663				/* XXX KDM do something here */
664				break;
665			}
666			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
667			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
668			/*
669			 * Keep track of this, we need to send it back over
670			 * when the datamove is complete.
671			 */
672			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
673
674			if (msg_info.dt.sg_sequence == 0) {
675				/*
676				 * XXX KDM we use the preallocated S/G list
677				 * here, but we'll need to change this to
678				 * dynamic allocation if we need larger S/G
679				 * lists.
680				 */
681				if (msg_info.dt.kern_sg_entries >
682				    sizeof(io->io_hdr.remote_sglist) /
683				    sizeof(io->io_hdr.remote_sglist[0])) {
684					printf("%s: number of S/G entries "
685					    "needed %u > allocated num %zd\n",
686					    __func__,
687					    msg_info.dt.kern_sg_entries,
688					    sizeof(io->io_hdr.remote_sglist)/
689					    sizeof(io->io_hdr.remote_sglist[0]));
690
691					/*
692					 * XXX KDM send a message back to
693					 * the other side to shut down the
694					 * DMA.  The error will come back
695					 * through via the normal channel.
696					 */
697					break;
698				}
699				sgl = io->io_hdr.remote_sglist;
700				memset(sgl, 0,
701				       sizeof(io->io_hdr.remote_sglist));
702
703				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
704
705				io->scsiio.kern_sg_entries =
706					msg_info.dt.kern_sg_entries;
707				io->scsiio.rem_sg_entries =
708					msg_info.dt.kern_sg_entries;
709				io->scsiio.kern_data_len =
710					msg_info.dt.kern_data_len;
711				io->scsiio.kern_total_len =
712					msg_info.dt.kern_total_len;
713				io->scsiio.kern_data_resid =
714					msg_info.dt.kern_data_resid;
715				io->scsiio.kern_rel_offset =
716					msg_info.dt.kern_rel_offset;
717				/*
718				 * Clear out per-DMA flags.
719				 */
720				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
721				/*
722				 * Add per-DMA flags that are set for this
723				 * particular DMA request.
724				 */
725				io->io_hdr.flags |= msg_info.dt.flags &
726						    CTL_FLAG_RDMA_MASK;
727			} else
728				sgl = (struct ctl_sg_entry *)
729					io->scsiio.kern_data_ptr;
730
731			for (i = msg_info.dt.sent_sg_entries, j = 0;
732			     i < (msg_info.dt.sent_sg_entries +
733			     msg_info.dt.cur_sg_entries); i++, j++) {
734				sgl[i].addr = msg_info.dt.sg_list[j].addr;
735				sgl[i].len = msg_info.dt.sg_list[j].len;
736
737#if 0
738				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
739				       __func__,
740				       msg_info.dt.sg_list[j].addr,
741				       msg_info.dt.sg_list[j].len,
742				       sgl[i].addr, sgl[i].len, j, i);
743#endif
744			}
745#if 0
746			memcpy(&sgl[msg_info.dt.sent_sg_entries],
747			       msg_info.dt.sg_list,
748			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
749#endif
750
751			/*
752			 * If this is the last piece of the I/O, we've got
753			 * the full S/G list.  Queue processing in the thread.
754			 * Otherwise wait for the next piece.
755			 */
756			if (msg_info.dt.sg_last != 0)
757				ctl_enqueue_isc(io);
758			break;
759		}
760		/* Performed on the Serializing (primary) SC, XFER mode only */
761		case CTL_MSG_DATAMOVE_DONE: {
762			if (msg_info.hdr.serializing_sc == NULL) {
763				printf("%s: serializing_sc == NULL!\n",
764				       __func__);
765				/* XXX KDM now what? */
766				break;
767			}
768			/*
769			 * We grab the sense information here in case
770			 * there was a failure, so we can return status
771			 * back to the initiator.
772			 */
773			io = msg_info.hdr.serializing_sc;
774			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
775			io->io_hdr.status = msg_info.hdr.status;
776			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
777			io->scsiio.sense_len = msg_info.scsi.sense_len;
778			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
779			io->io_hdr.port_status = msg_info.scsi.fetd_status;
780			io->scsiio.residual = msg_info.scsi.residual;
781			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
782			       sizeof(io->scsiio.sense_data));
783			ctl_enqueue_isc(io);
784			break;
785		}
786
787		/* Preformed on Originating SC, SER_ONLY mode */
788		case CTL_MSG_R2R:
789			io = msg_info.hdr.original_sc;
790			if (io == NULL) {
791				printf("%s: Major Bummer\n", __func__);
792				return;
793			} else {
794#if 0
795				printf("pOrig %x\n",(int) ctsio);
796#endif
797			}
798			io->io_hdr.msg_type = CTL_MSG_R2R;
799			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
800			ctl_enqueue_isc(io);
801			break;
802
803		/*
804		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
805		 * mode.
806		 * Performed on the Originating (i.e. secondary) SC in XFER
807		 * mode
808		 */
809		case CTL_MSG_FINISH_IO:
810			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
811				ctl_isc_handler_finish_xfer(ctl_softc,
812							    &msg_info);
813			else
814				ctl_isc_handler_finish_ser_only(ctl_softc,
815								&msg_info);
816			break;
817
818		/* Preformed on Originating SC */
819		case CTL_MSG_BAD_JUJU:
820			io = msg_info.hdr.original_sc;
821			if (io == NULL) {
822				printf("%s: Bad JUJU!, original_sc is NULL!\n",
823				       __func__);
824				break;
825			}
826			ctl_copy_sense_data(&msg_info, io);
827			/*
828			 * IO should have already been cleaned up on other
829			 * SC so clear this flag so we won't send a message
830			 * back to finish the IO there.
831			 */
832			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
833			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
834
835			/* io = msg_info.hdr.serializing_sc; */
836			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
837			ctl_enqueue_isc(io);
838			break;
839
840		/* Handle resets sent from the other side */
841		case CTL_MSG_MANAGE_TASKS: {
842			struct ctl_taskio *taskio;
843			taskio = (struct ctl_taskio *)ctl_alloc_io(
844				(void *)ctl_softc->othersc_pool);
845			if (taskio == NULL) {
846				printf("ctl_isc_event_handler: can't allocate "
847				       "ctl_io!\n");
848				/* Bad Juju */
849				/* should I just call the proper reset func
850				   here??? */
851				goto bailout;
852			}
853			ctl_zero_io((union ctl_io *)taskio);
854			taskio->io_hdr.io_type = CTL_IO_TASK;
855			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
856			taskio->io_hdr.nexus = msg_info.hdr.nexus;
857			taskio->task_action = msg_info.task.task_action;
858			taskio->tag_num = msg_info.task.tag_num;
859			taskio->tag_type = msg_info.task.tag_type;
860#ifdef CTL_TIME_IO
861			taskio->io_hdr.start_time = time_uptime;
862			getbintime(&taskio->io_hdr.start_bt);
863#if 0
864			cs_prof_gettime(&taskio->io_hdr.start_ticks);
865#endif
866#endif /* CTL_TIME_IO */
867			ctl_run_task((union ctl_io *)taskio);
868			break;
869		}
870		/* Persistent Reserve action which needs attention */
871		case CTL_MSG_PERS_ACTION:
872			presio = (struct ctl_prio *)ctl_alloc_io(
873				(void *)ctl_softc->othersc_pool);
874			if (presio == NULL) {
875				printf("ctl_isc_event_handler: can't allocate "
876				       "ctl_io!\n");
877				/* Bad Juju */
878				/* Need to set busy and send msg back */
879				goto bailout;
880			}
881			ctl_zero_io((union ctl_io *)presio);
882			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883			presio->pr_msg = msg_info.pr;
884			ctl_enqueue_isc((union ctl_io *)presio);
885			break;
886		case CTL_MSG_SYNC_FE:
887			rcv_sync_msg = 1;
888			break;
889		case CTL_MSG_APS_LOCK: {
890			// It's quicker to execute this then to
891			// queue it.
892			struct ctl_lun *lun;
893			struct ctl_page_index *page_index;
894			struct copan_aps_subpage *current_sp;
895			uint32_t targ_lun;
896
897			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
898			lun = ctl_softc->ctl_luns[targ_lun];
899			mtx_lock(&lun->lun_lock);
900			page_index = &lun->mode_pages.index[index_to_aps_page];
901			current_sp = (struct copan_aps_subpage *)
902				     (page_index->page_data +
903				     (page_index->page_len * CTL_PAGE_CURRENT));
904
905			current_sp->lock_active = msg_info.aps.lock_flag;
906			mtx_unlock(&lun->lun_lock);
907		        break;
908		}
909		default:
910		        printf("How did I get here?\n");
911		}
912	} else if (event == CTL_HA_EVT_MSG_SENT) {
913		if (param != CTL_HA_STATUS_SUCCESS) {
914			printf("Bad status from ctl_ha_msg_send status %d\n",
915			       param);
916		}
917		return;
918	} else if (event == CTL_HA_EVT_DISCONNECT) {
919		printf("CTL: Got a disconnect from Isc\n");
920		return;
921	} else {
922		printf("ctl_isc_event_handler: Unknown event %d\n", event);
923		return;
924	}
925
926bailout:
927	return;
928}
929
930static void
931ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
932{
933	struct scsi_sense_data *sense;
934
935	sense = &dest->scsiio.sense_data;
936	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
937	dest->scsiio.scsi_status = src->scsi.scsi_status;
938	dest->scsiio.sense_len = src->scsi.sense_len;
939	dest->io_hdr.status = src->hdr.status;
940}
941
942static int
943ctl_init(void)
944{
945	struct ctl_softc *softc;
946	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
947	struct ctl_port *port;
948        uint8_t sc_id =0;
949	int i, error, retval;
950	//int isc_retval;
951
952	retval = 0;
953	ctl_pause_rtr = 0;
954        rcv_sync_msg = 0;
955
956	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
957			       M_WAITOK | M_ZERO);
958	softc = control_softc;
959
960	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
961			      "cam/ctl");
962
963	softc->dev->si_drv1 = softc;
964
965	/*
966	 * By default, return a "bad LUN" peripheral qualifier for unknown
967	 * LUNs.  The user can override this default using the tunable or
968	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
969	 */
970	softc->inquiry_pq_no_lun = 1;
971	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
972			  &softc->inquiry_pq_no_lun);
973	sysctl_ctx_init(&softc->sysctl_ctx);
974	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
975		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
976		CTLFLAG_RD, 0, "CAM Target Layer");
977
978	if (softc->sysctl_tree == NULL) {
979		printf("%s: unable to allocate sysctl tree\n", __func__);
980		destroy_dev(softc->dev);
981		free(control_softc, M_DEVBUF);
982		control_softc = NULL;
983		return (ENOMEM);
984	}
985
986	SYSCTL_ADD_INT(&softc->sysctl_ctx,
987		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
988		       "inquiry_pq_no_lun", CTLFLAG_RW,
989		       &softc->inquiry_pq_no_lun, 0,
990		       "Report no lun possible for invalid LUNs");
991
992	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
993	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
994	softc->open_count = 0;
995
996	/*
997	 * Default to actually sending a SYNCHRONIZE CACHE command down to
998	 * the drive.
999	 */
1000	softc->flags = CTL_FLAG_REAL_SYNC;
1001
1002	/*
1003	 * In Copan's HA scheme, the "master" and "slave" roles are
1004	 * figured out through the slot the controller is in.  Although it
1005	 * is an active/active system, someone has to be in charge.
1006 	 */
1007#ifdef NEEDTOPORT
1008        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1009#endif
1010
1011        if (sc_id == 0) {
1012		softc->flags |= CTL_FLAG_MASTER_SHELF;
1013		persis_offset = 0;
1014	} else
1015		persis_offset = CTL_MAX_INITIATORS;
1016
1017	/*
1018	 * XXX KDM need to figure out where we want to get our target ID
1019	 * and WWID.  Is it different on each port?
1020	 */
1021	softc->target.id = 0;
1022	softc->target.wwid[0] = 0x12345678;
1023	softc->target.wwid[1] = 0x87654321;
1024	STAILQ_INIT(&softc->lun_list);
1025	STAILQ_INIT(&softc->pending_lun_queue);
1026	STAILQ_INIT(&softc->fe_list);
1027	STAILQ_INIT(&softc->port_list);
1028	STAILQ_INIT(&softc->be_list);
1029	STAILQ_INIT(&softc->io_pools);
1030	ctl_tpc_init(softc);
1031
1032	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1033			    &internal_pool)!= 0){
1034		printf("ctl: can't allocate %d entry internal pool, "
1035		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1036		return (ENOMEM);
1037	}
1038
1039	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1040			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1041		printf("ctl: can't allocate %d entry emergency pool, "
1042		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1043		ctl_pool_free(internal_pool);
1044		return (ENOMEM);
1045	}
1046
1047	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1048	                    &other_pool) != 0)
1049	{
1050		printf("ctl: can't allocate %d entry other SC pool, "
1051		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1052		ctl_pool_free(internal_pool);
1053		ctl_pool_free(emergency_pool);
1054		return (ENOMEM);
1055	}
1056
1057	softc->internal_pool = internal_pool;
1058	softc->emergency_pool = emergency_pool;
1059	softc->othersc_pool = other_pool;
1060
1061	if (worker_threads <= 0)
1062		worker_threads = max(1, mp_ncpus / 4);
1063	if (worker_threads > CTL_MAX_THREADS)
1064		worker_threads = CTL_MAX_THREADS;
1065
1066	for (i = 0; i < worker_threads; i++) {
1067		struct ctl_thread *thr = &softc->threads[i];
1068
1069		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1070		thr->ctl_softc = softc;
1071		STAILQ_INIT(&thr->incoming_queue);
1072		STAILQ_INIT(&thr->rtr_queue);
1073		STAILQ_INIT(&thr->done_queue);
1074		STAILQ_INIT(&thr->isc_queue);
1075
1076		error = kproc_kthread_add(ctl_work_thread, thr,
1077		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1078		if (error != 0) {
1079			printf("error creating CTL work thread!\n");
1080			ctl_pool_free(internal_pool);
1081			ctl_pool_free(emergency_pool);
1082			ctl_pool_free(other_pool);
1083			return (error);
1084		}
1085	}
1086	error = kproc_kthread_add(ctl_lun_thread, softc,
1087	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1088	if (error != 0) {
1089		printf("error creating CTL lun thread!\n");
1090		ctl_pool_free(internal_pool);
1091		ctl_pool_free(emergency_pool);
1092		ctl_pool_free(other_pool);
1093		return (error);
1094	}
1095	if (bootverbose)
1096		printf("ctl: CAM Target Layer loaded\n");
1097
1098	/*
1099	 * Initialize the ioctl front end.
1100	 */
1101	ctl_frontend_register(&ioctl_frontend);
1102	port = &softc->ioctl_info.port;
1103	port->frontend = &ioctl_frontend;
1104	sprintf(softc->ioctl_info.port_name, "ioctl");
1105	port->port_type = CTL_PORT_IOCTL;
1106	port->num_requested_ctl_io = 100;
1107	port->port_name = softc->ioctl_info.port_name;
1108	port->port_online = ctl_ioctl_online;
1109	port->port_offline = ctl_ioctl_offline;
1110	port->onoff_arg = &softc->ioctl_info;
1111	port->lun_enable = ctl_ioctl_lun_enable;
1112	port->lun_disable = ctl_ioctl_lun_disable;
1113	port->targ_lun_arg = &softc->ioctl_info;
1114	port->fe_datamove = ctl_ioctl_datamove;
1115	port->fe_done = ctl_ioctl_done;
1116	port->max_targets = 15;
1117	port->max_target_id = 15;
1118
1119	if (ctl_port_register(&softc->ioctl_info.port,
1120	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1121		printf("ctl: ioctl front end registration failed, will "
1122		       "continue anyway\n");
1123	}
1124
1125#ifdef CTL_IO_DELAY
1126	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1127		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1128		       sizeof(struct callout), CTL_TIMER_BYTES);
1129		return (EINVAL);
1130	}
1131#endif /* CTL_IO_DELAY */
1132
1133	return (0);
1134}
1135
1136void
1137ctl_shutdown(void)
1138{
1139	struct ctl_softc *softc;
1140	struct ctl_lun *lun, *next_lun;
1141	struct ctl_io_pool *pool;
1142
1143	softc = (struct ctl_softc *)control_softc;
1144
1145	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1146		printf("ctl: ioctl front end deregistration failed\n");
1147
1148	mtx_lock(&softc->ctl_lock);
1149
1150	/*
1151	 * Free up each LUN.
1152	 */
1153	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1154		next_lun = STAILQ_NEXT(lun, links);
1155		ctl_free_lun(lun);
1156	}
1157
1158	mtx_unlock(&softc->ctl_lock);
1159
1160	ctl_frontend_deregister(&ioctl_frontend);
1161
1162	/*
1163	 * This will rip the rug out from under any FETDs or anyone else
1164	 * that has a pool allocated.  Since we increment our module
1165	 * refcount any time someone outside the main CTL module allocates
1166	 * a pool, we shouldn't have any problems here.  The user won't be
1167	 * able to unload the CTL module until client modules have
1168	 * successfully unloaded.
1169	 */
1170	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1171		ctl_pool_free(pool);
1172
1173#if 0
1174	ctl_shutdown_thread(softc->work_thread);
1175	mtx_destroy(&softc->queue_lock);
1176#endif
1177
1178	ctl_tpc_shutdown(softc);
1179	mtx_destroy(&softc->pool_lock);
1180	mtx_destroy(&softc->ctl_lock);
1181
1182	destroy_dev(softc->dev);
1183
1184	sysctl_ctx_free(&softc->sysctl_ctx);
1185
1186	free(control_softc, M_DEVBUF);
1187	control_softc = NULL;
1188
1189	if (bootverbose)
1190		printf("ctl: CAM Target Layer unloaded\n");
1191}
1192
1193static int
1194ctl_module_event_handler(module_t mod, int what, void *arg)
1195{
1196
1197	switch (what) {
1198	case MOD_LOAD:
1199		return (ctl_init());
1200	case MOD_UNLOAD:
1201		return (EBUSY);
1202	default:
1203		return (EOPNOTSUPP);
1204	}
1205}
1206
1207/*
1208 * XXX KDM should we do some access checks here?  Bump a reference count to
1209 * prevent a CTL module from being unloaded while someone has it open?
1210 */
1211static int
1212ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1213{
1214	return (0);
1215}
1216
1217static int
1218ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1219{
1220	return (0);
1221}
1222
1223int
1224ctl_port_enable(ctl_port_type port_type)
1225{
1226	struct ctl_softc *softc;
1227	struct ctl_port *port;
1228
1229	if (ctl_is_single == 0) {
1230		union ctl_ha_msg msg_info;
1231		int isc_retval;
1232
1233#if 0
1234		printf("%s: HA mode, synchronizing frontend enable\n",
1235		        __func__);
1236#endif
1237		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1238	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1239		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1240			printf("Sync msg send error retval %d\n", isc_retval);
1241		}
1242		if (!rcv_sync_msg) {
1243			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1244			        sizeof(msg_info), 1);
1245		}
1246#if 0
1247        	printf("CTL:Frontend Enable\n");
1248	} else {
1249		printf("%s: single mode, skipping frontend synchronization\n",
1250		        __func__);
1251#endif
1252	}
1253
1254	softc = control_softc;
1255
1256	STAILQ_FOREACH(port, &softc->port_list, links) {
1257		if (port_type & port->port_type)
1258		{
1259#if 0
1260			printf("port %d\n", port->targ_port);
1261#endif
1262			ctl_port_online(port);
1263		}
1264	}
1265
1266	return (0);
1267}
1268
1269int
1270ctl_port_disable(ctl_port_type port_type)
1271{
1272	struct ctl_softc *softc;
1273	struct ctl_port *port;
1274
1275	softc = control_softc;
1276
1277	STAILQ_FOREACH(port, &softc->port_list, links) {
1278		if (port_type & port->port_type)
1279			ctl_port_offline(port);
1280	}
1281
1282	return (0);
1283}
1284
1285/*
1286 * Returns 0 for success, 1 for failure.
1287 * Currently the only failure mode is if there aren't enough entries
1288 * allocated.  So, in case of a failure, look at num_entries_dropped,
1289 * reallocate and try again.
1290 */
1291int
1292ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1293	      int *num_entries_filled, int *num_entries_dropped,
1294	      ctl_port_type port_type, int no_virtual)
1295{
1296	struct ctl_softc *softc;
1297	struct ctl_port *port;
1298	int entries_dropped, entries_filled;
1299	int retval;
1300	int i;
1301
1302	softc = control_softc;
1303
1304	retval = 0;
1305	entries_filled = 0;
1306	entries_dropped = 0;
1307
1308	i = 0;
1309	mtx_lock(&softc->ctl_lock);
1310	STAILQ_FOREACH(port, &softc->port_list, links) {
1311		struct ctl_port_entry *entry;
1312
1313		if ((port->port_type & port_type) == 0)
1314			continue;
1315
1316		if ((no_virtual != 0)
1317		 && (port->virtual_port != 0))
1318			continue;
1319
1320		if (entries_filled >= num_entries_alloced) {
1321			entries_dropped++;
1322			continue;
1323		}
1324		entry = &entries[i];
1325
1326		entry->port_type = port->port_type;
1327		strlcpy(entry->port_name, port->port_name,
1328			sizeof(entry->port_name));
1329		entry->physical_port = port->physical_port;
1330		entry->virtual_port = port->virtual_port;
1331		entry->wwnn = port->wwnn;
1332		entry->wwpn = port->wwpn;
1333
1334		i++;
1335		entries_filled++;
1336	}
1337
1338	mtx_unlock(&softc->ctl_lock);
1339
1340	if (entries_dropped > 0)
1341		retval = 1;
1342
1343	*num_entries_dropped = entries_dropped;
1344	*num_entries_filled = entries_filled;
1345
1346	return (retval);
1347}
1348
1349static void
1350ctl_ioctl_online(void *arg)
1351{
1352	struct ctl_ioctl_info *ioctl_info;
1353
1354	ioctl_info = (struct ctl_ioctl_info *)arg;
1355
1356	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1357}
1358
1359static void
1360ctl_ioctl_offline(void *arg)
1361{
1362	struct ctl_ioctl_info *ioctl_info;
1363
1364	ioctl_info = (struct ctl_ioctl_info *)arg;
1365
1366	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1367}
1368
1369/*
1370 * Remove an initiator by port number and initiator ID.
1371 * Returns 0 for success, -1 for failure.
1372 */
1373int
1374ctl_remove_initiator(struct ctl_port *port, int iid)
1375{
1376	struct ctl_softc *softc = control_softc;
1377
1378	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1379
1380	if (iid > CTL_MAX_INIT_PER_PORT) {
1381		printf("%s: initiator ID %u > maximun %u!\n",
1382		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1383		return (-1);
1384	}
1385
1386	mtx_lock(&softc->ctl_lock);
1387	port->wwpn_iid[iid].in_use--;
1388	port->wwpn_iid[iid].last_use = time_uptime;
1389	mtx_unlock(&softc->ctl_lock);
1390
1391	return (0);
1392}
1393
1394/*
1395 * Add an initiator to the initiator map.
1396 * Returns iid for success, < 0 for failure.
1397 */
1398int
1399ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1400{
1401	struct ctl_softc *softc = control_softc;
1402	time_t best_time;
1403	int i, best;
1404
1405	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1406
1407	if (iid >= CTL_MAX_INIT_PER_PORT) {
1408		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1409		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1410		free(name, M_CTL);
1411		return (-1);
1412	}
1413
1414	mtx_lock(&softc->ctl_lock);
1415
1416	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1417		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1418			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1419				iid = i;
1420				break;
1421			}
1422			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1423			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1424				iid = i;
1425				break;
1426			}
1427		}
1428	}
1429
1430	if (iid < 0) {
1431		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1432			if (port->wwpn_iid[i].in_use == 0 &&
1433			    port->wwpn_iid[i].wwpn == 0 &&
1434			    port->wwpn_iid[i].name == NULL) {
1435				iid = i;
1436				break;
1437			}
1438		}
1439	}
1440
1441	if (iid < 0) {
1442		best = -1;
1443		best_time = INT32_MAX;
1444		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1445			if (port->wwpn_iid[i].in_use == 0) {
1446				if (port->wwpn_iid[i].last_use < best_time) {
1447					best = i;
1448					best_time = port->wwpn_iid[i].last_use;
1449				}
1450			}
1451		}
1452		iid = best;
1453	}
1454
1455	if (iid < 0) {
1456		mtx_unlock(&softc->ctl_lock);
1457		free(name, M_CTL);
1458		return (-2);
1459	}
1460
1461	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1462		/*
1463		 * This is not an error yet.
1464		 */
1465		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1466#if 0
1467			printf("%s: port %d iid %u WWPN %#jx arrived"
1468			    " again\n", __func__, port->targ_port,
1469			    iid, (uintmax_t)wwpn);
1470#endif
1471			goto take;
1472		}
1473		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1474		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1475#if 0
1476			printf("%s: port %d iid %u name '%s' arrived"
1477			    " again\n", __func__, port->targ_port,
1478			    iid, name);
1479#endif
1480			goto take;
1481		}
1482
1483		/*
1484		 * This is an error, but what do we do about it?  The
1485		 * driver is telling us we have a new WWPN for this
1486		 * initiator ID, so we pretty much need to use it.
1487		 */
1488		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1489		    " but WWPN %#jx '%s' is still at that address\n",
1490		    __func__, port->targ_port, iid, wwpn, name,
1491		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1492		    port->wwpn_iid[iid].name);
1493
1494		/*
1495		 * XXX KDM clear have_ca and ua_pending on each LUN for
1496		 * this initiator.
1497		 */
1498	}
1499take:
1500	free(port->wwpn_iid[iid].name, M_CTL);
1501	port->wwpn_iid[iid].name = name;
1502	port->wwpn_iid[iid].wwpn = wwpn;
1503	port->wwpn_iid[iid].in_use++;
1504	mtx_unlock(&softc->ctl_lock);
1505
1506	return (iid);
1507}
1508
1509static int
1510ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1511{
1512	int len;
1513
1514	switch (port->port_type) {
1515	case CTL_PORT_FC:
1516	{
1517		struct scsi_transportid_fcp *id =
1518		    (struct scsi_transportid_fcp *)buf;
1519		if (port->wwpn_iid[iid].wwpn == 0)
1520			return (0);
1521		memset(id, 0, sizeof(*id));
1522		id->format_protocol = SCSI_PROTO_FC;
1523		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1524		return (sizeof(*id));
1525	}
1526	case CTL_PORT_ISCSI:
1527	{
1528		struct scsi_transportid_iscsi_port *id =
1529		    (struct scsi_transportid_iscsi_port *)buf;
1530		if (port->wwpn_iid[iid].name == NULL)
1531			return (0);
1532		memset(id, 0, 256);
1533		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1534		    SCSI_PROTO_ISCSI;
1535		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1536		len = roundup2(min(len, 252), 4);
1537		scsi_ulto2b(len, id->additional_length);
1538		return (sizeof(*id) + len);
1539	}
1540	case CTL_PORT_SAS:
1541	{
1542		struct scsi_transportid_sas *id =
1543		    (struct scsi_transportid_sas *)buf;
1544		if (port->wwpn_iid[iid].wwpn == 0)
1545			return (0);
1546		memset(id, 0, sizeof(*id));
1547		id->format_protocol = SCSI_PROTO_SAS;
1548		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1549		return (sizeof(*id));
1550	}
1551	default:
1552	{
1553		struct scsi_transportid_spi *id =
1554		    (struct scsi_transportid_spi *)buf;
1555		memset(id, 0, sizeof(*id));
1556		id->format_protocol = SCSI_PROTO_SPI;
1557		scsi_ulto2b(iid, id->scsi_addr);
1558		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1559		return (sizeof(*id));
1560	}
1561	}
1562}
1563
1564static int
1565ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1566{
1567	return (0);
1568}
1569
1570static int
1571ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1572{
1573	return (0);
1574}
1575
1576/*
1577 * Data movement routine for the CTL ioctl frontend port.
1578 */
1579static int
1580ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1581{
1582	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1583	struct ctl_sg_entry ext_entry, kern_entry;
1584	int ext_sglen, ext_sg_entries, kern_sg_entries;
1585	int ext_sg_start, ext_offset;
1586	int len_to_copy, len_copied;
1587	int kern_watermark, ext_watermark;
1588	int ext_sglist_malloced;
1589	int i, j;
1590
1591	ext_sglist_malloced = 0;
1592	ext_sg_start = 0;
1593	ext_offset = 0;
1594
1595	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1596
1597	/*
1598	 * If this flag is set, fake the data transfer.
1599	 */
1600	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1601		ctsio->ext_data_filled = ctsio->ext_data_len;
1602		goto bailout;
1603	}
1604
1605	/*
1606	 * To simplify things here, if we have a single buffer, stick it in
1607	 * a S/G entry and just make it a single entry S/G list.
1608	 */
1609	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1610		int len_seen;
1611
1612		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1613
1614		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1615							   M_WAITOK);
1616		ext_sglist_malloced = 1;
1617		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1618				   ext_sglen) != 0) {
1619			ctl_set_internal_failure(ctsio,
1620						 /*sks_valid*/ 0,
1621						 /*retry_count*/ 0);
1622			goto bailout;
1623		}
1624		ext_sg_entries = ctsio->ext_sg_entries;
1625		len_seen = 0;
1626		for (i = 0; i < ext_sg_entries; i++) {
1627			if ((len_seen + ext_sglist[i].len) >=
1628			     ctsio->ext_data_filled) {
1629				ext_sg_start = i;
1630				ext_offset = ctsio->ext_data_filled - len_seen;
1631				break;
1632			}
1633			len_seen += ext_sglist[i].len;
1634		}
1635	} else {
1636		ext_sglist = &ext_entry;
1637		ext_sglist->addr = ctsio->ext_data_ptr;
1638		ext_sglist->len = ctsio->ext_data_len;
1639		ext_sg_entries = 1;
1640		ext_sg_start = 0;
1641		ext_offset = ctsio->ext_data_filled;
1642	}
1643
1644	if (ctsio->kern_sg_entries > 0) {
1645		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1646		kern_sg_entries = ctsio->kern_sg_entries;
1647	} else {
1648		kern_sglist = &kern_entry;
1649		kern_sglist->addr = ctsio->kern_data_ptr;
1650		kern_sglist->len = ctsio->kern_data_len;
1651		kern_sg_entries = 1;
1652	}
1653
1654
1655	kern_watermark = 0;
1656	ext_watermark = ext_offset;
1657	len_copied = 0;
1658	for (i = ext_sg_start, j = 0;
1659	     i < ext_sg_entries && j < kern_sg_entries;) {
1660		uint8_t *ext_ptr, *kern_ptr;
1661
1662		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1663				      kern_sglist[j].len - kern_watermark);
1664
1665		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1666		ext_ptr = ext_ptr + ext_watermark;
1667		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1668			/*
1669			 * XXX KDM fix this!
1670			 */
1671			panic("need to implement bus address support");
1672#if 0
1673			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1674#endif
1675		} else
1676			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1677		kern_ptr = kern_ptr + kern_watermark;
1678
1679		kern_watermark += len_to_copy;
1680		ext_watermark += len_to_copy;
1681
1682		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1683		     CTL_FLAG_DATA_IN) {
1684			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1685					 "bytes to user\n", len_to_copy));
1686			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1687					 "to %p\n", kern_ptr, ext_ptr));
1688			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1689				ctl_set_internal_failure(ctsio,
1690							 /*sks_valid*/ 0,
1691							 /*retry_count*/ 0);
1692				goto bailout;
1693			}
1694		} else {
1695			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1696					 "bytes from user\n", len_to_copy));
1697			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1698					 "to %p\n", ext_ptr, kern_ptr));
1699			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1700				ctl_set_internal_failure(ctsio,
1701							 /*sks_valid*/ 0,
1702							 /*retry_count*/0);
1703				goto bailout;
1704			}
1705		}
1706
1707		len_copied += len_to_copy;
1708
1709		if (ext_sglist[i].len == ext_watermark) {
1710			i++;
1711			ext_watermark = 0;
1712		}
1713
1714		if (kern_sglist[j].len == kern_watermark) {
1715			j++;
1716			kern_watermark = 0;
1717		}
1718	}
1719
1720	ctsio->ext_data_filled += len_copied;
1721
1722	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1723			 "kern_sg_entries: %d\n", ext_sg_entries,
1724			 kern_sg_entries));
1725	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1726			 "kern_data_len = %d\n", ctsio->ext_data_len,
1727			 ctsio->kern_data_len));
1728
1729
1730	/* XXX KDM set residual?? */
1731bailout:
1732
1733	if (ext_sglist_malloced != 0)
1734		free(ext_sglist, M_CTL);
1735
1736	return (CTL_RETVAL_COMPLETE);
1737}
1738
1739/*
1740 * Serialize a command that went down the "wrong" side, and so was sent to
1741 * this controller for execution.  The logic is a little different than the
1742 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1743 * sent back to the other side, but in the success case, we execute the
1744 * command on this side (XFER mode) or tell the other side to execute it
1745 * (SER_ONLY mode).
1746 */
1747static int
1748ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1749{
1750	struct ctl_softc *ctl_softc;
1751	union ctl_ha_msg msg_info;
1752	struct ctl_lun *lun;
1753	int retval = 0;
1754	uint32_t targ_lun;
1755
1756	ctl_softc = control_softc;
1757
1758	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1759	lun = ctl_softc->ctl_luns[targ_lun];
1760	if (lun==NULL)
1761	{
1762		/*
1763		 * Why isn't LUN defined? The other side wouldn't
1764		 * send a cmd if the LUN is undefined.
1765		 */
1766		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1767
1768		/* "Logical unit not supported" */
1769		ctl_set_sense_data(&msg_info.scsi.sense_data,
1770				   lun,
1771				   /*sense_format*/SSD_TYPE_NONE,
1772				   /*current_error*/ 1,
1773				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1774				   /*asc*/ 0x25,
1775				   /*ascq*/ 0x00,
1776				   SSD_ELEM_NONE);
1777
1778		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1779		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1780		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1781		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1782		msg_info.hdr.serializing_sc = NULL;
1783		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1784	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1785				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1786		}
1787		return(1);
1788
1789	}
1790
1791	mtx_lock(&lun->lun_lock);
1792    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1793
1794	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1795		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1796		 ooa_links))) {
1797	case CTL_ACTION_BLOCK:
1798		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1799		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1800				  blocked_links);
1801		break;
1802	case CTL_ACTION_PASS:
1803	case CTL_ACTION_SKIP:
1804		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1805			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1806			ctl_enqueue_rtr((union ctl_io *)ctsio);
1807		} else {
1808
1809			/* send msg back to other side */
1810			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1811			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1812			msg_info.hdr.msg_type = CTL_MSG_R2R;
1813#if 0
1814			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1815#endif
1816		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1817			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1818			}
1819		}
1820		break;
1821	case CTL_ACTION_OVERLAP:
1822		/* OVERLAPPED COMMANDS ATTEMPTED */
1823		ctl_set_sense_data(&msg_info.scsi.sense_data,
1824				   lun,
1825				   /*sense_format*/SSD_TYPE_NONE,
1826				   /*current_error*/ 1,
1827				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1828				   /*asc*/ 0x4E,
1829				   /*ascq*/ 0x00,
1830				   SSD_ELEM_NONE);
1831
1832		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1833		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1834		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1835		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1836		msg_info.hdr.serializing_sc = NULL;
1837		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1838#if 0
1839		printf("BAD JUJU:Major Bummer Overlap\n");
1840#endif
1841		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1842		retval = 1;
1843		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1844		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1845		}
1846		break;
1847	case CTL_ACTION_OVERLAP_TAG:
1848		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1849		ctl_set_sense_data(&msg_info.scsi.sense_data,
1850				   lun,
1851				   /*sense_format*/SSD_TYPE_NONE,
1852				   /*current_error*/ 1,
1853				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854				   /*asc*/ 0x4D,
1855				   /*ascq*/ ctsio->tag_num & 0xff,
1856				   SSD_ELEM_NONE);
1857
1858		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862		msg_info.hdr.serializing_sc = NULL;
1863		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864#if 0
1865		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1866#endif
1867		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868		retval = 1;
1869		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871		}
1872		break;
1873	case CTL_ACTION_ERROR:
1874	default:
1875		/* "Internal target failure" */
1876		ctl_set_sense_data(&msg_info.scsi.sense_data,
1877				   lun,
1878				   /*sense_format*/SSD_TYPE_NONE,
1879				   /*current_error*/ 1,
1880				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1881				   /*asc*/ 0x44,
1882				   /*ascq*/ 0x00,
1883				   SSD_ELEM_NONE);
1884
1885		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1886		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1887		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1888		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1889		msg_info.hdr.serializing_sc = NULL;
1890		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1891#if 0
1892		printf("BAD JUJU:Major Bummer HW Error\n");
1893#endif
1894		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1895		retval = 1;
1896		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1897		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1898		}
1899		break;
1900	}
1901	mtx_unlock(&lun->lun_lock);
1902	return (retval);
1903}
1904
1905static int
1906ctl_ioctl_submit_wait(union ctl_io *io)
1907{
1908	struct ctl_fe_ioctl_params params;
1909	ctl_fe_ioctl_state last_state;
1910	int done, retval;
1911
1912	retval = 0;
1913
1914	bzero(&params, sizeof(params));
1915
1916	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1917	cv_init(&params.sem, "ctlioccv");
1918	params.state = CTL_IOCTL_INPROG;
1919	last_state = params.state;
1920
1921	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1922
1923	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1924
1925	/* This shouldn't happen */
1926	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1927		return (retval);
1928
1929	done = 0;
1930
1931	do {
1932		mtx_lock(&params.ioctl_mtx);
1933		/*
1934		 * Check the state here, and don't sleep if the state has
1935		 * already changed (i.e. wakeup has already occured, but we
1936		 * weren't waiting yet).
1937		 */
1938		if (params.state == last_state) {
1939			/* XXX KDM cv_wait_sig instead? */
1940			cv_wait(&params.sem, &params.ioctl_mtx);
1941		}
1942		last_state = params.state;
1943
1944		switch (params.state) {
1945		case CTL_IOCTL_INPROG:
1946			/* Why did we wake up? */
1947			/* XXX KDM error here? */
1948			mtx_unlock(&params.ioctl_mtx);
1949			break;
1950		case CTL_IOCTL_DATAMOVE:
1951			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1952
1953			/*
1954			 * change last_state back to INPROG to avoid
1955			 * deadlock on subsequent data moves.
1956			 */
1957			params.state = last_state = CTL_IOCTL_INPROG;
1958
1959			mtx_unlock(&params.ioctl_mtx);
1960			ctl_ioctl_do_datamove(&io->scsiio);
1961			/*
1962			 * Note that in some cases, most notably writes,
1963			 * this will queue the I/O and call us back later.
1964			 * In other cases, generally reads, this routine
1965			 * will immediately call back and wake us up,
1966			 * probably using our own context.
1967			 */
1968			io->scsiio.be_move_done(io);
1969			break;
1970		case CTL_IOCTL_DONE:
1971			mtx_unlock(&params.ioctl_mtx);
1972			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1973			done = 1;
1974			break;
1975		default:
1976			mtx_unlock(&params.ioctl_mtx);
1977			/* XXX KDM error here? */
1978			break;
1979		}
1980	} while (done == 0);
1981
1982	mtx_destroy(&params.ioctl_mtx);
1983	cv_destroy(&params.sem);
1984
1985	return (CTL_RETVAL_COMPLETE);
1986}
1987
1988static void
1989ctl_ioctl_datamove(union ctl_io *io)
1990{
1991	struct ctl_fe_ioctl_params *params;
1992
1993	params = (struct ctl_fe_ioctl_params *)
1994		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1995
1996	mtx_lock(&params->ioctl_mtx);
1997	params->state = CTL_IOCTL_DATAMOVE;
1998	cv_broadcast(&params->sem);
1999	mtx_unlock(&params->ioctl_mtx);
2000}
2001
2002static void
2003ctl_ioctl_done(union ctl_io *io)
2004{
2005	struct ctl_fe_ioctl_params *params;
2006
2007	params = (struct ctl_fe_ioctl_params *)
2008		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2009
2010	mtx_lock(&params->ioctl_mtx);
2011	params->state = CTL_IOCTL_DONE;
2012	cv_broadcast(&params->sem);
2013	mtx_unlock(&params->ioctl_mtx);
2014}
2015
2016static void
2017ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2018{
2019	struct ctl_fe_ioctl_startstop_info *sd_info;
2020
2021	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2022
2023	sd_info->hs_info.status = metatask->status;
2024	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2025	sd_info->hs_info.luns_complete =
2026		metatask->taskinfo.startstop.luns_complete;
2027	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2028
2029	cv_broadcast(&sd_info->sem);
2030}
2031
2032static void
2033ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2034{
2035	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2036
2037	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2038
2039	mtx_lock(fe_bbr_info->lock);
2040	fe_bbr_info->bbr_info->status = metatask->status;
2041	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2042	fe_bbr_info->wakeup_done = 1;
2043	mtx_unlock(fe_bbr_info->lock);
2044
2045	cv_broadcast(&fe_bbr_info->sem);
2046}
2047
2048/*
2049 * Returns 0 for success, errno for failure.
2050 */
2051static int
2052ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2053		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2054{
2055	union ctl_io *io;
2056	int retval;
2057
2058	retval = 0;
2059
2060	mtx_lock(&lun->lun_lock);
2061	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2062	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2063	     ooa_links)) {
2064		struct ctl_ooa_entry *entry;
2065
2066		/*
2067		 * If we've got more than we can fit, just count the
2068		 * remaining entries.
2069		 */
2070		if (*cur_fill_num >= ooa_hdr->alloc_num)
2071			continue;
2072
2073		entry = &kern_entries[*cur_fill_num];
2074
2075		entry->tag_num = io->scsiio.tag_num;
2076		entry->lun_num = lun->lun;
2077#ifdef CTL_TIME_IO
2078		entry->start_bt = io->io_hdr.start_bt;
2079#endif
2080		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2081		entry->cdb_len = io->scsiio.cdb_len;
2082		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2083			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2084
2085		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2086			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2087
2088		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2089			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2090
2091		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2092			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2093
2094		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2095			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2096	}
2097	mtx_unlock(&lun->lun_lock);
2098
2099	return (retval);
2100}
2101
2102static void *
2103ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2104		 size_t error_str_len)
2105{
2106	void *kptr;
2107
2108	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2109
2110	if (copyin(user_addr, kptr, len) != 0) {
2111		snprintf(error_str, error_str_len, "Error copying %d bytes "
2112			 "from user address %p to kernel address %p", len,
2113			 user_addr, kptr);
2114		free(kptr, M_CTL);
2115		return (NULL);
2116	}
2117
2118	return (kptr);
2119}
2120
2121static void
2122ctl_free_args(int num_args, struct ctl_be_arg *args)
2123{
2124	int i;
2125
2126	if (args == NULL)
2127		return;
2128
2129	for (i = 0; i < num_args; i++) {
2130		free(args[i].kname, M_CTL);
2131		free(args[i].kvalue, M_CTL);
2132	}
2133
2134	free(args, M_CTL);
2135}
2136
2137static struct ctl_be_arg *
2138ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2139		char *error_str, size_t error_str_len)
2140{
2141	struct ctl_be_arg *args;
2142	int i;
2143
2144	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2145				error_str, error_str_len);
2146
2147	if (args == NULL)
2148		goto bailout;
2149
2150	for (i = 0; i < num_args; i++) {
2151		args[i].kname = NULL;
2152		args[i].kvalue = NULL;
2153	}
2154
2155	for (i = 0; i < num_args; i++) {
2156		uint8_t *tmpptr;
2157
2158		args[i].kname = ctl_copyin_alloc(args[i].name,
2159			args[i].namelen, error_str, error_str_len);
2160		if (args[i].kname == NULL)
2161			goto bailout;
2162
2163		if (args[i].kname[args[i].namelen - 1] != '\0') {
2164			snprintf(error_str, error_str_len, "Argument %d "
2165				 "name is not NUL-terminated", i);
2166			goto bailout;
2167		}
2168
2169		if (args[i].flags & CTL_BEARG_RD) {
2170			tmpptr = ctl_copyin_alloc(args[i].value,
2171				args[i].vallen, error_str, error_str_len);
2172			if (tmpptr == NULL)
2173				goto bailout;
2174			if ((args[i].flags & CTL_BEARG_ASCII)
2175			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2176				snprintf(error_str, error_str_len, "Argument "
2177				    "%d value is not NUL-terminated", i);
2178				goto bailout;
2179			}
2180			args[i].kvalue = tmpptr;
2181		} else {
2182			args[i].kvalue = malloc(args[i].vallen,
2183			    M_CTL, M_WAITOK | M_ZERO);
2184		}
2185	}
2186
2187	return (args);
2188bailout:
2189
2190	ctl_free_args(num_args, args);
2191
2192	return (NULL);
2193}
2194
2195static void
2196ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2197{
2198	int i;
2199
2200	for (i = 0; i < num_args; i++) {
2201		if (args[i].flags & CTL_BEARG_WR)
2202			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2203	}
2204}
2205
2206/*
2207 * Escape characters that are illegal or not recommended in XML.
2208 */
2209int
2210ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2211{
2212	int retval;
2213
2214	retval = 0;
2215
2216	for (; *str; str++) {
2217		switch (*str) {
2218		case '&':
2219			retval = sbuf_printf(sb, "&amp;");
2220			break;
2221		case '>':
2222			retval = sbuf_printf(sb, "&gt;");
2223			break;
2224		case '<':
2225			retval = sbuf_printf(sb, "&lt;");
2226			break;
2227		default:
2228			retval = sbuf_putc(sb, *str);
2229			break;
2230		}
2231
2232		if (retval != 0)
2233			break;
2234
2235	}
2236
2237	return (retval);
2238}
2239
2240static void
2241ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2242{
2243	struct scsi_vpd_id_descriptor *desc;
2244	int i;
2245
2246	if (id == NULL || id->len < 4)
2247		return;
2248	desc = (struct scsi_vpd_id_descriptor *)id->data;
2249	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2250	case SVPD_ID_TYPE_T10:
2251		sbuf_printf(sb, "t10.");
2252		break;
2253	case SVPD_ID_TYPE_EUI64:
2254		sbuf_printf(sb, "eui.");
2255		break;
2256	case SVPD_ID_TYPE_NAA:
2257		sbuf_printf(sb, "naa.");
2258		break;
2259	case SVPD_ID_TYPE_SCSI_NAME:
2260		break;
2261	}
2262	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2263	case SVPD_ID_CODESET_BINARY:
2264		for (i = 0; i < desc->length; i++)
2265			sbuf_printf(sb, "%02x", desc->identifier[i]);
2266		break;
2267	case SVPD_ID_CODESET_ASCII:
2268		sbuf_printf(sb, "%.*s", (int)desc->length,
2269		    (char *)desc->identifier);
2270		break;
2271	case SVPD_ID_CODESET_UTF8:
2272		sbuf_printf(sb, "%s", (char *)desc->identifier);
2273		break;
2274	}
2275}
2276
2277static int
2278ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2279	  struct thread *td)
2280{
2281	struct ctl_softc *softc;
2282	int retval;
2283
2284	softc = control_softc;
2285
2286	retval = 0;
2287
2288	switch (cmd) {
2289	case CTL_IO: {
2290		union ctl_io *io;
2291		void *pool_tmp;
2292
2293		/*
2294		 * If we haven't been "enabled", don't allow any SCSI I/O
2295		 * to this FETD.
2296		 */
2297		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2298			retval = EPERM;
2299			break;
2300		}
2301
2302		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2303		if (io == NULL) {
2304			printf("ctl_ioctl: can't allocate ctl_io!\n");
2305			retval = ENOSPC;
2306			break;
2307		}
2308
2309		/*
2310		 * Need to save the pool reference so it doesn't get
2311		 * spammed by the user's ctl_io.
2312		 */
2313		pool_tmp = io->io_hdr.pool;
2314
2315		memcpy(io, (void *)addr, sizeof(*io));
2316
2317		io->io_hdr.pool = pool_tmp;
2318		/*
2319		 * No status yet, so make sure the status is set properly.
2320		 */
2321		io->io_hdr.status = CTL_STATUS_NONE;
2322
2323		/*
2324		 * The user sets the initiator ID, target and LUN IDs.
2325		 */
2326		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2327		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2328		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2329		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2330			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2331
2332		retval = ctl_ioctl_submit_wait(io);
2333
2334		if (retval != 0) {
2335			ctl_free_io(io);
2336			break;
2337		}
2338
2339		memcpy((void *)addr, io, sizeof(*io));
2340
2341		/* return this to our pool */
2342		ctl_free_io(io);
2343
2344		break;
2345	}
2346	case CTL_ENABLE_PORT:
2347	case CTL_DISABLE_PORT:
2348	case CTL_SET_PORT_WWNS: {
2349		struct ctl_port *port;
2350		struct ctl_port_entry *entry;
2351
2352		entry = (struct ctl_port_entry *)addr;
2353
2354		mtx_lock(&softc->ctl_lock);
2355		STAILQ_FOREACH(port, &softc->port_list, links) {
2356			int action, done;
2357
2358			action = 0;
2359			done = 0;
2360
2361			if ((entry->port_type == CTL_PORT_NONE)
2362			 && (entry->targ_port == port->targ_port)) {
2363				/*
2364				 * If the user only wants to enable or
2365				 * disable or set WWNs on a specific port,
2366				 * do the operation and we're done.
2367				 */
2368				action = 1;
2369				done = 1;
2370			} else if (entry->port_type & port->port_type) {
2371				/*
2372				 * Compare the user's type mask with the
2373				 * particular frontend type to see if we
2374				 * have a match.
2375				 */
2376				action = 1;
2377				done = 0;
2378
2379				/*
2380				 * Make sure the user isn't trying to set
2381				 * WWNs on multiple ports at the same time.
2382				 */
2383				if (cmd == CTL_SET_PORT_WWNS) {
2384					printf("%s: Can't set WWNs on "
2385					       "multiple ports\n", __func__);
2386					retval = EINVAL;
2387					break;
2388				}
2389			}
2390			if (action != 0) {
2391				/*
2392				 * XXX KDM we have to drop the lock here,
2393				 * because the online/offline operations
2394				 * can potentially block.  We need to
2395				 * reference count the frontends so they
2396				 * can't go away,
2397				 */
2398				mtx_unlock(&softc->ctl_lock);
2399
2400				if (cmd == CTL_ENABLE_PORT) {
2401					struct ctl_lun *lun;
2402
2403					STAILQ_FOREACH(lun, &softc->lun_list,
2404						       links) {
2405						port->lun_enable(port->targ_lun_arg,
2406						    lun->target,
2407						    lun->lun);
2408					}
2409
2410					ctl_port_online(port);
2411				} else if (cmd == CTL_DISABLE_PORT) {
2412					struct ctl_lun *lun;
2413
2414					ctl_port_offline(port);
2415
2416					STAILQ_FOREACH(lun, &softc->lun_list,
2417						       links) {
2418						port->lun_disable(
2419						    port->targ_lun_arg,
2420						    lun->target,
2421						    lun->lun);
2422					}
2423				}
2424
2425				mtx_lock(&softc->ctl_lock);
2426
2427				if (cmd == CTL_SET_PORT_WWNS)
2428					ctl_port_set_wwns(port,
2429					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2430					    1 : 0, entry->wwnn,
2431					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2432					    1 : 0, entry->wwpn);
2433			}
2434			if (done != 0)
2435				break;
2436		}
2437		mtx_unlock(&softc->ctl_lock);
2438		break;
2439	}
2440	case CTL_GET_PORT_LIST: {
2441		struct ctl_port *port;
2442		struct ctl_port_list *list;
2443		int i;
2444
2445		list = (struct ctl_port_list *)addr;
2446
2447		if (list->alloc_len != (list->alloc_num *
2448		    sizeof(struct ctl_port_entry))) {
2449			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2450			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2451			       "%zu\n", __func__, list->alloc_len,
2452			       list->alloc_num, sizeof(struct ctl_port_entry));
2453			retval = EINVAL;
2454			break;
2455		}
2456		list->fill_len = 0;
2457		list->fill_num = 0;
2458		list->dropped_num = 0;
2459		i = 0;
2460		mtx_lock(&softc->ctl_lock);
2461		STAILQ_FOREACH(port, &softc->port_list, links) {
2462			struct ctl_port_entry entry, *list_entry;
2463
2464			if (list->fill_num >= list->alloc_num) {
2465				list->dropped_num++;
2466				continue;
2467			}
2468
2469			entry.port_type = port->port_type;
2470			strlcpy(entry.port_name, port->port_name,
2471				sizeof(entry.port_name));
2472			entry.targ_port = port->targ_port;
2473			entry.physical_port = port->physical_port;
2474			entry.virtual_port = port->virtual_port;
2475			entry.wwnn = port->wwnn;
2476			entry.wwpn = port->wwpn;
2477			if (port->status & CTL_PORT_STATUS_ONLINE)
2478				entry.online = 1;
2479			else
2480				entry.online = 0;
2481
2482			list_entry = &list->entries[i];
2483
2484			retval = copyout(&entry, list_entry, sizeof(entry));
2485			if (retval != 0) {
2486				printf("%s: CTL_GET_PORT_LIST: copyout "
2487				       "returned %d\n", __func__, retval);
2488				break;
2489			}
2490			i++;
2491			list->fill_num++;
2492			list->fill_len += sizeof(entry);
2493		}
2494		mtx_unlock(&softc->ctl_lock);
2495
2496		/*
2497		 * If this is non-zero, we had a copyout fault, so there's
2498		 * probably no point in attempting to set the status inside
2499		 * the structure.
2500		 */
2501		if (retval != 0)
2502			break;
2503
2504		if (list->dropped_num > 0)
2505			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2506		else
2507			list->status = CTL_PORT_LIST_OK;
2508		break;
2509	}
2510	case CTL_DUMP_OOA: {
2511		struct ctl_lun *lun;
2512		union ctl_io *io;
2513		char printbuf[128];
2514		struct sbuf sb;
2515
2516		mtx_lock(&softc->ctl_lock);
2517		printf("Dumping OOA queues:\n");
2518		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2519			mtx_lock(&lun->lun_lock);
2520			for (io = (union ctl_io *)TAILQ_FIRST(
2521			     &lun->ooa_queue); io != NULL;
2522			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2523			     ooa_links)) {
2524				sbuf_new(&sb, printbuf, sizeof(printbuf),
2525					 SBUF_FIXEDLEN);
2526				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2527					    (intmax_t)lun->lun,
2528					    io->scsiio.tag_num,
2529					    (io->io_hdr.flags &
2530					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2531					    (io->io_hdr.flags &
2532					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2533					    (io->io_hdr.flags &
2534					    CTL_FLAG_ABORT) ? " ABORT" : "",
2535			                    (io->io_hdr.flags &
2536		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2537				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2538				sbuf_finish(&sb);
2539				printf("%s\n", sbuf_data(&sb));
2540			}
2541			mtx_unlock(&lun->lun_lock);
2542		}
2543		printf("OOA queues dump done\n");
2544		mtx_unlock(&softc->ctl_lock);
2545		break;
2546	}
2547	case CTL_GET_OOA: {
2548		struct ctl_lun *lun;
2549		struct ctl_ooa *ooa_hdr;
2550		struct ctl_ooa_entry *entries;
2551		uint32_t cur_fill_num;
2552
2553		ooa_hdr = (struct ctl_ooa *)addr;
2554
2555		if ((ooa_hdr->alloc_len == 0)
2556		 || (ooa_hdr->alloc_num == 0)) {
2557			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2558			       "must be non-zero\n", __func__,
2559			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2560			retval = EINVAL;
2561			break;
2562		}
2563
2564		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2565		    sizeof(struct ctl_ooa_entry))) {
2566			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2567			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2568			       __func__, ooa_hdr->alloc_len,
2569			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2570			retval = EINVAL;
2571			break;
2572		}
2573
2574		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2575		if (entries == NULL) {
2576			printf("%s: could not allocate %d bytes for OOA "
2577			       "dump\n", __func__, ooa_hdr->alloc_len);
2578			retval = ENOMEM;
2579			break;
2580		}
2581
2582		mtx_lock(&softc->ctl_lock);
2583		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2584		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2585		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2586			mtx_unlock(&softc->ctl_lock);
2587			free(entries, M_CTL);
2588			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2589			       __func__, (uintmax_t)ooa_hdr->lun_num);
2590			retval = EINVAL;
2591			break;
2592		}
2593
2594		cur_fill_num = 0;
2595
2596		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2597			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2598				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2599					ooa_hdr, entries);
2600				if (retval != 0)
2601					break;
2602			}
2603			if (retval != 0) {
2604				mtx_unlock(&softc->ctl_lock);
2605				free(entries, M_CTL);
2606				break;
2607			}
2608		} else {
2609			lun = softc->ctl_luns[ooa_hdr->lun_num];
2610
2611			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2612						    entries);
2613		}
2614		mtx_unlock(&softc->ctl_lock);
2615
2616		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2617		ooa_hdr->fill_len = ooa_hdr->fill_num *
2618			sizeof(struct ctl_ooa_entry);
2619		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2620		if (retval != 0) {
2621			printf("%s: error copying out %d bytes for OOA dump\n",
2622			       __func__, ooa_hdr->fill_len);
2623		}
2624
2625		getbintime(&ooa_hdr->cur_bt);
2626
2627		if (cur_fill_num > ooa_hdr->alloc_num) {
2628			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2629			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2630		} else {
2631			ooa_hdr->dropped_num = 0;
2632			ooa_hdr->status = CTL_OOA_OK;
2633		}
2634
2635		free(entries, M_CTL);
2636		break;
2637	}
2638	case CTL_CHECK_OOA: {
2639		union ctl_io *io;
2640		struct ctl_lun *lun;
2641		struct ctl_ooa_info *ooa_info;
2642
2643
2644		ooa_info = (struct ctl_ooa_info *)addr;
2645
2646		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2647			ooa_info->status = CTL_OOA_INVALID_LUN;
2648			break;
2649		}
2650		mtx_lock(&softc->ctl_lock);
2651		lun = softc->ctl_luns[ooa_info->lun_id];
2652		if (lun == NULL) {
2653			mtx_unlock(&softc->ctl_lock);
2654			ooa_info->status = CTL_OOA_INVALID_LUN;
2655			break;
2656		}
2657		mtx_lock(&lun->lun_lock);
2658		mtx_unlock(&softc->ctl_lock);
2659		ooa_info->num_entries = 0;
2660		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2661		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2662		     &io->io_hdr, ooa_links)) {
2663			ooa_info->num_entries++;
2664		}
2665		mtx_unlock(&lun->lun_lock);
2666
2667		ooa_info->status = CTL_OOA_SUCCESS;
2668
2669		break;
2670	}
2671	case CTL_HARD_START:
2672	case CTL_HARD_STOP: {
2673		struct ctl_fe_ioctl_startstop_info ss_info;
2674		struct cfi_metatask *metatask;
2675		struct mtx hs_mtx;
2676
2677		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2678
2679		cv_init(&ss_info.sem, "hard start/stop cv" );
2680
2681		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2682		if (metatask == NULL) {
2683			retval = ENOMEM;
2684			mtx_destroy(&hs_mtx);
2685			break;
2686		}
2687
2688		if (cmd == CTL_HARD_START)
2689			metatask->tasktype = CFI_TASK_STARTUP;
2690		else
2691			metatask->tasktype = CFI_TASK_SHUTDOWN;
2692
2693		metatask->callback = ctl_ioctl_hard_startstop_callback;
2694		metatask->callback_arg = &ss_info;
2695
2696		cfi_action(metatask);
2697
2698		/* Wait for the callback */
2699		mtx_lock(&hs_mtx);
2700		cv_wait_sig(&ss_info.sem, &hs_mtx);
2701		mtx_unlock(&hs_mtx);
2702
2703		/*
2704		 * All information has been copied from the metatask by the
2705		 * time cv_broadcast() is called, so we free the metatask here.
2706		 */
2707		cfi_free_metatask(metatask);
2708
2709		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2710
2711		mtx_destroy(&hs_mtx);
2712		break;
2713	}
2714	case CTL_BBRREAD: {
2715		struct ctl_bbrread_info *bbr_info;
2716		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2717		struct mtx bbr_mtx;
2718		struct cfi_metatask *metatask;
2719
2720		bbr_info = (struct ctl_bbrread_info *)addr;
2721
2722		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2723
2724		bzero(&bbr_mtx, sizeof(bbr_mtx));
2725		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2726
2727		fe_bbr_info.bbr_info = bbr_info;
2728		fe_bbr_info.lock = &bbr_mtx;
2729
2730		cv_init(&fe_bbr_info.sem, "BBR read cv");
2731		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2732
2733		if (metatask == NULL) {
2734			mtx_destroy(&bbr_mtx);
2735			cv_destroy(&fe_bbr_info.sem);
2736			retval = ENOMEM;
2737			break;
2738		}
2739		metatask->tasktype = CFI_TASK_BBRREAD;
2740		metatask->callback = ctl_ioctl_bbrread_callback;
2741		metatask->callback_arg = &fe_bbr_info;
2742		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2743		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2744		metatask->taskinfo.bbrread.len = bbr_info->len;
2745
2746		cfi_action(metatask);
2747
2748		mtx_lock(&bbr_mtx);
2749		while (fe_bbr_info.wakeup_done == 0)
2750			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2751		mtx_unlock(&bbr_mtx);
2752
2753		bbr_info->status = metatask->status;
2754		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2755		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2756		memcpy(&bbr_info->sense_data,
2757		       &metatask->taskinfo.bbrread.sense_data,
2758		       ctl_min(sizeof(bbr_info->sense_data),
2759			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2760
2761		cfi_free_metatask(metatask);
2762
2763		mtx_destroy(&bbr_mtx);
2764		cv_destroy(&fe_bbr_info.sem);
2765
2766		break;
2767	}
2768	case CTL_DELAY_IO: {
2769		struct ctl_io_delay_info *delay_info;
2770#ifdef CTL_IO_DELAY
2771		struct ctl_lun *lun;
2772#endif /* CTL_IO_DELAY */
2773
2774		delay_info = (struct ctl_io_delay_info *)addr;
2775
2776#ifdef CTL_IO_DELAY
2777		mtx_lock(&softc->ctl_lock);
2778
2779		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2780		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2781			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2782		} else {
2783			lun = softc->ctl_luns[delay_info->lun_id];
2784			mtx_lock(&lun->lun_lock);
2785
2786			delay_info->status = CTL_DELAY_STATUS_OK;
2787
2788			switch (delay_info->delay_type) {
2789			case CTL_DELAY_TYPE_CONT:
2790				break;
2791			case CTL_DELAY_TYPE_ONESHOT:
2792				break;
2793			default:
2794				delay_info->status =
2795					CTL_DELAY_STATUS_INVALID_TYPE;
2796				break;
2797			}
2798
2799			switch (delay_info->delay_loc) {
2800			case CTL_DELAY_LOC_DATAMOVE:
2801				lun->delay_info.datamove_type =
2802					delay_info->delay_type;
2803				lun->delay_info.datamove_delay =
2804					delay_info->delay_secs;
2805				break;
2806			case CTL_DELAY_LOC_DONE:
2807				lun->delay_info.done_type =
2808					delay_info->delay_type;
2809				lun->delay_info.done_delay =
2810					delay_info->delay_secs;
2811				break;
2812			default:
2813				delay_info->status =
2814					CTL_DELAY_STATUS_INVALID_LOC;
2815				break;
2816			}
2817			mtx_unlock(&lun->lun_lock);
2818		}
2819
2820		mtx_unlock(&softc->ctl_lock);
2821#else
2822		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2823#endif /* CTL_IO_DELAY */
2824		break;
2825	}
2826	case CTL_REALSYNC_SET: {
2827		int *syncstate;
2828
2829		syncstate = (int *)addr;
2830
2831		mtx_lock(&softc->ctl_lock);
2832		switch (*syncstate) {
2833		case 0:
2834			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2835			break;
2836		case 1:
2837			softc->flags |= CTL_FLAG_REAL_SYNC;
2838			break;
2839		default:
2840			retval = EINVAL;
2841			break;
2842		}
2843		mtx_unlock(&softc->ctl_lock);
2844		break;
2845	}
2846	case CTL_REALSYNC_GET: {
2847		int *syncstate;
2848
2849		syncstate = (int*)addr;
2850
2851		mtx_lock(&softc->ctl_lock);
2852		if (softc->flags & CTL_FLAG_REAL_SYNC)
2853			*syncstate = 1;
2854		else
2855			*syncstate = 0;
2856		mtx_unlock(&softc->ctl_lock);
2857
2858		break;
2859	}
2860	case CTL_SETSYNC:
2861	case CTL_GETSYNC: {
2862		struct ctl_sync_info *sync_info;
2863		struct ctl_lun *lun;
2864
2865		sync_info = (struct ctl_sync_info *)addr;
2866
2867		mtx_lock(&softc->ctl_lock);
2868		lun = softc->ctl_luns[sync_info->lun_id];
2869		if (lun == NULL) {
2870			mtx_unlock(&softc->ctl_lock);
2871			sync_info->status = CTL_GS_SYNC_NO_LUN;
2872		}
2873		/*
2874		 * Get or set the sync interval.  We're not bounds checking
2875		 * in the set case, hopefully the user won't do something
2876		 * silly.
2877		 */
2878		mtx_lock(&lun->lun_lock);
2879		mtx_unlock(&softc->ctl_lock);
2880		if (cmd == CTL_GETSYNC)
2881			sync_info->sync_interval = lun->sync_interval;
2882		else
2883			lun->sync_interval = sync_info->sync_interval;
2884		mtx_unlock(&lun->lun_lock);
2885
2886		sync_info->status = CTL_GS_SYNC_OK;
2887
2888		break;
2889	}
2890	case CTL_GETSTATS: {
2891		struct ctl_stats *stats;
2892		struct ctl_lun *lun;
2893		int i;
2894
2895		stats = (struct ctl_stats *)addr;
2896
2897		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2898		     stats->alloc_len) {
2899			stats->status = CTL_SS_NEED_MORE_SPACE;
2900			stats->num_luns = softc->num_luns;
2901			break;
2902		}
2903		/*
2904		 * XXX KDM no locking here.  If the LUN list changes,
2905		 * things can blow up.
2906		 */
2907		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2908		     i++, lun = STAILQ_NEXT(lun, links)) {
2909			retval = copyout(&lun->stats, &stats->lun_stats[i],
2910					 sizeof(lun->stats));
2911			if (retval != 0)
2912				break;
2913		}
2914		stats->num_luns = softc->num_luns;
2915		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2916				 softc->num_luns;
2917		stats->status = CTL_SS_OK;
2918#ifdef CTL_TIME_IO
2919		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2920#else
2921		stats->flags = CTL_STATS_FLAG_NONE;
2922#endif
2923		getnanouptime(&stats->timestamp);
2924		break;
2925	}
2926	case CTL_ERROR_INJECT: {
2927		struct ctl_error_desc *err_desc, *new_err_desc;
2928		struct ctl_lun *lun;
2929
2930		err_desc = (struct ctl_error_desc *)addr;
2931
2932		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2933				      M_WAITOK | M_ZERO);
2934		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2935
2936		mtx_lock(&softc->ctl_lock);
2937		lun = softc->ctl_luns[err_desc->lun_id];
2938		if (lun == NULL) {
2939			mtx_unlock(&softc->ctl_lock);
2940			free(new_err_desc, M_CTL);
2941			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2942			       __func__, (uintmax_t)err_desc->lun_id);
2943			retval = EINVAL;
2944			break;
2945		}
2946		mtx_lock(&lun->lun_lock);
2947		mtx_unlock(&softc->ctl_lock);
2948
2949		/*
2950		 * We could do some checking here to verify the validity
2951		 * of the request, but given the complexity of error
2952		 * injection requests, the checking logic would be fairly
2953		 * complex.
2954		 *
2955		 * For now, if the request is invalid, it just won't get
2956		 * executed and might get deleted.
2957		 */
2958		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2959
2960		/*
2961		 * XXX KDM check to make sure the serial number is unique,
2962		 * in case we somehow manage to wrap.  That shouldn't
2963		 * happen for a very long time, but it's the right thing to
2964		 * do.
2965		 */
2966		new_err_desc->serial = lun->error_serial;
2967		err_desc->serial = lun->error_serial;
2968		lun->error_serial++;
2969
2970		mtx_unlock(&lun->lun_lock);
2971		break;
2972	}
2973	case CTL_ERROR_INJECT_DELETE: {
2974		struct ctl_error_desc *delete_desc, *desc, *desc2;
2975		struct ctl_lun *lun;
2976		int delete_done;
2977
2978		delete_desc = (struct ctl_error_desc *)addr;
2979		delete_done = 0;
2980
2981		mtx_lock(&softc->ctl_lock);
2982		lun = softc->ctl_luns[delete_desc->lun_id];
2983		if (lun == NULL) {
2984			mtx_unlock(&softc->ctl_lock);
2985			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2986			       __func__, (uintmax_t)delete_desc->lun_id);
2987			retval = EINVAL;
2988			break;
2989		}
2990		mtx_lock(&lun->lun_lock);
2991		mtx_unlock(&softc->ctl_lock);
2992		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2993			if (desc->serial != delete_desc->serial)
2994				continue;
2995
2996			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2997				      links);
2998			free(desc, M_CTL);
2999			delete_done = 1;
3000		}
3001		mtx_unlock(&lun->lun_lock);
3002		if (delete_done == 0) {
3003			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3004			       "error serial %ju on LUN %u\n", __func__,
3005			       delete_desc->serial, delete_desc->lun_id);
3006			retval = EINVAL;
3007			break;
3008		}
3009		break;
3010	}
3011	case CTL_DUMP_STRUCTS: {
3012		int i, j, k, idx;
3013		struct ctl_port *port;
3014		struct ctl_frontend *fe;
3015
3016		mtx_lock(&softc->ctl_lock);
3017		printf("CTL Persistent Reservation information start:\n");
3018		for (i = 0; i < CTL_MAX_LUNS; i++) {
3019			struct ctl_lun *lun;
3020
3021			lun = softc->ctl_luns[i];
3022
3023			if ((lun == NULL)
3024			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3025				continue;
3026
3027			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3028				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3029					idx = j * CTL_MAX_INIT_PER_PORT + k;
3030					if (lun->pr_keys[idx] == 0)
3031						continue;
3032					printf("  LUN %d port %d iid %d key "
3033					       "%#jx\n", i, j, k,
3034					       (uintmax_t)lun->pr_keys[idx]);
3035				}
3036			}
3037		}
3038		printf("CTL Persistent Reservation information end\n");
3039		printf("CTL Ports:\n");
3040		STAILQ_FOREACH(port, &softc->port_list, links) {
3041			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3042			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3043			       port->frontend->name, port->port_type,
3044			       port->physical_port, port->virtual_port,
3045			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3046			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3047				if (port->wwpn_iid[j].in_use == 0 &&
3048				    port->wwpn_iid[j].wwpn == 0 &&
3049				    port->wwpn_iid[j].name == NULL)
3050					continue;
3051
3052				printf("    iid %u use %d WWPN %#jx '%s'\n",
3053				    j, port->wwpn_iid[j].in_use,
3054				    (uintmax_t)port->wwpn_iid[j].wwpn,
3055				    port->wwpn_iid[j].name);
3056			}
3057		}
3058		printf("CTL Port information end\n");
3059		mtx_unlock(&softc->ctl_lock);
3060		/*
3061		 * XXX KDM calling this without a lock.  We'd likely want
3062		 * to drop the lock before calling the frontend's dump
3063		 * routine anyway.
3064		 */
3065		printf("CTL Frontends:\n");
3066		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3067			printf("  Frontend '%s'\n", fe->name);
3068			if (fe->fe_dump != NULL)
3069				fe->fe_dump();
3070		}
3071		printf("CTL Frontend information end\n");
3072		break;
3073	}
3074	case CTL_LUN_REQ: {
3075		struct ctl_lun_req *lun_req;
3076		struct ctl_backend_driver *backend;
3077
3078		lun_req = (struct ctl_lun_req *)addr;
3079
3080		backend = ctl_backend_find(lun_req->backend);
3081		if (backend == NULL) {
3082			lun_req->status = CTL_LUN_ERROR;
3083			snprintf(lun_req->error_str,
3084				 sizeof(lun_req->error_str),
3085				 "Backend \"%s\" not found.",
3086				 lun_req->backend);
3087			break;
3088		}
3089		if (lun_req->num_be_args > 0) {
3090			lun_req->kern_be_args = ctl_copyin_args(
3091				lun_req->num_be_args,
3092				lun_req->be_args,
3093				lun_req->error_str,
3094				sizeof(lun_req->error_str));
3095			if (lun_req->kern_be_args == NULL) {
3096				lun_req->status = CTL_LUN_ERROR;
3097				break;
3098			}
3099		}
3100
3101		retval = backend->ioctl(dev, cmd, addr, flag, td);
3102
3103		if (lun_req->num_be_args > 0) {
3104			ctl_copyout_args(lun_req->num_be_args,
3105				      lun_req->kern_be_args);
3106			ctl_free_args(lun_req->num_be_args,
3107				      lun_req->kern_be_args);
3108		}
3109		break;
3110	}
3111	case CTL_LUN_LIST: {
3112		struct sbuf *sb;
3113		struct ctl_lun *lun;
3114		struct ctl_lun_list *list;
3115		struct ctl_option *opt;
3116
3117		list = (struct ctl_lun_list *)addr;
3118
3119		/*
3120		 * Allocate a fixed length sbuf here, based on the length
3121		 * of the user's buffer.  We could allocate an auto-extending
3122		 * buffer, and then tell the user how much larger our
3123		 * amount of data is than his buffer, but that presents
3124		 * some problems:
3125		 *
3126		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3127		 *     we can't hold a lock while calling them with an
3128		 *     auto-extending buffer.
3129 		 *
3130		 * 2.  There is not currently a LUN reference counting
3131		 *     mechanism, outside of outstanding transactions on
3132		 *     the LUN's OOA queue.  So a LUN could go away on us
3133		 *     while we're getting the LUN number, backend-specific
3134		 *     information, etc.  Thus, given the way things
3135		 *     currently work, we need to hold the CTL lock while
3136		 *     grabbing LUN information.
3137		 *
3138		 * So, from the user's standpoint, the best thing to do is
3139		 * allocate what he thinks is a reasonable buffer length,
3140		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3141		 * double the buffer length and try again.  (And repeat
3142		 * that until he succeeds.)
3143		 */
3144		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3145		if (sb == NULL) {
3146			list->status = CTL_LUN_LIST_ERROR;
3147			snprintf(list->error_str, sizeof(list->error_str),
3148				 "Unable to allocate %d bytes for LUN list",
3149				 list->alloc_len);
3150			break;
3151		}
3152
3153		sbuf_printf(sb, "<ctllunlist>\n");
3154
3155		mtx_lock(&softc->ctl_lock);
3156		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3157			mtx_lock(&lun->lun_lock);
3158			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3159					     (uintmax_t)lun->lun);
3160
3161			/*
3162			 * Bail out as soon as we see that we've overfilled
3163			 * the buffer.
3164			 */
3165			if (retval != 0)
3166				break;
3167
3168			retval = sbuf_printf(sb, "\t<backend_type>%s"
3169					     "</backend_type>\n",
3170					     (lun->backend == NULL) ?  "none" :
3171					     lun->backend->name);
3172
3173			if (retval != 0)
3174				break;
3175
3176			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3177					     lun->be_lun->lun_type);
3178
3179			if (retval != 0)
3180				break;
3181
3182			if (lun->backend == NULL) {
3183				retval = sbuf_printf(sb, "</lun>\n");
3184				if (retval != 0)
3185					break;
3186				continue;
3187			}
3188
3189			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3190					     (lun->be_lun->maxlba > 0) ?
3191					     lun->be_lun->maxlba + 1 : 0);
3192
3193			if (retval != 0)
3194				break;
3195
3196			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3197					     lun->be_lun->blocksize);
3198
3199			if (retval != 0)
3200				break;
3201
3202			retval = sbuf_printf(sb, "\t<serial_number>");
3203
3204			if (retval != 0)
3205				break;
3206
3207			retval = ctl_sbuf_printf_esc(sb,
3208						     lun->be_lun->serial_num);
3209
3210			if (retval != 0)
3211				break;
3212
3213			retval = sbuf_printf(sb, "</serial_number>\n");
3214
3215			if (retval != 0)
3216				break;
3217
3218			retval = sbuf_printf(sb, "\t<device_id>");
3219
3220			if (retval != 0)
3221				break;
3222
3223			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3224
3225			if (retval != 0)
3226				break;
3227
3228			retval = sbuf_printf(sb, "</device_id>\n");
3229
3230			if (retval != 0)
3231				break;
3232
3233			if (lun->backend->lun_info != NULL) {
3234				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3235				if (retval != 0)
3236					break;
3237			}
3238			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3239				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3240				    opt->name, opt->value, opt->name);
3241				if (retval != 0)
3242					break;
3243			}
3244
3245			retval = sbuf_printf(sb, "</lun>\n");
3246
3247			if (retval != 0)
3248				break;
3249			mtx_unlock(&lun->lun_lock);
3250		}
3251		if (lun != NULL)
3252			mtx_unlock(&lun->lun_lock);
3253		mtx_unlock(&softc->ctl_lock);
3254
3255		if ((retval != 0)
3256		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3257			retval = 0;
3258			sbuf_delete(sb);
3259			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3260			snprintf(list->error_str, sizeof(list->error_str),
3261				 "Out of space, %d bytes is too small",
3262				 list->alloc_len);
3263			break;
3264		}
3265
3266		sbuf_finish(sb);
3267
3268		retval = copyout(sbuf_data(sb), list->lun_xml,
3269				 sbuf_len(sb) + 1);
3270
3271		list->fill_len = sbuf_len(sb) + 1;
3272		list->status = CTL_LUN_LIST_OK;
3273		sbuf_delete(sb);
3274		break;
3275	}
3276	case CTL_ISCSI: {
3277		struct ctl_iscsi *ci;
3278		struct ctl_frontend *fe;
3279
3280		ci = (struct ctl_iscsi *)addr;
3281
3282		fe = ctl_frontend_find("iscsi");
3283		if (fe == NULL) {
3284			ci->status = CTL_ISCSI_ERROR;
3285			snprintf(ci->error_str, sizeof(ci->error_str),
3286			    "Frontend \"iscsi\" not found.");
3287			break;
3288		}
3289
3290		retval = fe->ioctl(dev, cmd, addr, flag, td);
3291		break;
3292	}
3293	case CTL_PORT_REQ: {
3294		struct ctl_req *req;
3295		struct ctl_frontend *fe;
3296
3297		req = (struct ctl_req *)addr;
3298
3299		fe = ctl_frontend_find(req->driver);
3300		if (fe == NULL) {
3301			req->status = CTL_LUN_ERROR;
3302			snprintf(req->error_str, sizeof(req->error_str),
3303			    "Frontend \"%s\" not found.", req->driver);
3304			break;
3305		}
3306		if (req->num_args > 0) {
3307			req->kern_args = ctl_copyin_args(req->num_args,
3308			    req->args, req->error_str, sizeof(req->error_str));
3309			if (req->kern_args == NULL) {
3310				req->status = CTL_LUN_ERROR;
3311				break;
3312			}
3313		}
3314
3315		retval = fe->ioctl(dev, cmd, addr, flag, td);
3316
3317		if (req->num_args > 0) {
3318			ctl_copyout_args(req->num_args, req->kern_args);
3319			ctl_free_args(req->num_args, req->kern_args);
3320		}
3321		break;
3322	}
3323	case CTL_PORT_LIST: {
3324		struct sbuf *sb;
3325		struct ctl_port *port;
3326		struct ctl_lun_list *list;
3327		struct ctl_option *opt;
3328		int j;
3329
3330		list = (struct ctl_lun_list *)addr;
3331
3332		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3333		if (sb == NULL) {
3334			list->status = CTL_LUN_LIST_ERROR;
3335			snprintf(list->error_str, sizeof(list->error_str),
3336				 "Unable to allocate %d bytes for LUN list",
3337				 list->alloc_len);
3338			break;
3339		}
3340
3341		sbuf_printf(sb, "<ctlportlist>\n");
3342
3343		mtx_lock(&softc->ctl_lock);
3344		STAILQ_FOREACH(port, &softc->port_list, links) {
3345			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3346					     (uintmax_t)port->targ_port);
3347
3348			/*
3349			 * Bail out as soon as we see that we've overfilled
3350			 * the buffer.
3351			 */
3352			if (retval != 0)
3353				break;
3354
3355			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3356			    "</frontend_type>\n", port->frontend->name);
3357			if (retval != 0)
3358				break;
3359
3360			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3361					     port->port_type);
3362			if (retval != 0)
3363				break;
3364
3365			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3366			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3367			if (retval != 0)
3368				break;
3369
3370			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3371			    port->port_name);
3372			if (retval != 0)
3373				break;
3374
3375			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3376			    port->physical_port);
3377			if (retval != 0)
3378				break;
3379
3380			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3381			    port->virtual_port);
3382			if (retval != 0)
3383				break;
3384
3385			if (port->target_devid != NULL) {
3386				sbuf_printf(sb, "\t<target>");
3387				ctl_id_sbuf(port->target_devid, sb);
3388				sbuf_printf(sb, "</target>\n");
3389			}
3390
3391			if (port->port_devid != NULL) {
3392				sbuf_printf(sb, "\t<port>");
3393				ctl_id_sbuf(port->port_devid, sb);
3394				sbuf_printf(sb, "</port>\n");
3395			}
3396
3397			if (port->port_info != NULL) {
3398				retval = port->port_info(port->onoff_arg, sb);
3399				if (retval != 0)
3400					break;
3401			}
3402			STAILQ_FOREACH(opt, &port->options, links) {
3403				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3404				    opt->name, opt->value, opt->name);
3405				if (retval != 0)
3406					break;
3407			}
3408
3409			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3410				if (port->wwpn_iid[j].in_use == 0 ||
3411				    (port->wwpn_iid[j].wwpn == 0 &&
3412				     port->wwpn_iid[j].name == NULL))
3413					continue;
3414
3415				if (port->wwpn_iid[j].name != NULL)
3416					retval = sbuf_printf(sb,
3417					    "\t<initiator>%u %s</initiator>\n",
3418					    j, port->wwpn_iid[j].name);
3419				else
3420					retval = sbuf_printf(sb,
3421					    "\t<initiator>%u naa.%08jx</initiator>\n",
3422					    j, port->wwpn_iid[j].wwpn);
3423				if (retval != 0)
3424					break;
3425			}
3426			if (retval != 0)
3427				break;
3428
3429			retval = sbuf_printf(sb, "</targ_port>\n");
3430			if (retval != 0)
3431				break;
3432		}
3433		mtx_unlock(&softc->ctl_lock);
3434
3435		if ((retval != 0)
3436		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3437			retval = 0;
3438			sbuf_delete(sb);
3439			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3440			snprintf(list->error_str, sizeof(list->error_str),
3441				 "Out of space, %d bytes is too small",
3442				 list->alloc_len);
3443			break;
3444		}
3445
3446		sbuf_finish(sb);
3447
3448		retval = copyout(sbuf_data(sb), list->lun_xml,
3449				 sbuf_len(sb) + 1);
3450
3451		list->fill_len = sbuf_len(sb) + 1;
3452		list->status = CTL_LUN_LIST_OK;
3453		sbuf_delete(sb);
3454		break;
3455	}
3456	default: {
3457		/* XXX KDM should we fix this? */
3458#if 0
3459		struct ctl_backend_driver *backend;
3460		unsigned int type;
3461		int found;
3462
3463		found = 0;
3464
3465		/*
3466		 * We encode the backend type as the ioctl type for backend
3467		 * ioctls.  So parse it out here, and then search for a
3468		 * backend of this type.
3469		 */
3470		type = _IOC_TYPE(cmd);
3471
3472		STAILQ_FOREACH(backend, &softc->be_list, links) {
3473			if (backend->type == type) {
3474				found = 1;
3475				break;
3476			}
3477		}
3478		if (found == 0) {
3479			printf("ctl: unknown ioctl command %#lx or backend "
3480			       "%d\n", cmd, type);
3481			retval = EINVAL;
3482			break;
3483		}
3484		retval = backend->ioctl(dev, cmd, addr, flag, td);
3485#endif
3486		retval = ENOTTY;
3487		break;
3488	}
3489	}
3490	return (retval);
3491}
3492
3493uint32_t
3494ctl_get_initindex(struct ctl_nexus *nexus)
3495{
3496	if (nexus->targ_port < CTL_MAX_PORTS)
3497		return (nexus->initid.id +
3498			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3499	else
3500		return (nexus->initid.id +
3501		       ((nexus->targ_port - CTL_MAX_PORTS) *
3502			CTL_MAX_INIT_PER_PORT));
3503}
3504
3505uint32_t
3506ctl_get_resindex(struct ctl_nexus *nexus)
3507{
3508	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3509}
3510
3511uint32_t
3512ctl_port_idx(int port_num)
3513{
3514	if (port_num < CTL_MAX_PORTS)
3515		return(port_num);
3516	else
3517		return(port_num - CTL_MAX_PORTS);
3518}
3519
3520static uint32_t
3521ctl_map_lun(int port_num, uint32_t lun_id)
3522{
3523	struct ctl_port *port;
3524
3525	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3526	if (port == NULL)
3527		return (UINT32_MAX);
3528	if (port->lun_map == NULL)
3529		return (lun_id);
3530	return (port->lun_map(port->targ_lun_arg, lun_id));
3531}
3532
3533static uint32_t
3534ctl_map_lun_back(int port_num, uint32_t lun_id)
3535{
3536	struct ctl_port *port;
3537	uint32_t i;
3538
3539	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3540	if (port->lun_map == NULL)
3541		return (lun_id);
3542	for (i = 0; i < CTL_MAX_LUNS; i++) {
3543		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3544			return (i);
3545	}
3546	return (UINT32_MAX);
3547}
3548
3549/*
3550 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3551 * that are a power of 2.
3552 */
3553int
3554ctl_ffz(uint32_t *mask, uint32_t size)
3555{
3556	uint32_t num_chunks, num_pieces;
3557	int i, j;
3558
3559	num_chunks = (size >> 5);
3560	if (num_chunks == 0)
3561		num_chunks++;
3562	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3563
3564	for (i = 0; i < num_chunks; i++) {
3565		for (j = 0; j < num_pieces; j++) {
3566			if ((mask[i] & (1 << j)) == 0)
3567				return ((i << 5) + j);
3568		}
3569	}
3570
3571	return (-1);
3572}
3573
3574int
3575ctl_set_mask(uint32_t *mask, uint32_t bit)
3576{
3577	uint32_t chunk, piece;
3578
3579	chunk = bit >> 5;
3580	piece = bit % (sizeof(uint32_t) * 8);
3581
3582	if ((mask[chunk] & (1 << piece)) != 0)
3583		return (-1);
3584	else
3585		mask[chunk] |= (1 << piece);
3586
3587	return (0);
3588}
3589
3590int
3591ctl_clear_mask(uint32_t *mask, uint32_t bit)
3592{
3593	uint32_t chunk, piece;
3594
3595	chunk = bit >> 5;
3596	piece = bit % (sizeof(uint32_t) * 8);
3597
3598	if ((mask[chunk] & (1 << piece)) == 0)
3599		return (-1);
3600	else
3601		mask[chunk] &= ~(1 << piece);
3602
3603	return (0);
3604}
3605
3606int
3607ctl_is_set(uint32_t *mask, uint32_t bit)
3608{
3609	uint32_t chunk, piece;
3610
3611	chunk = bit >> 5;
3612	piece = bit % (sizeof(uint32_t) * 8);
3613
3614	if ((mask[chunk] & (1 << piece)) == 0)
3615		return (0);
3616	else
3617		return (1);
3618}
3619
3620#ifdef unused
3621/*
3622 * The bus, target and lun are optional, they can be filled in later.
3623 * can_wait is used to determine whether we can wait on the malloc or not.
3624 */
3625union ctl_io*
3626ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3627	      uint32_t targ_lun, int can_wait)
3628{
3629	union ctl_io *io;
3630
3631	if (can_wait)
3632		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3633	else
3634		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3635
3636	if (io != NULL) {
3637		io->io_hdr.io_type = io_type;
3638		io->io_hdr.targ_port = targ_port;
3639		/*
3640		 * XXX KDM this needs to change/go away.  We need to move
3641		 * to a preallocated pool of ctl_scsiio structures.
3642		 */
3643		io->io_hdr.nexus.targ_target.id = targ_target;
3644		io->io_hdr.nexus.targ_lun = targ_lun;
3645	}
3646
3647	return (io);
3648}
3649
3650void
3651ctl_kfree_io(union ctl_io *io)
3652{
3653	free(io, M_CTL);
3654}
3655#endif /* unused */
3656
3657/*
3658 * ctl_softc, pool_type, total_ctl_io are passed in.
3659 * npool is passed out.
3660 */
3661int
3662ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3663		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3664{
3665	uint32_t i;
3666	union ctl_io *cur_io, *next_io;
3667	struct ctl_io_pool *pool;
3668	int retval;
3669
3670	retval = 0;
3671
3672	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3673					    M_NOWAIT | M_ZERO);
3674	if (pool == NULL) {
3675		retval = ENOMEM;
3676		goto bailout;
3677	}
3678
3679	pool->type = pool_type;
3680	pool->ctl_softc = ctl_softc;
3681
3682	mtx_lock(&ctl_softc->pool_lock);
3683	pool->id = ctl_softc->cur_pool_id++;
3684	mtx_unlock(&ctl_softc->pool_lock);
3685
3686	pool->flags = CTL_POOL_FLAG_NONE;
3687	pool->refcount = 1;		/* Reference for validity. */
3688	STAILQ_INIT(&pool->free_queue);
3689
3690	/*
3691	 * XXX KDM other options here:
3692	 * - allocate a page at a time
3693	 * - allocate one big chunk of memory.
3694	 * Page allocation might work well, but would take a little more
3695	 * tracking.
3696	 */
3697	for (i = 0; i < total_ctl_io; i++) {
3698		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3699						M_NOWAIT);
3700		if (cur_io == NULL) {
3701			retval = ENOMEM;
3702			break;
3703		}
3704		cur_io->io_hdr.pool = pool;
3705		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3706		pool->total_ctl_io++;
3707		pool->free_ctl_io++;
3708	}
3709
3710	if (retval != 0) {
3711		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3712		     cur_io != NULL; cur_io = next_io) {
3713			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3714							      links);
3715			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3716				      ctl_io_hdr, links);
3717			free(cur_io, M_CTLIO);
3718		}
3719
3720		free(pool, M_CTL);
3721		goto bailout;
3722	}
3723	mtx_lock(&ctl_softc->pool_lock);
3724	ctl_softc->num_pools++;
3725	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3726	/*
3727	 * Increment our usage count if this is an external consumer, so we
3728	 * can't get unloaded until the external consumer (most likely a
3729	 * FETD) unloads and frees his pool.
3730	 *
3731	 * XXX KDM will this increment the caller's module use count, or
3732	 * mine?
3733	 */
3734#if 0
3735	if ((pool_type != CTL_POOL_EMERGENCY)
3736	 && (pool_type != CTL_POOL_INTERNAL)
3737	 && (pool_type != CTL_POOL_4OTHERSC))
3738		MOD_INC_USE_COUNT;
3739#endif
3740
3741	mtx_unlock(&ctl_softc->pool_lock);
3742
3743	*npool = pool;
3744
3745bailout:
3746
3747	return (retval);
3748}
3749
3750static int
3751ctl_pool_acquire(struct ctl_io_pool *pool)
3752{
3753
3754	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3755
3756	if (pool->flags & CTL_POOL_FLAG_INVALID)
3757		return (EINVAL);
3758
3759	pool->refcount++;
3760
3761	return (0);
3762}
3763
3764static void
3765ctl_pool_release(struct ctl_io_pool *pool)
3766{
3767	struct ctl_softc *ctl_softc = pool->ctl_softc;
3768	union ctl_io *io;
3769
3770	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3771
3772	if (--pool->refcount != 0)
3773		return;
3774
3775	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3776		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3777			      links);
3778		free(io, M_CTLIO);
3779	}
3780
3781	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3782	ctl_softc->num_pools--;
3783
3784	/*
3785	 * XXX KDM will this decrement the caller's usage count or mine?
3786	 */
3787#if 0
3788	if ((pool->type != CTL_POOL_EMERGENCY)
3789	 && (pool->type != CTL_POOL_INTERNAL)
3790	 && (pool->type != CTL_POOL_4OTHERSC))
3791		MOD_DEC_USE_COUNT;
3792#endif
3793
3794	free(pool, M_CTL);
3795}
3796
3797void
3798ctl_pool_free(struct ctl_io_pool *pool)
3799{
3800	struct ctl_softc *ctl_softc;
3801
3802	if (pool == NULL)
3803		return;
3804
3805	ctl_softc = pool->ctl_softc;
3806	mtx_lock(&ctl_softc->pool_lock);
3807	pool->flags |= CTL_POOL_FLAG_INVALID;
3808	ctl_pool_release(pool);
3809	mtx_unlock(&ctl_softc->pool_lock);
3810}
3811
3812/*
3813 * This routine does not block (except for spinlocks of course).
3814 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3815 * possible.
3816 */
3817union ctl_io *
3818ctl_alloc_io(void *pool_ref)
3819{
3820	union ctl_io *io;
3821	struct ctl_softc *ctl_softc;
3822	struct ctl_io_pool *pool, *npool;
3823	struct ctl_io_pool *emergency_pool;
3824
3825	pool = (struct ctl_io_pool *)pool_ref;
3826
3827	if (pool == NULL) {
3828		printf("%s: pool is NULL\n", __func__);
3829		return (NULL);
3830	}
3831
3832	emergency_pool = NULL;
3833
3834	ctl_softc = pool->ctl_softc;
3835
3836	mtx_lock(&ctl_softc->pool_lock);
3837	/*
3838	 * First, try to get the io structure from the user's pool.
3839	 */
3840	if (ctl_pool_acquire(pool) == 0) {
3841		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3842		if (io != NULL) {
3843			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3844			pool->total_allocated++;
3845			pool->free_ctl_io--;
3846			mtx_unlock(&ctl_softc->pool_lock);
3847			return (io);
3848		} else
3849			ctl_pool_release(pool);
3850	}
3851	/*
3852	 * If he doesn't have any io structures left, search for an
3853	 * emergency pool and grab one from there.
3854	 */
3855	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3856		if (npool->type != CTL_POOL_EMERGENCY)
3857			continue;
3858
3859		if (ctl_pool_acquire(npool) != 0)
3860			continue;
3861
3862		emergency_pool = npool;
3863
3864		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3865		if (io != NULL) {
3866			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3867			npool->total_allocated++;
3868			npool->free_ctl_io--;
3869			mtx_unlock(&ctl_softc->pool_lock);
3870			return (io);
3871		} else
3872			ctl_pool_release(npool);
3873	}
3874
3875	/* Drop the spinlock before we malloc */
3876	mtx_unlock(&ctl_softc->pool_lock);
3877
3878	/*
3879	 * The emergency pool (if it exists) didn't have one, so try an
3880	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3881	 */
3882	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3883	if (io != NULL) {
3884		/*
3885		 * If the emergency pool exists but is empty, add this
3886		 * ctl_io to its list when it gets freed.
3887		 */
3888		if (emergency_pool != NULL) {
3889			mtx_lock(&ctl_softc->pool_lock);
3890			if (ctl_pool_acquire(emergency_pool) == 0) {
3891				io->io_hdr.pool = emergency_pool;
3892				emergency_pool->total_ctl_io++;
3893				/*
3894				 * Need to bump this, otherwise
3895				 * total_allocated and total_freed won't
3896				 * match when we no longer have anything
3897				 * outstanding.
3898				 */
3899				emergency_pool->total_allocated++;
3900			}
3901			mtx_unlock(&ctl_softc->pool_lock);
3902		} else
3903			io->io_hdr.pool = NULL;
3904	}
3905
3906	return (io);
3907}
3908
3909void
3910ctl_free_io(union ctl_io *io)
3911{
3912	if (io == NULL)
3913		return;
3914
3915	/*
3916	 * If this ctl_io has a pool, return it to that pool.
3917	 */
3918	if (io->io_hdr.pool != NULL) {
3919		struct ctl_io_pool *pool;
3920
3921		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3922		mtx_lock(&pool->ctl_softc->pool_lock);
3923		io->io_hdr.io_type = 0xff;
3924		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3925		pool->total_freed++;
3926		pool->free_ctl_io++;
3927		ctl_pool_release(pool);
3928		mtx_unlock(&pool->ctl_softc->pool_lock);
3929	} else {
3930		/*
3931		 * Otherwise, just free it.  We probably malloced it and
3932		 * the emergency pool wasn't available.
3933		 */
3934		free(io, M_CTLIO);
3935	}
3936
3937}
3938
3939void
3940ctl_zero_io(union ctl_io *io)
3941{
3942	void *pool_ref;
3943
3944	if (io == NULL)
3945		return;
3946
3947	/*
3948	 * May need to preserve linked list pointers at some point too.
3949	 */
3950	pool_ref = io->io_hdr.pool;
3951
3952	memset(io, 0, sizeof(*io));
3953
3954	io->io_hdr.pool = pool_ref;
3955}
3956
3957/*
3958 * This routine is currently used for internal copies of ctl_ios that need
3959 * to persist for some reason after we've already returned status to the
3960 * FETD.  (Thus the flag set.)
3961 *
3962 * XXX XXX
3963 * Note that this makes a blind copy of all fields in the ctl_io, except
3964 * for the pool reference.  This includes any memory that has been
3965 * allocated!  That memory will no longer be valid after done has been
3966 * called, so this would be VERY DANGEROUS for command that actually does
3967 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3968 * start and stop commands, which don't transfer any data, so this is not a
3969 * problem.  If it is used for anything else, the caller would also need to
3970 * allocate data buffer space and this routine would need to be modified to
3971 * copy the data buffer(s) as well.
3972 */
3973void
3974ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3975{
3976	void *pool_ref;
3977
3978	if ((src == NULL)
3979	 || (dest == NULL))
3980		return;
3981
3982	/*
3983	 * May need to preserve linked list pointers at some point too.
3984	 */
3985	pool_ref = dest->io_hdr.pool;
3986
3987	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3988
3989	dest->io_hdr.pool = pool_ref;
3990	/*
3991	 * We need to know that this is an internal copy, and doesn't need
3992	 * to get passed back to the FETD that allocated it.
3993	 */
3994	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3995}
3996
3997#ifdef NEEDTOPORT
3998static void
3999ctl_update_power_subpage(struct copan_power_subpage *page)
4000{
4001	int num_luns, num_partitions, config_type;
4002	struct ctl_softc *softc;
4003	cs_BOOL_t aor_present, shelf_50pct_power;
4004	cs_raidset_personality_t rs_type;
4005	int max_active_luns;
4006
4007	softc = control_softc;
4008
4009	/* subtract out the processor LUN */
4010	num_luns = softc->num_luns - 1;
4011	/*
4012	 * Default to 7 LUNs active, which was the only number we allowed
4013	 * in the past.
4014	 */
4015	max_active_luns = 7;
4016
4017	num_partitions = config_GetRsPartitionInfo();
4018	config_type = config_GetConfigType();
4019	shelf_50pct_power = config_GetShelfPowerMode();
4020	aor_present = config_IsAorRsPresent();
4021
4022	rs_type = ddb_GetRsRaidType(1);
4023	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
4024	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
4025		EPRINT(0, "Unsupported RS type %d!", rs_type);
4026	}
4027
4028
4029	page->total_luns = num_luns;
4030
4031	switch (config_type) {
4032	case 40:
4033		/*
4034		 * In a 40 drive configuration, it doesn't matter what DC
4035		 * cards we have, whether we have AOR enabled or not,
4036		 * partitioning or not, or what type of RAIDset we have.
4037		 * In that scenario, we can power up every LUN we present
4038		 * to the user.
4039		 */
4040		max_active_luns = num_luns;
4041
4042		break;
4043	case 64:
4044		if (shelf_50pct_power == CS_FALSE) {
4045			/* 25% power */
4046			if (aor_present == CS_TRUE) {
4047				if (rs_type ==
4048				     CS_RAIDSET_PERSONALITY_RAID5) {
4049					max_active_luns = 7;
4050				} else if (rs_type ==
4051					 CS_RAIDSET_PERSONALITY_RAID1){
4052					max_active_luns = 14;
4053				} else {
4054					/* XXX KDM now what?? */
4055				}
4056			} else {
4057				if (rs_type ==
4058				     CS_RAIDSET_PERSONALITY_RAID5) {
4059					max_active_luns = 8;
4060				} else if (rs_type ==
4061					 CS_RAIDSET_PERSONALITY_RAID1){
4062					max_active_luns = 16;
4063				} else {
4064					/* XXX KDM now what?? */
4065				}
4066			}
4067		} else {
4068			/* 50% power */
4069			/*
4070			 * With 50% power in a 64 drive configuration, we
4071			 * can power all LUNs we present.
4072			 */
4073			max_active_luns = num_luns;
4074		}
4075		break;
4076	case 112:
4077		if (shelf_50pct_power == CS_FALSE) {
4078			/* 25% power */
4079			if (aor_present == CS_TRUE) {
4080				if (rs_type ==
4081				     CS_RAIDSET_PERSONALITY_RAID5) {
4082					max_active_luns = 7;
4083				} else if (rs_type ==
4084					 CS_RAIDSET_PERSONALITY_RAID1){
4085					max_active_luns = 14;
4086				} else {
4087					/* XXX KDM now what?? */
4088				}
4089			} else {
4090				if (rs_type ==
4091				     CS_RAIDSET_PERSONALITY_RAID5) {
4092					max_active_luns = 8;
4093				} else if (rs_type ==
4094					 CS_RAIDSET_PERSONALITY_RAID1){
4095					max_active_luns = 16;
4096				} else {
4097					/* XXX KDM now what?? */
4098				}
4099			}
4100		} else {
4101			/* 50% power */
4102			if (aor_present == CS_TRUE) {
4103				if (rs_type ==
4104				     CS_RAIDSET_PERSONALITY_RAID5) {
4105					max_active_luns = 14;
4106				} else if (rs_type ==
4107					 CS_RAIDSET_PERSONALITY_RAID1){
4108					/*
4109					 * We're assuming here that disk
4110					 * caching is enabled, and so we're
4111					 * able to power up half of each
4112					 * LUN, and cache all writes.
4113					 */
4114					max_active_luns = num_luns;
4115				} else {
4116					/* XXX KDM now what?? */
4117				}
4118			} else {
4119				if (rs_type ==
4120				     CS_RAIDSET_PERSONALITY_RAID5) {
4121					max_active_luns = 15;
4122				} else if (rs_type ==
4123					 CS_RAIDSET_PERSONALITY_RAID1){
4124					max_active_luns = 30;
4125				} else {
4126					/* XXX KDM now what?? */
4127				}
4128			}
4129		}
4130		break;
4131	default:
4132		/*
4133		 * In this case, we have an unknown configuration, so we
4134		 * just use the default from above.
4135		 */
4136		break;
4137	}
4138
4139	page->max_active_luns = max_active_luns;
4140#if 0
4141	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4142	       page->total_luns, page->max_active_luns);
4143#endif
4144}
4145#endif /* NEEDTOPORT */
4146
4147/*
4148 * This routine could be used in the future to load default and/or saved
4149 * mode page parameters for a particuar lun.
4150 */
4151static int
4152ctl_init_page_index(struct ctl_lun *lun)
4153{
4154	int i;
4155	struct ctl_page_index *page_index;
4156	struct ctl_softc *softc;
4157	const char *value;
4158
4159	memcpy(&lun->mode_pages.index, page_index_template,
4160	       sizeof(page_index_template));
4161
4162	softc = lun->ctl_softc;
4163
4164	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4165
4166		page_index = &lun->mode_pages.index[i];
4167		/*
4168		 * If this is a disk-only mode page, there's no point in
4169		 * setting it up.  For some pages, we have to have some
4170		 * basic information about the disk in order to calculate the
4171		 * mode page data.
4172		 */
4173		if ((lun->be_lun->lun_type != T_DIRECT)
4174		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4175			continue;
4176
4177		switch (page_index->page_code & SMPH_PC_MASK) {
4178		case SMS_FORMAT_DEVICE_PAGE: {
4179			struct scsi_format_page *format_page;
4180
4181			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4182				panic("subpage is incorrect!");
4183
4184			/*
4185			 * Sectors per track are set above.  Bytes per
4186			 * sector need to be set here on a per-LUN basis.
4187			 */
4188			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4189			       &format_page_default,
4190			       sizeof(format_page_default));
4191			memcpy(&lun->mode_pages.format_page[
4192			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4193			       sizeof(format_page_changeable));
4194			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4195			       &format_page_default,
4196			       sizeof(format_page_default));
4197			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4198			       &format_page_default,
4199			       sizeof(format_page_default));
4200
4201			format_page = &lun->mode_pages.format_page[
4202				CTL_PAGE_CURRENT];
4203			scsi_ulto2b(lun->be_lun->blocksize,
4204				    format_page->bytes_per_sector);
4205
4206			format_page = &lun->mode_pages.format_page[
4207				CTL_PAGE_DEFAULT];
4208			scsi_ulto2b(lun->be_lun->blocksize,
4209				    format_page->bytes_per_sector);
4210
4211			format_page = &lun->mode_pages.format_page[
4212				CTL_PAGE_SAVED];
4213			scsi_ulto2b(lun->be_lun->blocksize,
4214				    format_page->bytes_per_sector);
4215
4216			page_index->page_data =
4217				(uint8_t *)lun->mode_pages.format_page;
4218			break;
4219		}
4220		case SMS_RIGID_DISK_PAGE: {
4221			struct scsi_rigid_disk_page *rigid_disk_page;
4222			uint32_t sectors_per_cylinder;
4223			uint64_t cylinders;
4224#ifndef	__XSCALE__
4225			int shift;
4226#endif /* !__XSCALE__ */
4227
4228			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4229				panic("invalid subpage value %d",
4230				      page_index->subpage);
4231
4232			/*
4233			 * Rotation rate and sectors per track are set
4234			 * above.  We calculate the cylinders here based on
4235			 * capacity.  Due to the number of heads and
4236			 * sectors per track we're using, smaller arrays
4237			 * may turn out to have 0 cylinders.  Linux and
4238			 * FreeBSD don't pay attention to these mode pages
4239			 * to figure out capacity, but Solaris does.  It
4240			 * seems to deal with 0 cylinders just fine, and
4241			 * works out a fake geometry based on the capacity.
4242			 */
4243			memcpy(&lun->mode_pages.rigid_disk_page[
4244			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4245			       sizeof(rigid_disk_page_default));
4246			memcpy(&lun->mode_pages.rigid_disk_page[
4247			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4248			       sizeof(rigid_disk_page_changeable));
4249			memcpy(&lun->mode_pages.rigid_disk_page[
4250			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4251			       sizeof(rigid_disk_page_default));
4252			memcpy(&lun->mode_pages.rigid_disk_page[
4253			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4254			       sizeof(rigid_disk_page_default));
4255
4256			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4257				CTL_DEFAULT_HEADS;
4258
4259			/*
4260			 * The divide method here will be more accurate,
4261			 * probably, but results in floating point being
4262			 * used in the kernel on i386 (__udivdi3()).  On the
4263			 * XScale, though, __udivdi3() is implemented in
4264			 * software.
4265			 *
4266			 * The shift method for cylinder calculation is
4267			 * accurate if sectors_per_cylinder is a power of
4268			 * 2.  Otherwise it might be slightly off -- you
4269			 * might have a bit of a truncation problem.
4270			 */
4271#ifdef	__XSCALE__
4272			cylinders = (lun->be_lun->maxlba + 1) /
4273				sectors_per_cylinder;
4274#else
4275			for (shift = 31; shift > 0; shift--) {
4276				if (sectors_per_cylinder & (1 << shift))
4277					break;
4278			}
4279			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4280#endif
4281
4282			/*
4283			 * We've basically got 3 bytes, or 24 bits for the
4284			 * cylinder size in the mode page.  If we're over,
4285			 * just round down to 2^24.
4286			 */
4287			if (cylinders > 0xffffff)
4288				cylinders = 0xffffff;
4289
4290			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4291				CTL_PAGE_CURRENT];
4292			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4293
4294			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4295				CTL_PAGE_DEFAULT];
4296			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4297
4298			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4299				CTL_PAGE_SAVED];
4300			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4301
4302			page_index->page_data =
4303				(uint8_t *)lun->mode_pages.rigid_disk_page;
4304			break;
4305		}
4306		case SMS_CACHING_PAGE: {
4307			struct scsi_caching_page *caching_page;
4308
4309			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4310				panic("invalid subpage value %d",
4311				      page_index->subpage);
4312			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4313			       &caching_page_default,
4314			       sizeof(caching_page_default));
4315			memcpy(&lun->mode_pages.caching_page[
4316			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4317			       sizeof(caching_page_changeable));
4318			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4319			       &caching_page_default,
4320			       sizeof(caching_page_default));
4321			caching_page = &lun->mode_pages.caching_page[
4322			    CTL_PAGE_SAVED];
4323			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4324			if (value != NULL && strcmp(value, "off") == 0)
4325				caching_page->flags1 &= ~SCP_WCE;
4326			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4327			if (value != NULL && strcmp(value, "off") == 0)
4328				caching_page->flags1 |= SCP_RCD;
4329			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4330			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4331			       sizeof(caching_page_default));
4332			page_index->page_data =
4333				(uint8_t *)lun->mode_pages.caching_page;
4334			break;
4335		}
4336		case SMS_CONTROL_MODE_PAGE: {
4337			struct scsi_control_page *control_page;
4338
4339			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4340				panic("invalid subpage value %d",
4341				      page_index->subpage);
4342
4343			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4344			       &control_page_default,
4345			       sizeof(control_page_default));
4346			memcpy(&lun->mode_pages.control_page[
4347			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4348			       sizeof(control_page_changeable));
4349			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4350			       &control_page_default,
4351			       sizeof(control_page_default));
4352			control_page = &lun->mode_pages.control_page[
4353			    CTL_PAGE_SAVED];
4354			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4355			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4356				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4357				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4358			}
4359			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4360			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4361			       sizeof(control_page_default));
4362			page_index->page_data =
4363				(uint8_t *)lun->mode_pages.control_page;
4364			break;
4365
4366		}
4367		case SMS_VENDOR_SPECIFIC_PAGE:{
4368			switch (page_index->subpage) {
4369			case PWR_SUBPAGE_CODE: {
4370				struct copan_power_subpage *current_page,
4371							   *saved_page;
4372
4373				memcpy(&lun->mode_pages.power_subpage[
4374				       CTL_PAGE_CURRENT],
4375				       &power_page_default,
4376				       sizeof(power_page_default));
4377				memcpy(&lun->mode_pages.power_subpage[
4378				       CTL_PAGE_CHANGEABLE],
4379				       &power_page_changeable,
4380				       sizeof(power_page_changeable));
4381				memcpy(&lun->mode_pages.power_subpage[
4382				       CTL_PAGE_DEFAULT],
4383				       &power_page_default,
4384				       sizeof(power_page_default));
4385				memcpy(&lun->mode_pages.power_subpage[
4386				       CTL_PAGE_SAVED],
4387				       &power_page_default,
4388				       sizeof(power_page_default));
4389				page_index->page_data =
4390				    (uint8_t *)lun->mode_pages.power_subpage;
4391
4392				current_page = (struct copan_power_subpage *)
4393					(page_index->page_data +
4394					 (page_index->page_len *
4395					  CTL_PAGE_CURRENT));
4396			        saved_page = (struct copan_power_subpage *)
4397				        (page_index->page_data +
4398					 (page_index->page_len *
4399					  CTL_PAGE_SAVED));
4400				break;
4401			}
4402			case APS_SUBPAGE_CODE: {
4403				struct copan_aps_subpage *current_page,
4404							 *saved_page;
4405
4406				// This gets set multiple times but
4407				// it should always be the same. It's
4408				// only done during init so who cares.
4409				index_to_aps_page = i;
4410
4411				memcpy(&lun->mode_pages.aps_subpage[
4412				       CTL_PAGE_CURRENT],
4413				       &aps_page_default,
4414				       sizeof(aps_page_default));
4415				memcpy(&lun->mode_pages.aps_subpage[
4416				       CTL_PAGE_CHANGEABLE],
4417				       &aps_page_changeable,
4418				       sizeof(aps_page_changeable));
4419				memcpy(&lun->mode_pages.aps_subpage[
4420				       CTL_PAGE_DEFAULT],
4421				       &aps_page_default,
4422				       sizeof(aps_page_default));
4423				memcpy(&lun->mode_pages.aps_subpage[
4424				       CTL_PAGE_SAVED],
4425				       &aps_page_default,
4426				       sizeof(aps_page_default));
4427				page_index->page_data =
4428					(uint8_t *)lun->mode_pages.aps_subpage;
4429
4430				current_page = (struct copan_aps_subpage *)
4431					(page_index->page_data +
4432					 (page_index->page_len *
4433					  CTL_PAGE_CURRENT));
4434				saved_page = (struct copan_aps_subpage *)
4435					(page_index->page_data +
4436					 (page_index->page_len *
4437					  CTL_PAGE_SAVED));
4438				break;
4439			}
4440			case DBGCNF_SUBPAGE_CODE: {
4441				struct copan_debugconf_subpage *current_page,
4442							       *saved_page;
4443
4444				memcpy(&lun->mode_pages.debugconf_subpage[
4445				       CTL_PAGE_CURRENT],
4446				       &debugconf_page_default,
4447				       sizeof(debugconf_page_default));
4448				memcpy(&lun->mode_pages.debugconf_subpage[
4449				       CTL_PAGE_CHANGEABLE],
4450				       &debugconf_page_changeable,
4451				       sizeof(debugconf_page_changeable));
4452				memcpy(&lun->mode_pages.debugconf_subpage[
4453				       CTL_PAGE_DEFAULT],
4454				       &debugconf_page_default,
4455				       sizeof(debugconf_page_default));
4456				memcpy(&lun->mode_pages.debugconf_subpage[
4457				       CTL_PAGE_SAVED],
4458				       &debugconf_page_default,
4459				       sizeof(debugconf_page_default));
4460				page_index->page_data =
4461					(uint8_t *)lun->mode_pages.debugconf_subpage;
4462
4463				current_page = (struct copan_debugconf_subpage *)
4464					(page_index->page_data +
4465					 (page_index->page_len *
4466					  CTL_PAGE_CURRENT));
4467				saved_page = (struct copan_debugconf_subpage *)
4468					(page_index->page_data +
4469					 (page_index->page_len *
4470					  CTL_PAGE_SAVED));
4471				break;
4472			}
4473			default:
4474				panic("invalid subpage value %d",
4475				      page_index->subpage);
4476				break;
4477			}
4478   			break;
4479		}
4480		default:
4481			panic("invalid page value %d",
4482			      page_index->page_code & SMPH_PC_MASK);
4483			break;
4484    	}
4485	}
4486
4487	return (CTL_RETVAL_COMPLETE);
4488}
4489
4490/*
4491 * LUN allocation.
4492 *
4493 * Requirements:
4494 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4495 *   wants us to allocate the LUN and he can block.
4496 * - ctl_softc is always set
4497 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4498 *
4499 * Returns 0 for success, non-zero (errno) for failure.
4500 */
4501static int
4502ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4503	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4504{
4505	struct ctl_lun *nlun, *lun;
4506	struct ctl_port *port;
4507	struct scsi_vpd_id_descriptor *desc;
4508	struct scsi_vpd_id_t10 *t10id;
4509	const char *eui, *naa, *scsiname, *vendor, *value;
4510	int lun_number, i, lun_malloced;
4511	int devidlen, idlen1, idlen2 = 0, len;
4512
4513	if (be_lun == NULL)
4514		return (EINVAL);
4515
4516	/*
4517	 * We currently only support Direct Access or Processor LUN types.
4518	 */
4519	switch (be_lun->lun_type) {
4520	case T_DIRECT:
4521		break;
4522	case T_PROCESSOR:
4523		break;
4524	case T_SEQUENTIAL:
4525	case T_CHANGER:
4526	default:
4527		be_lun->lun_config_status(be_lun->be_lun,
4528					  CTL_LUN_CONFIG_FAILURE);
4529		break;
4530	}
4531	if (ctl_lun == NULL) {
4532		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4533		lun_malloced = 1;
4534	} else {
4535		lun_malloced = 0;
4536		lun = ctl_lun;
4537	}
4538
4539	memset(lun, 0, sizeof(*lun));
4540	if (lun_malloced)
4541		lun->flags = CTL_LUN_MALLOCED;
4542
4543	/* Generate LUN ID. */
4544	devidlen = max(CTL_DEVID_MIN_LEN,
4545	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4546	idlen1 = sizeof(*t10id) + devidlen;
4547	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4548	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4549	if (scsiname != NULL) {
4550		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4551		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4552	}
4553	eui = ctl_get_opt(&be_lun->options, "eui");
4554	if (eui != NULL) {
4555		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4556	}
4557	naa = ctl_get_opt(&be_lun->options, "naa");
4558	if (naa != NULL) {
4559		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4560	}
4561	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4562	    M_CTL, M_WAITOK | M_ZERO);
4563	lun->lun_devid->len = len;
4564	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4565	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4566	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4567	desc->length = idlen1;
4568	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4569	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4570	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4571		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4572	} else {
4573		strncpy(t10id->vendor, vendor,
4574		    min(sizeof(t10id->vendor), strlen(vendor)));
4575	}
4576	strncpy((char *)t10id->vendor_spec_id,
4577	    (char *)be_lun->device_id, devidlen);
4578	if (scsiname != NULL) {
4579		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4580		    desc->length);
4581		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4582		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4583		    SVPD_ID_TYPE_SCSI_NAME;
4584		desc->length = idlen2;
4585		strlcpy(desc->identifier, scsiname, idlen2);
4586	}
4587	if (eui != NULL) {
4588		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4589		    desc->length);
4590		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4591		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4592		    SVPD_ID_TYPE_EUI64;
4593		desc->length = 8;
4594		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4595	}
4596	if (naa != NULL) {
4597		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4598		    desc->length);
4599		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4600		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4601		    SVPD_ID_TYPE_NAA;
4602		desc->length = 8;
4603		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4604	}
4605
4606	mtx_lock(&ctl_softc->ctl_lock);
4607	/*
4608	 * See if the caller requested a particular LUN number.  If so, see
4609	 * if it is available.  Otherwise, allocate the first available LUN.
4610	 */
4611	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4612		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4613		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4614			mtx_unlock(&ctl_softc->ctl_lock);
4615			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4616				printf("ctl: requested LUN ID %d is higher "
4617				       "than CTL_MAX_LUNS - 1 (%d)\n",
4618				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4619			} else {
4620				/*
4621				 * XXX KDM return an error, or just assign
4622				 * another LUN ID in this case??
4623				 */
4624				printf("ctl: requested LUN ID %d is already "
4625				       "in use\n", be_lun->req_lun_id);
4626			}
4627			if (lun->flags & CTL_LUN_MALLOCED)
4628				free(lun, M_CTL);
4629			be_lun->lun_config_status(be_lun->be_lun,
4630						  CTL_LUN_CONFIG_FAILURE);
4631			return (ENOSPC);
4632		}
4633		lun_number = be_lun->req_lun_id;
4634	} else {
4635		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4636		if (lun_number == -1) {
4637			mtx_unlock(&ctl_softc->ctl_lock);
4638			printf("ctl: can't allocate LUN on target %ju, out of "
4639			       "LUNs\n", (uintmax_t)target_id.id);
4640			if (lun->flags & CTL_LUN_MALLOCED)
4641				free(lun, M_CTL);
4642			be_lun->lun_config_status(be_lun->be_lun,
4643						  CTL_LUN_CONFIG_FAILURE);
4644			return (ENOSPC);
4645		}
4646	}
4647	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4648
4649	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4650	lun->target = target_id;
4651	lun->lun = lun_number;
4652	lun->be_lun = be_lun;
4653	/*
4654	 * The processor LUN is always enabled.  Disk LUNs come on line
4655	 * disabled, and must be enabled by the backend.
4656	 */
4657	lun->flags |= CTL_LUN_DISABLED;
4658	lun->backend = be_lun->be;
4659	be_lun->ctl_lun = lun;
4660	be_lun->lun_id = lun_number;
4661	atomic_add_int(&be_lun->be->num_luns, 1);
4662	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4663		lun->flags |= CTL_LUN_OFFLINE;
4664
4665	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4666		lun->flags |= CTL_LUN_STOPPED;
4667
4668	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4669		lun->flags |= CTL_LUN_INOPERABLE;
4670
4671	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4672		lun->flags |= CTL_LUN_PRIMARY_SC;
4673
4674	value = ctl_get_opt(&be_lun->options, "readonly");
4675	if (value != NULL && strcmp(value, "on") == 0)
4676		lun->flags |= CTL_LUN_READONLY;
4677
4678	lun->ctl_softc = ctl_softc;
4679	TAILQ_INIT(&lun->ooa_queue);
4680	TAILQ_INIT(&lun->blocked_queue);
4681	STAILQ_INIT(&lun->error_list);
4682	ctl_tpc_lun_init(lun);
4683
4684	/*
4685	 * Initialize the mode page index.
4686	 */
4687	ctl_init_page_index(lun);
4688
4689	/*
4690	 * Set the poweron UA for all initiators on this LUN only.
4691	 */
4692	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4693		lun->pending_ua[i] = CTL_UA_POWERON;
4694
4695	/*
4696	 * Now, before we insert this lun on the lun list, set the lun
4697	 * inventory changed UA for all other luns.
4698	 */
4699	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4700		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4701			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4702		}
4703	}
4704
4705	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4706
4707	ctl_softc->ctl_luns[lun_number] = lun;
4708
4709	ctl_softc->num_luns++;
4710
4711	/* Setup statistics gathering */
4712	lun->stats.device_type = be_lun->lun_type;
4713	lun->stats.lun_number = lun_number;
4714	if (lun->stats.device_type == T_DIRECT)
4715		lun->stats.blocksize = be_lun->blocksize;
4716	else
4717		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4718	for (i = 0;i < CTL_MAX_PORTS;i++)
4719		lun->stats.ports[i].targ_port = i;
4720
4721	mtx_unlock(&ctl_softc->ctl_lock);
4722
4723	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4724
4725	/*
4726	 * Run through each registered FETD and bring it online if it isn't
4727	 * already.  Enable the target ID if it hasn't been enabled, and
4728	 * enable this particular LUN.
4729	 */
4730	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4731		int retval;
4732
4733		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4734		if (retval != 0) {
4735			printf("ctl_alloc_lun: FETD %s port %d returned error "
4736			       "%d for lun_enable on target %ju lun %d\n",
4737			       port->port_name, port->targ_port, retval,
4738			       (uintmax_t)target_id.id, lun_number);
4739		} else
4740			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4741	}
4742	return (0);
4743}
4744
4745/*
4746 * Delete a LUN.
4747 * Assumptions:
4748 * - LUN has already been marked invalid and any pending I/O has been taken
4749 *   care of.
4750 */
4751static int
4752ctl_free_lun(struct ctl_lun *lun)
4753{
4754	struct ctl_softc *softc;
4755#if 0
4756	struct ctl_port *port;
4757#endif
4758	struct ctl_lun *nlun;
4759	int i;
4760
4761	softc = lun->ctl_softc;
4762
4763	mtx_assert(&softc->ctl_lock, MA_OWNED);
4764
4765	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4766
4767	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4768
4769	softc->ctl_luns[lun->lun] = NULL;
4770
4771	if (!TAILQ_EMPTY(&lun->ooa_queue))
4772		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4773
4774	softc->num_luns--;
4775
4776	/*
4777	 * XXX KDM this scheme only works for a single target/multiple LUN
4778	 * setup.  It needs to be revamped for a multiple target scheme.
4779	 *
4780	 * XXX KDM this results in port->lun_disable() getting called twice,
4781	 * once when ctl_disable_lun() is called, and a second time here.
4782	 * We really need to re-think the LUN disable semantics.  There
4783	 * should probably be several steps/levels to LUN removal:
4784	 *  - disable
4785	 *  - invalidate
4786	 *  - free
4787 	 *
4788	 * Right now we only have a disable method when communicating to
4789	 * the front end ports, at least for individual LUNs.
4790	 */
4791#if 0
4792	STAILQ_FOREACH(port, &softc->port_list, links) {
4793		int retval;
4794
4795		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4796					 lun->lun);
4797		if (retval != 0) {
4798			printf("ctl_free_lun: FETD %s port %d returned error "
4799			       "%d for lun_disable on target %ju lun %jd\n",
4800			       port->port_name, port->targ_port, retval,
4801			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4802		}
4803
4804		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4805			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4806
4807			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4808			if (retval != 0) {
4809				printf("ctl_free_lun: FETD %s port %d "
4810				       "returned error %d for targ_disable on "
4811				       "target %ju\n", port->port_name,
4812				       port->targ_port, retval,
4813				       (uintmax_t)lun->target.id);
4814			} else
4815				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4816
4817			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4818				continue;
4819
4820#if 0
4821			port->port_offline(port->onoff_arg);
4822			port->status &= ~CTL_PORT_STATUS_ONLINE;
4823#endif
4824		}
4825	}
4826#endif
4827
4828	/*
4829	 * Tell the backend to free resources, if this LUN has a backend.
4830	 */
4831	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4832	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4833
4834	ctl_tpc_lun_shutdown(lun);
4835	mtx_destroy(&lun->lun_lock);
4836	free(lun->lun_devid, M_CTL);
4837	if (lun->flags & CTL_LUN_MALLOCED)
4838		free(lun, M_CTL);
4839
4840	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4841		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4842			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4843		}
4844	}
4845
4846	return (0);
4847}
4848
4849static void
4850ctl_create_lun(struct ctl_be_lun *be_lun)
4851{
4852	struct ctl_softc *ctl_softc;
4853
4854	ctl_softc = control_softc;
4855
4856	/*
4857	 * ctl_alloc_lun() should handle all potential failure cases.
4858	 */
4859	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4860}
4861
4862int
4863ctl_add_lun(struct ctl_be_lun *be_lun)
4864{
4865	struct ctl_softc *ctl_softc = control_softc;
4866
4867	mtx_lock(&ctl_softc->ctl_lock);
4868	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4869	mtx_unlock(&ctl_softc->ctl_lock);
4870	wakeup(&ctl_softc->pending_lun_queue);
4871
4872	return (0);
4873}
4874
4875int
4876ctl_enable_lun(struct ctl_be_lun *be_lun)
4877{
4878	struct ctl_softc *ctl_softc;
4879	struct ctl_port *port, *nport;
4880	struct ctl_lun *lun;
4881	int retval;
4882
4883	ctl_softc = control_softc;
4884
4885	lun = (struct ctl_lun *)be_lun->ctl_lun;
4886
4887	mtx_lock(&ctl_softc->ctl_lock);
4888	mtx_lock(&lun->lun_lock);
4889	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4890		/*
4891		 * eh?  Why did we get called if the LUN is already
4892		 * enabled?
4893		 */
4894		mtx_unlock(&lun->lun_lock);
4895		mtx_unlock(&ctl_softc->ctl_lock);
4896		return (0);
4897	}
4898	lun->flags &= ~CTL_LUN_DISABLED;
4899	mtx_unlock(&lun->lun_lock);
4900
4901	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4902		nport = STAILQ_NEXT(port, links);
4903
4904		/*
4905		 * Drop the lock while we call the FETD's enable routine.
4906		 * This can lead to a callback into CTL (at least in the
4907		 * case of the internal initiator frontend.
4908		 */
4909		mtx_unlock(&ctl_softc->ctl_lock);
4910		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4911		mtx_lock(&ctl_softc->ctl_lock);
4912		if (retval != 0) {
4913			printf("%s: FETD %s port %d returned error "
4914			       "%d for lun_enable on target %ju lun %jd\n",
4915			       __func__, port->port_name, port->targ_port, retval,
4916			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4917		}
4918#if 0
4919		 else {
4920            /* NOTE:  TODO:  why does lun enable affect port status? */
4921			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4922		}
4923#endif
4924	}
4925
4926	mtx_unlock(&ctl_softc->ctl_lock);
4927
4928	return (0);
4929}
4930
4931int
4932ctl_disable_lun(struct ctl_be_lun *be_lun)
4933{
4934	struct ctl_softc *ctl_softc;
4935	struct ctl_port *port;
4936	struct ctl_lun *lun;
4937	int retval;
4938
4939	ctl_softc = control_softc;
4940
4941	lun = (struct ctl_lun *)be_lun->ctl_lun;
4942
4943	mtx_lock(&ctl_softc->ctl_lock);
4944	mtx_lock(&lun->lun_lock);
4945	if (lun->flags & CTL_LUN_DISABLED) {
4946		mtx_unlock(&lun->lun_lock);
4947		mtx_unlock(&ctl_softc->ctl_lock);
4948		return (0);
4949	}
4950	lun->flags |= CTL_LUN_DISABLED;
4951	mtx_unlock(&lun->lun_lock);
4952
4953	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4954		mtx_unlock(&ctl_softc->ctl_lock);
4955		/*
4956		 * Drop the lock before we call the frontend's disable
4957		 * routine, to avoid lock order reversals.
4958		 *
4959		 * XXX KDM what happens if the frontend list changes while
4960		 * we're traversing it?  It's unlikely, but should be handled.
4961		 */
4962		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4963					 lun->lun);
4964		mtx_lock(&ctl_softc->ctl_lock);
4965		if (retval != 0) {
4966			printf("ctl_alloc_lun: FETD %s port %d returned error "
4967			       "%d for lun_disable on target %ju lun %jd\n",
4968			       port->port_name, port->targ_port, retval,
4969			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4970		}
4971	}
4972
4973	mtx_unlock(&ctl_softc->ctl_lock);
4974
4975	return (0);
4976}
4977
4978int
4979ctl_start_lun(struct ctl_be_lun *be_lun)
4980{
4981	struct ctl_softc *ctl_softc;
4982	struct ctl_lun *lun;
4983
4984	ctl_softc = control_softc;
4985
4986	lun = (struct ctl_lun *)be_lun->ctl_lun;
4987
4988	mtx_lock(&lun->lun_lock);
4989	lun->flags &= ~CTL_LUN_STOPPED;
4990	mtx_unlock(&lun->lun_lock);
4991
4992	return (0);
4993}
4994
4995int
4996ctl_stop_lun(struct ctl_be_lun *be_lun)
4997{
4998	struct ctl_softc *ctl_softc;
4999	struct ctl_lun *lun;
5000
5001	ctl_softc = control_softc;
5002
5003	lun = (struct ctl_lun *)be_lun->ctl_lun;
5004
5005	mtx_lock(&lun->lun_lock);
5006	lun->flags |= CTL_LUN_STOPPED;
5007	mtx_unlock(&lun->lun_lock);
5008
5009	return (0);
5010}
5011
5012int
5013ctl_lun_offline(struct ctl_be_lun *be_lun)
5014{
5015	struct ctl_softc *ctl_softc;
5016	struct ctl_lun *lun;
5017
5018	ctl_softc = control_softc;
5019
5020	lun = (struct ctl_lun *)be_lun->ctl_lun;
5021
5022	mtx_lock(&lun->lun_lock);
5023	lun->flags |= CTL_LUN_OFFLINE;
5024	mtx_unlock(&lun->lun_lock);
5025
5026	return (0);
5027}
5028
5029int
5030ctl_lun_online(struct ctl_be_lun *be_lun)
5031{
5032	struct ctl_softc *ctl_softc;
5033	struct ctl_lun *lun;
5034
5035	ctl_softc = control_softc;
5036
5037	lun = (struct ctl_lun *)be_lun->ctl_lun;
5038
5039	mtx_lock(&lun->lun_lock);
5040	lun->flags &= ~CTL_LUN_OFFLINE;
5041	mtx_unlock(&lun->lun_lock);
5042
5043	return (0);
5044}
5045
5046int
5047ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5048{
5049	struct ctl_softc *ctl_softc;
5050	struct ctl_lun *lun;
5051
5052	ctl_softc = control_softc;
5053
5054	lun = (struct ctl_lun *)be_lun->ctl_lun;
5055
5056	mtx_lock(&lun->lun_lock);
5057
5058	/*
5059	 * The LUN needs to be disabled before it can be marked invalid.
5060	 */
5061	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5062		mtx_unlock(&lun->lun_lock);
5063		return (-1);
5064	}
5065	/*
5066	 * Mark the LUN invalid.
5067	 */
5068	lun->flags |= CTL_LUN_INVALID;
5069
5070	/*
5071	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5072	 * If we have something in the OOA queue, we'll free it when the
5073	 * last I/O completes.
5074	 */
5075	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5076		mtx_unlock(&lun->lun_lock);
5077		mtx_lock(&ctl_softc->ctl_lock);
5078		ctl_free_lun(lun);
5079		mtx_unlock(&ctl_softc->ctl_lock);
5080	} else
5081		mtx_unlock(&lun->lun_lock);
5082
5083	return (0);
5084}
5085
5086int
5087ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5088{
5089	struct ctl_softc *ctl_softc;
5090	struct ctl_lun *lun;
5091
5092	ctl_softc = control_softc;
5093	lun = (struct ctl_lun *)be_lun->ctl_lun;
5094
5095	mtx_lock(&lun->lun_lock);
5096	lun->flags |= CTL_LUN_INOPERABLE;
5097	mtx_unlock(&lun->lun_lock);
5098
5099	return (0);
5100}
5101
5102int
5103ctl_lun_operable(struct ctl_be_lun *be_lun)
5104{
5105	struct ctl_softc *ctl_softc;
5106	struct ctl_lun *lun;
5107
5108	ctl_softc = control_softc;
5109	lun = (struct ctl_lun *)be_lun->ctl_lun;
5110
5111	mtx_lock(&lun->lun_lock);
5112	lun->flags &= ~CTL_LUN_INOPERABLE;
5113	mtx_unlock(&lun->lun_lock);
5114
5115	return (0);
5116}
5117
5118int
5119ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5120		   int lock)
5121{
5122	struct ctl_softc *softc;
5123	struct ctl_lun *lun;
5124	struct copan_aps_subpage *current_sp;
5125	struct ctl_page_index *page_index;
5126	int i;
5127
5128	softc = control_softc;
5129
5130	mtx_lock(&softc->ctl_lock);
5131
5132	lun = (struct ctl_lun *)be_lun->ctl_lun;
5133	mtx_lock(&lun->lun_lock);
5134
5135	page_index = NULL;
5136	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5137		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5138		     APS_PAGE_CODE)
5139			continue;
5140
5141		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5142			continue;
5143		page_index = &lun->mode_pages.index[i];
5144	}
5145
5146	if (page_index == NULL) {
5147		mtx_unlock(&lun->lun_lock);
5148		mtx_unlock(&softc->ctl_lock);
5149		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5150		       (uintmax_t)lun->lun);
5151		return (1);
5152	}
5153#if 0
5154	if ((softc->aps_locked_lun != 0)
5155	 && (softc->aps_locked_lun != lun->lun)) {
5156		printf("%s: attempt to lock LUN %llu when %llu is already "
5157		       "locked\n");
5158		mtx_unlock(&lun->lun_lock);
5159		mtx_unlock(&softc->ctl_lock);
5160		return (1);
5161	}
5162#endif
5163
5164	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5165		(page_index->page_len * CTL_PAGE_CURRENT));
5166
5167	if (lock != 0) {
5168		current_sp->lock_active = APS_LOCK_ACTIVE;
5169		softc->aps_locked_lun = lun->lun;
5170	} else {
5171		current_sp->lock_active = 0;
5172		softc->aps_locked_lun = 0;
5173	}
5174
5175
5176	/*
5177	 * If we're in HA mode, try to send the lock message to the other
5178	 * side.
5179	 */
5180	if (ctl_is_single == 0) {
5181		int isc_retval;
5182		union ctl_ha_msg lock_msg;
5183
5184		lock_msg.hdr.nexus = *nexus;
5185		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5186		if (lock != 0)
5187			lock_msg.aps.lock_flag = 1;
5188		else
5189			lock_msg.aps.lock_flag = 0;
5190		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5191					 sizeof(lock_msg), 0);
5192		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5193			printf("%s: APS (lock=%d) error returned from "
5194			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5195			mtx_unlock(&lun->lun_lock);
5196			mtx_unlock(&softc->ctl_lock);
5197			return (1);
5198		}
5199	}
5200
5201	mtx_unlock(&lun->lun_lock);
5202	mtx_unlock(&softc->ctl_lock);
5203
5204	return (0);
5205}
5206
5207void
5208ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5209{
5210	struct ctl_lun *lun;
5211	struct ctl_softc *softc;
5212	int i;
5213
5214	softc = control_softc;
5215
5216	lun = (struct ctl_lun *)be_lun->ctl_lun;
5217
5218	mtx_lock(&lun->lun_lock);
5219
5220	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5221		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5222
5223	mtx_unlock(&lun->lun_lock);
5224}
5225
5226/*
5227 * Backend "memory move is complete" callback for requests that never
5228 * make it down to say RAIDCore's configuration code.
5229 */
5230int
5231ctl_config_move_done(union ctl_io *io)
5232{
5233	int retval;
5234
5235	retval = CTL_RETVAL_COMPLETE;
5236
5237
5238	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5239	/*
5240	 * XXX KDM this shouldn't happen, but what if it does?
5241	 */
5242	if (io->io_hdr.io_type != CTL_IO_SCSI)
5243		panic("I/O type isn't CTL_IO_SCSI!");
5244
5245	if ((io->io_hdr.port_status == 0)
5246	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5247	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5248		io->io_hdr.status = CTL_SUCCESS;
5249	else if ((io->io_hdr.port_status != 0)
5250	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5251	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5252		/*
5253		 * For hardware error sense keys, the sense key
5254		 * specific value is defined to be a retry count,
5255		 * but we use it to pass back an internal FETD
5256		 * error code.  XXX KDM  Hopefully the FETD is only
5257		 * using 16 bits for an error code, since that's
5258		 * all the space we have in the sks field.
5259		 */
5260		ctl_set_internal_failure(&io->scsiio,
5261					 /*sks_valid*/ 1,
5262					 /*retry_count*/
5263					 io->io_hdr.port_status);
5264		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5265			free(io->scsiio.kern_data_ptr, M_CTL);
5266		ctl_done(io);
5267		goto bailout;
5268	}
5269
5270	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5271	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5272	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5273		/*
5274		 * XXX KDM just assuming a single pointer here, and not a
5275		 * S/G list.  If we start using S/G lists for config data,
5276		 * we'll need to know how to clean them up here as well.
5277		 */
5278		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5279			free(io->scsiio.kern_data_ptr, M_CTL);
5280		/* Hopefully the user has already set the status... */
5281		ctl_done(io);
5282	} else {
5283		/*
5284		 * XXX KDM now we need to continue data movement.  Some
5285		 * options:
5286		 * - call ctl_scsiio() again?  We don't do this for data
5287		 *   writes, because for those at least we know ahead of
5288		 *   time where the write will go and how long it is.  For
5289		 *   config writes, though, that information is largely
5290		 *   contained within the write itself, thus we need to
5291		 *   parse out the data again.
5292		 *
5293		 * - Call some other function once the data is in?
5294		 */
5295
5296		/*
5297		 * XXX KDM call ctl_scsiio() again for now, and check flag
5298		 * bits to see whether we're allocated or not.
5299		 */
5300		retval = ctl_scsiio(&io->scsiio);
5301	}
5302bailout:
5303	return (retval);
5304}
5305
5306/*
5307 * This gets called by a backend driver when it is done with a
5308 * data_submit method.
5309 */
5310void
5311ctl_data_submit_done(union ctl_io *io)
5312{
5313	/*
5314	 * If the IO_CONT flag is set, we need to call the supplied
5315	 * function to continue processing the I/O, instead of completing
5316	 * the I/O just yet.
5317	 *
5318	 * If there is an error, though, we don't want to keep processing.
5319	 * Instead, just send status back to the initiator.
5320	 */
5321	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5322	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5323	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5324	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5325		io->scsiio.io_cont(io);
5326		return;
5327	}
5328	ctl_done(io);
5329}
5330
5331/*
5332 * This gets called by a backend driver when it is done with a
5333 * configuration write.
5334 */
5335void
5336ctl_config_write_done(union ctl_io *io)
5337{
5338	uint8_t *buf;
5339
5340	/*
5341	 * If the IO_CONT flag is set, we need to call the supplied
5342	 * function to continue processing the I/O, instead of completing
5343	 * the I/O just yet.
5344	 *
5345	 * If there is an error, though, we don't want to keep processing.
5346	 * Instead, just send status back to the initiator.
5347	 */
5348	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5349	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5350	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5351	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5352		io->scsiio.io_cont(io);
5353		return;
5354	}
5355	/*
5356	 * Since a configuration write can be done for commands that actually
5357	 * have data allocated, like write buffer, and commands that have
5358	 * no data, like start/stop unit, we need to check here.
5359	 */
5360	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5361		buf = io->scsiio.kern_data_ptr;
5362	else
5363		buf = NULL;
5364	ctl_done(io);
5365	if (buf)
5366		free(buf, M_CTL);
5367}
5368
5369/*
5370 * SCSI release command.
5371 */
5372int
5373ctl_scsi_release(struct ctl_scsiio *ctsio)
5374{
5375	int length, longid, thirdparty_id, resv_id;
5376	struct ctl_softc *ctl_softc;
5377	struct ctl_lun *lun;
5378	uint32_t residx;
5379
5380	length = 0;
5381	resv_id = 0;
5382
5383	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5384
5385	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5386	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5387	ctl_softc = control_softc;
5388
5389	switch (ctsio->cdb[0]) {
5390	case RELEASE_10: {
5391		struct scsi_release_10 *cdb;
5392
5393		cdb = (struct scsi_release_10 *)ctsio->cdb;
5394
5395		if (cdb->byte2 & SR10_LONGID)
5396			longid = 1;
5397		else
5398			thirdparty_id = cdb->thirdparty_id;
5399
5400		resv_id = cdb->resv_id;
5401		length = scsi_2btoul(cdb->length);
5402		break;
5403	}
5404	}
5405
5406
5407	/*
5408	 * XXX KDM right now, we only support LUN reservation.  We don't
5409	 * support 3rd party reservations, or extent reservations, which
5410	 * might actually need the parameter list.  If we've gotten this
5411	 * far, we've got a LUN reservation.  Anything else got kicked out
5412	 * above.  So, according to SPC, ignore the length.
5413	 */
5414	length = 0;
5415
5416	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5417	 && (length > 0)) {
5418		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5419		ctsio->kern_data_len = length;
5420		ctsio->kern_total_len = length;
5421		ctsio->kern_data_resid = 0;
5422		ctsio->kern_rel_offset = 0;
5423		ctsio->kern_sg_entries = 0;
5424		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5425		ctsio->be_move_done = ctl_config_move_done;
5426		ctl_datamove((union ctl_io *)ctsio);
5427
5428		return (CTL_RETVAL_COMPLETE);
5429	}
5430
5431	if (length > 0)
5432		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5433
5434	mtx_lock(&lun->lun_lock);
5435
5436	/*
5437	 * According to SPC, it is not an error for an intiator to attempt
5438	 * to release a reservation on a LUN that isn't reserved, or that
5439	 * is reserved by another initiator.  The reservation can only be
5440	 * released, though, by the initiator who made it or by one of
5441	 * several reset type events.
5442	 */
5443	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5444			lun->flags &= ~CTL_LUN_RESERVED;
5445
5446	mtx_unlock(&lun->lun_lock);
5447
5448	ctsio->scsi_status = SCSI_STATUS_OK;
5449	ctsio->io_hdr.status = CTL_SUCCESS;
5450
5451	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5452		free(ctsio->kern_data_ptr, M_CTL);
5453		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5454	}
5455
5456	ctl_done((union ctl_io *)ctsio);
5457	return (CTL_RETVAL_COMPLETE);
5458}
5459
5460int
5461ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5462{
5463	int extent, thirdparty, longid;
5464	int resv_id, length;
5465	uint64_t thirdparty_id;
5466	struct ctl_softc *ctl_softc;
5467	struct ctl_lun *lun;
5468	uint32_t residx;
5469
5470	extent = 0;
5471	thirdparty = 0;
5472	longid = 0;
5473	resv_id = 0;
5474	length = 0;
5475	thirdparty_id = 0;
5476
5477	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5478
5479	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5480	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5481	ctl_softc = control_softc;
5482
5483	switch (ctsio->cdb[0]) {
5484	case RESERVE_10: {
5485		struct scsi_reserve_10 *cdb;
5486
5487		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5488
5489		if (cdb->byte2 & SR10_LONGID)
5490			longid = 1;
5491		else
5492			thirdparty_id = cdb->thirdparty_id;
5493
5494		resv_id = cdb->resv_id;
5495		length = scsi_2btoul(cdb->length);
5496		break;
5497	}
5498	}
5499
5500	/*
5501	 * XXX KDM right now, we only support LUN reservation.  We don't
5502	 * support 3rd party reservations, or extent reservations, which
5503	 * might actually need the parameter list.  If we've gotten this
5504	 * far, we've got a LUN reservation.  Anything else got kicked out
5505	 * above.  So, according to SPC, ignore the length.
5506	 */
5507	length = 0;
5508
5509	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5510	 && (length > 0)) {
5511		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5512		ctsio->kern_data_len = length;
5513		ctsio->kern_total_len = length;
5514		ctsio->kern_data_resid = 0;
5515		ctsio->kern_rel_offset = 0;
5516		ctsio->kern_sg_entries = 0;
5517		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5518		ctsio->be_move_done = ctl_config_move_done;
5519		ctl_datamove((union ctl_io *)ctsio);
5520
5521		return (CTL_RETVAL_COMPLETE);
5522	}
5523
5524	if (length > 0)
5525		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5526
5527	mtx_lock(&lun->lun_lock);
5528	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5529		ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5530		ctsio->io_hdr.status = CTL_SCSI_ERROR;
5531		goto bailout;
5532	}
5533
5534	lun->flags |= CTL_LUN_RESERVED;
5535	lun->res_idx = residx;
5536
5537	ctsio->scsi_status = SCSI_STATUS_OK;
5538	ctsio->io_hdr.status = CTL_SUCCESS;
5539
5540bailout:
5541	mtx_unlock(&lun->lun_lock);
5542
5543	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5544		free(ctsio->kern_data_ptr, M_CTL);
5545		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5546	}
5547
5548	ctl_done((union ctl_io *)ctsio);
5549	return (CTL_RETVAL_COMPLETE);
5550}
5551
5552int
5553ctl_start_stop(struct ctl_scsiio *ctsio)
5554{
5555	struct scsi_start_stop_unit *cdb;
5556	struct ctl_lun *lun;
5557	struct ctl_softc *ctl_softc;
5558	int retval;
5559
5560	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5561
5562	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5563	ctl_softc = control_softc;
5564	retval = 0;
5565
5566	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5567
5568	/*
5569	 * XXX KDM
5570	 * We don't support the immediate bit on a stop unit.  In order to
5571	 * do that, we would need to code up a way to know that a stop is
5572	 * pending, and hold off any new commands until it completes, one
5573	 * way or another.  Then we could accept or reject those commands
5574	 * depending on its status.  We would almost need to do the reverse
5575	 * of what we do below for an immediate start -- return the copy of
5576	 * the ctl_io to the FETD with status to send to the host (and to
5577	 * free the copy!) and then free the original I/O once the stop
5578	 * actually completes.  That way, the OOA queue mechanism can work
5579	 * to block commands that shouldn't proceed.  Another alternative
5580	 * would be to put the copy in the queue in place of the original,
5581	 * and return the original back to the caller.  That could be
5582	 * slightly safer..
5583	 */
5584	if ((cdb->byte2 & SSS_IMMED)
5585	 && ((cdb->how & SSS_START) == 0)) {
5586		ctl_set_invalid_field(ctsio,
5587				      /*sks_valid*/ 1,
5588				      /*command*/ 1,
5589				      /*field*/ 1,
5590				      /*bit_valid*/ 1,
5591				      /*bit*/ 0);
5592		ctl_done((union ctl_io *)ctsio);
5593		return (CTL_RETVAL_COMPLETE);
5594	}
5595
5596	if ((lun->flags & CTL_LUN_PR_RESERVED)
5597	 && ((cdb->how & SSS_START)==0)) {
5598		uint32_t residx;
5599
5600		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5601		if (lun->pr_keys[residx] == 0
5602		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5603
5604			ctl_set_reservation_conflict(ctsio);
5605			ctl_done((union ctl_io *)ctsio);
5606			return (CTL_RETVAL_COMPLETE);
5607		}
5608	}
5609
5610	/*
5611	 * If there is no backend on this device, we can't start or stop
5612	 * it.  In theory we shouldn't get any start/stop commands in the
5613	 * first place at this level if the LUN doesn't have a backend.
5614	 * That should get stopped by the command decode code.
5615	 */
5616	if (lun->backend == NULL) {
5617		ctl_set_invalid_opcode(ctsio);
5618		ctl_done((union ctl_io *)ctsio);
5619		return (CTL_RETVAL_COMPLETE);
5620	}
5621
5622	/*
5623	 * XXX KDM Copan-specific offline behavior.
5624	 * Figure out a reasonable way to port this?
5625	 */
5626#ifdef NEEDTOPORT
5627	mtx_lock(&lun->lun_lock);
5628
5629	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5630	 && (lun->flags & CTL_LUN_OFFLINE)) {
5631		/*
5632		 * If the LUN is offline, and the on/offline bit isn't set,
5633		 * reject the start or stop.  Otherwise, let it through.
5634		 */
5635		mtx_unlock(&lun->lun_lock);
5636		ctl_set_lun_not_ready(ctsio);
5637		ctl_done((union ctl_io *)ctsio);
5638	} else {
5639		mtx_unlock(&lun->lun_lock);
5640#endif /* NEEDTOPORT */
5641		/*
5642		 * This could be a start or a stop when we're online,
5643		 * or a stop/offline or start/online.  A start or stop when
5644		 * we're offline is covered in the case above.
5645		 */
5646		/*
5647		 * In the non-immediate case, we send the request to
5648		 * the backend and return status to the user when
5649		 * it is done.
5650		 *
5651		 * In the immediate case, we allocate a new ctl_io
5652		 * to hold a copy of the request, and send that to
5653		 * the backend.  We then set good status on the
5654		 * user's request and return it immediately.
5655		 */
5656		if (cdb->byte2 & SSS_IMMED) {
5657			union ctl_io *new_io;
5658
5659			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5660			if (new_io == NULL) {
5661				ctl_set_busy(ctsio);
5662				ctl_done((union ctl_io *)ctsio);
5663			} else {
5664				ctl_copy_io((union ctl_io *)ctsio,
5665					    new_io);
5666				retval = lun->backend->config_write(new_io);
5667				ctl_set_success(ctsio);
5668				ctl_done((union ctl_io *)ctsio);
5669			}
5670		} else {
5671			retval = lun->backend->config_write(
5672				(union ctl_io *)ctsio);
5673		}
5674#ifdef NEEDTOPORT
5675	}
5676#endif
5677	return (retval);
5678}
5679
5680/*
5681 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5682 * we don't really do anything with the LBA and length fields if the user
5683 * passes them in.  Instead we'll just flush out the cache for the entire
5684 * LUN.
5685 */
5686int
5687ctl_sync_cache(struct ctl_scsiio *ctsio)
5688{
5689	struct ctl_lun *lun;
5690	struct ctl_softc *ctl_softc;
5691	uint64_t starting_lba;
5692	uint32_t block_count;
5693	int retval;
5694
5695	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5696
5697	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5698	ctl_softc = control_softc;
5699	retval = 0;
5700
5701	switch (ctsio->cdb[0]) {
5702	case SYNCHRONIZE_CACHE: {
5703		struct scsi_sync_cache *cdb;
5704		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5705
5706		starting_lba = scsi_4btoul(cdb->begin_lba);
5707		block_count = scsi_2btoul(cdb->lb_count);
5708		break;
5709	}
5710	case SYNCHRONIZE_CACHE_16: {
5711		struct scsi_sync_cache_16 *cdb;
5712		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5713
5714		starting_lba = scsi_8btou64(cdb->begin_lba);
5715		block_count = scsi_4btoul(cdb->lb_count);
5716		break;
5717	}
5718	default:
5719		ctl_set_invalid_opcode(ctsio);
5720		ctl_done((union ctl_io *)ctsio);
5721		goto bailout;
5722		break; /* NOTREACHED */
5723	}
5724
5725	/*
5726	 * We check the LBA and length, but don't do anything with them.
5727	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5728	 * get flushed.  This check will just help satisfy anyone who wants
5729	 * to see an error for an out of range LBA.
5730	 */
5731	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5732		ctl_set_lba_out_of_range(ctsio);
5733		ctl_done((union ctl_io *)ctsio);
5734		goto bailout;
5735	}
5736
5737	/*
5738	 * If this LUN has no backend, we can't flush the cache anyway.
5739	 */
5740	if (lun->backend == NULL) {
5741		ctl_set_invalid_opcode(ctsio);
5742		ctl_done((union ctl_io *)ctsio);
5743		goto bailout;
5744	}
5745
5746	/*
5747	 * Check to see whether we're configured to send the SYNCHRONIZE
5748	 * CACHE command directly to the back end.
5749	 */
5750	mtx_lock(&lun->lun_lock);
5751	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5752	 && (++(lun->sync_count) >= lun->sync_interval)) {
5753		lun->sync_count = 0;
5754		mtx_unlock(&lun->lun_lock);
5755		retval = lun->backend->config_write((union ctl_io *)ctsio);
5756	} else {
5757		mtx_unlock(&lun->lun_lock);
5758		ctl_set_success(ctsio);
5759		ctl_done((union ctl_io *)ctsio);
5760	}
5761
5762bailout:
5763
5764	return (retval);
5765}
5766
5767int
5768ctl_format(struct ctl_scsiio *ctsio)
5769{
5770	struct scsi_format *cdb;
5771	struct ctl_lun *lun;
5772	struct ctl_softc *ctl_softc;
5773	int length, defect_list_len;
5774
5775	CTL_DEBUG_PRINT(("ctl_format\n"));
5776
5777	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5778	ctl_softc = control_softc;
5779
5780	cdb = (struct scsi_format *)ctsio->cdb;
5781
5782	length = 0;
5783	if (cdb->byte2 & SF_FMTDATA) {
5784		if (cdb->byte2 & SF_LONGLIST)
5785			length = sizeof(struct scsi_format_header_long);
5786		else
5787			length = sizeof(struct scsi_format_header_short);
5788	}
5789
5790	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5791	 && (length > 0)) {
5792		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5793		ctsio->kern_data_len = length;
5794		ctsio->kern_total_len = length;
5795		ctsio->kern_data_resid = 0;
5796		ctsio->kern_rel_offset = 0;
5797		ctsio->kern_sg_entries = 0;
5798		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5799		ctsio->be_move_done = ctl_config_move_done;
5800		ctl_datamove((union ctl_io *)ctsio);
5801
5802		return (CTL_RETVAL_COMPLETE);
5803	}
5804
5805	defect_list_len = 0;
5806
5807	if (cdb->byte2 & SF_FMTDATA) {
5808		if (cdb->byte2 & SF_LONGLIST) {
5809			struct scsi_format_header_long *header;
5810
5811			header = (struct scsi_format_header_long *)
5812				ctsio->kern_data_ptr;
5813
5814			defect_list_len = scsi_4btoul(header->defect_list_len);
5815			if (defect_list_len != 0) {
5816				ctl_set_invalid_field(ctsio,
5817						      /*sks_valid*/ 1,
5818						      /*command*/ 0,
5819						      /*field*/ 2,
5820						      /*bit_valid*/ 0,
5821						      /*bit*/ 0);
5822				goto bailout;
5823			}
5824		} else {
5825			struct scsi_format_header_short *header;
5826
5827			header = (struct scsi_format_header_short *)
5828				ctsio->kern_data_ptr;
5829
5830			defect_list_len = scsi_2btoul(header->defect_list_len);
5831			if (defect_list_len != 0) {
5832				ctl_set_invalid_field(ctsio,
5833						      /*sks_valid*/ 1,
5834						      /*command*/ 0,
5835						      /*field*/ 2,
5836						      /*bit_valid*/ 0,
5837						      /*bit*/ 0);
5838				goto bailout;
5839			}
5840		}
5841	}
5842
5843	/*
5844	 * The format command will clear out the "Medium format corrupted"
5845	 * status if set by the configuration code.  That status is really
5846	 * just a way to notify the host that we have lost the media, and
5847	 * get them to issue a command that will basically make them think
5848	 * they're blowing away the media.
5849	 */
5850	mtx_lock(&lun->lun_lock);
5851	lun->flags &= ~CTL_LUN_INOPERABLE;
5852	mtx_unlock(&lun->lun_lock);
5853
5854	ctsio->scsi_status = SCSI_STATUS_OK;
5855	ctsio->io_hdr.status = CTL_SUCCESS;
5856bailout:
5857
5858	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5859		free(ctsio->kern_data_ptr, M_CTL);
5860		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5861	}
5862
5863	ctl_done((union ctl_io *)ctsio);
5864	return (CTL_RETVAL_COMPLETE);
5865}
5866
5867int
5868ctl_read_buffer(struct ctl_scsiio *ctsio)
5869{
5870	struct scsi_read_buffer *cdb;
5871	struct ctl_lun *lun;
5872	int buffer_offset, len;
5873	static uint8_t descr[4];
5874	static uint8_t echo_descr[4] = { 0 };
5875
5876	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5877
5878	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5879	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5880
5881	if (lun->flags & CTL_LUN_PR_RESERVED) {
5882		uint32_t residx;
5883
5884		/*
5885		 * XXX KDM need a lock here.
5886		 */
5887		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5888		if ((lun->res_type == SPR_TYPE_EX_AC
5889		  && residx != lun->pr_res_idx)
5890		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5891		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5892		  && lun->pr_keys[residx] == 0)) {
5893			ctl_set_reservation_conflict(ctsio);
5894			ctl_done((union ctl_io *)ctsio);
5895			return (CTL_RETVAL_COMPLETE);
5896	        }
5897	}
5898
5899	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5900	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5901	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5902		ctl_set_invalid_field(ctsio,
5903				      /*sks_valid*/ 1,
5904				      /*command*/ 1,
5905				      /*field*/ 1,
5906				      /*bit_valid*/ 1,
5907				      /*bit*/ 4);
5908		ctl_done((union ctl_io *)ctsio);
5909		return (CTL_RETVAL_COMPLETE);
5910	}
5911
5912	len = scsi_3btoul(cdb->length);
5913	buffer_offset = scsi_3btoul(cdb->offset);
5914
5915	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5916		ctl_set_invalid_field(ctsio,
5917				      /*sks_valid*/ 1,
5918				      /*command*/ 1,
5919				      /*field*/ 6,
5920				      /*bit_valid*/ 0,
5921				      /*bit*/ 0);
5922		ctl_done((union ctl_io *)ctsio);
5923		return (CTL_RETVAL_COMPLETE);
5924	}
5925
5926	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5927		descr[0] = 0;
5928		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5929		ctsio->kern_data_ptr = descr;
5930		len = min(len, sizeof(descr));
5931	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5932		ctsio->kern_data_ptr = echo_descr;
5933		len = min(len, sizeof(echo_descr));
5934	} else
5935		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5936	ctsio->kern_data_len = len;
5937	ctsio->kern_total_len = len;
5938	ctsio->kern_data_resid = 0;
5939	ctsio->kern_rel_offset = 0;
5940	ctsio->kern_sg_entries = 0;
5941	ctsio->be_move_done = ctl_config_move_done;
5942	ctl_datamove((union ctl_io *)ctsio);
5943
5944	return (CTL_RETVAL_COMPLETE);
5945}
5946
5947int
5948ctl_write_buffer(struct ctl_scsiio *ctsio)
5949{
5950	struct scsi_write_buffer *cdb;
5951	struct ctl_lun *lun;
5952	int buffer_offset, len;
5953
5954	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5955
5956	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5957	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5958
5959	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5960		ctl_set_invalid_field(ctsio,
5961				      /*sks_valid*/ 1,
5962				      /*command*/ 1,
5963				      /*field*/ 1,
5964				      /*bit_valid*/ 1,
5965				      /*bit*/ 4);
5966		ctl_done((union ctl_io *)ctsio);
5967		return (CTL_RETVAL_COMPLETE);
5968	}
5969
5970	len = scsi_3btoul(cdb->length);
5971	buffer_offset = scsi_3btoul(cdb->offset);
5972
5973	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5974		ctl_set_invalid_field(ctsio,
5975				      /*sks_valid*/ 1,
5976				      /*command*/ 1,
5977				      /*field*/ 6,
5978				      /*bit_valid*/ 0,
5979				      /*bit*/ 0);
5980		ctl_done((union ctl_io *)ctsio);
5981		return (CTL_RETVAL_COMPLETE);
5982	}
5983
5984	/*
5985	 * If we've got a kernel request that hasn't been malloced yet,
5986	 * malloc it and tell the caller the data buffer is here.
5987	 */
5988	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5989		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5990		ctsio->kern_data_len = len;
5991		ctsio->kern_total_len = len;
5992		ctsio->kern_data_resid = 0;
5993		ctsio->kern_rel_offset = 0;
5994		ctsio->kern_sg_entries = 0;
5995		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5996		ctsio->be_move_done = ctl_config_move_done;
5997		ctl_datamove((union ctl_io *)ctsio);
5998
5999		return (CTL_RETVAL_COMPLETE);
6000	}
6001
6002	ctl_done((union ctl_io *)ctsio);
6003
6004	return (CTL_RETVAL_COMPLETE);
6005}
6006
6007int
6008ctl_write_same(struct ctl_scsiio *ctsio)
6009{
6010	struct ctl_lun *lun;
6011	struct ctl_lba_len_flags *lbalen;
6012	uint64_t lba;
6013	uint32_t num_blocks;
6014	int len, retval;
6015	uint8_t byte2;
6016
6017	retval = CTL_RETVAL_COMPLETE;
6018
6019	CTL_DEBUG_PRINT(("ctl_write_same\n"));
6020
6021	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6022
6023	switch (ctsio->cdb[0]) {
6024	case WRITE_SAME_10: {
6025		struct scsi_write_same_10 *cdb;
6026
6027		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
6028
6029		lba = scsi_4btoul(cdb->addr);
6030		num_blocks = scsi_2btoul(cdb->length);
6031		byte2 = cdb->byte2;
6032		break;
6033	}
6034	case WRITE_SAME_16: {
6035		struct scsi_write_same_16 *cdb;
6036
6037		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
6038
6039		lba = scsi_8btou64(cdb->addr);
6040		num_blocks = scsi_4btoul(cdb->length);
6041		byte2 = cdb->byte2;
6042		break;
6043	}
6044	default:
6045		/*
6046		 * We got a command we don't support.  This shouldn't
6047		 * happen, commands should be filtered out above us.
6048		 */
6049		ctl_set_invalid_opcode(ctsio);
6050		ctl_done((union ctl_io *)ctsio);
6051
6052		return (CTL_RETVAL_COMPLETE);
6053		break; /* NOTREACHED */
6054	}
6055
6056	/* NDOB and ANCHOR flags can be used only together with UNMAP */
6057	if ((byte2 & SWS_UNMAP) == 0 &&
6058	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
6059		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6060		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6061		ctl_done((union ctl_io *)ctsio);
6062		return (CTL_RETVAL_COMPLETE);
6063	}
6064
6065	/*
6066	 * The first check is to make sure we're in bounds, the second
6067	 * check is to catch wrap-around problems.  If the lba + num blocks
6068	 * is less than the lba, then we've wrapped around and the block
6069	 * range is invalid anyway.
6070	 */
6071	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6072	 || ((lba + num_blocks) < lba)) {
6073		ctl_set_lba_out_of_range(ctsio);
6074		ctl_done((union ctl_io *)ctsio);
6075		return (CTL_RETVAL_COMPLETE);
6076	}
6077
6078	/* Zero number of blocks means "to the last logical block" */
6079	if (num_blocks == 0) {
6080		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6081			ctl_set_invalid_field(ctsio,
6082					      /*sks_valid*/ 0,
6083					      /*command*/ 1,
6084					      /*field*/ 0,
6085					      /*bit_valid*/ 0,
6086					      /*bit*/ 0);
6087			ctl_done((union ctl_io *)ctsio);
6088			return (CTL_RETVAL_COMPLETE);
6089		}
6090		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6091	}
6092
6093	len = lun->be_lun->blocksize;
6094
6095	/*
6096	 * If we've got a kernel request that hasn't been malloced yet,
6097	 * malloc it and tell the caller the data buffer is here.
6098	 */
6099	if ((byte2 & SWS_NDOB) == 0 &&
6100	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6101		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6102		ctsio->kern_data_len = len;
6103		ctsio->kern_total_len = len;
6104		ctsio->kern_data_resid = 0;
6105		ctsio->kern_rel_offset = 0;
6106		ctsio->kern_sg_entries = 0;
6107		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6108		ctsio->be_move_done = ctl_config_move_done;
6109		ctl_datamove((union ctl_io *)ctsio);
6110
6111		return (CTL_RETVAL_COMPLETE);
6112	}
6113
6114	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6115	lbalen->lba = lba;
6116	lbalen->len = num_blocks;
6117	lbalen->flags = byte2;
6118	retval = lun->backend->config_write((union ctl_io *)ctsio);
6119
6120	return (retval);
6121}
6122
6123int
6124ctl_unmap(struct ctl_scsiio *ctsio)
6125{
6126	struct ctl_lun *lun;
6127	struct scsi_unmap *cdb;
6128	struct ctl_ptr_len_flags *ptrlen;
6129	struct scsi_unmap_header *hdr;
6130	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6131	uint64_t lba;
6132	uint32_t num_blocks;
6133	int len, retval;
6134	uint8_t byte2;
6135
6136	retval = CTL_RETVAL_COMPLETE;
6137
6138	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6139
6140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6141	cdb = (struct scsi_unmap *)ctsio->cdb;
6142
6143	len = scsi_2btoul(cdb->length);
6144	byte2 = cdb->byte2;
6145
6146	/*
6147	 * If we've got a kernel request that hasn't been malloced yet,
6148	 * malloc it and tell the caller the data buffer is here.
6149	 */
6150	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6151		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6152		ctsio->kern_data_len = len;
6153		ctsio->kern_total_len = len;
6154		ctsio->kern_data_resid = 0;
6155		ctsio->kern_rel_offset = 0;
6156		ctsio->kern_sg_entries = 0;
6157		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6158		ctsio->be_move_done = ctl_config_move_done;
6159		ctl_datamove((union ctl_io *)ctsio);
6160
6161		return (CTL_RETVAL_COMPLETE);
6162	}
6163
6164	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6165	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6166	if (len < sizeof (*hdr) ||
6167	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6168	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6169	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6170		ctl_set_invalid_field(ctsio,
6171				      /*sks_valid*/ 0,
6172				      /*command*/ 0,
6173				      /*field*/ 0,
6174				      /*bit_valid*/ 0,
6175				      /*bit*/ 0);
6176		ctl_done((union ctl_io *)ctsio);
6177		return (CTL_RETVAL_COMPLETE);
6178	}
6179	len = scsi_2btoul(hdr->desc_length);
6180	buf = (struct scsi_unmap_desc *)(hdr + 1);
6181	end = buf + len / sizeof(*buf);
6182
6183	endnz = buf;
6184	for (range = buf; range < end; range++) {
6185		lba = scsi_8btou64(range->lba);
6186		num_blocks = scsi_4btoul(range->length);
6187		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6188		 || ((lba + num_blocks) < lba)) {
6189			ctl_set_lba_out_of_range(ctsio);
6190			ctl_done((union ctl_io *)ctsio);
6191			return (CTL_RETVAL_COMPLETE);
6192		}
6193		if (num_blocks != 0)
6194			endnz = range + 1;
6195	}
6196
6197	/*
6198	 * Block backend can not handle zero last range.
6199	 * Filter it out and return if there is nothing left.
6200	 */
6201	len = (uint8_t *)endnz - (uint8_t *)buf;
6202	if (len == 0) {
6203		ctl_set_success(ctsio);
6204		ctl_done((union ctl_io *)ctsio);
6205		return (CTL_RETVAL_COMPLETE);
6206	}
6207
6208	mtx_lock(&lun->lun_lock);
6209	ptrlen = (struct ctl_ptr_len_flags *)
6210	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6211	ptrlen->ptr = (void *)buf;
6212	ptrlen->len = len;
6213	ptrlen->flags = byte2;
6214	ctl_check_blocked(lun);
6215	mtx_unlock(&lun->lun_lock);
6216
6217	retval = lun->backend->config_write((union ctl_io *)ctsio);
6218	return (retval);
6219}
6220
6221/*
6222 * Note that this function currently doesn't actually do anything inside
6223 * CTL to enforce things if the DQue bit is turned on.
6224 *
6225 * Also note that this function can't be used in the default case, because
6226 * the DQue bit isn't set in the changeable mask for the control mode page
6227 * anyway.  This is just here as an example for how to implement a page
6228 * handler, and a placeholder in case we want to allow the user to turn
6229 * tagged queueing on and off.
6230 *
6231 * The D_SENSE bit handling is functional, however, and will turn
6232 * descriptor sense on and off for a given LUN.
6233 */
6234int
6235ctl_control_page_handler(struct ctl_scsiio *ctsio,
6236			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6237{
6238	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6239	struct ctl_lun *lun;
6240	struct ctl_softc *softc;
6241	int set_ua;
6242	uint32_t initidx;
6243
6244	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6245	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6246	set_ua = 0;
6247
6248	user_cp = (struct scsi_control_page *)page_ptr;
6249	current_cp = (struct scsi_control_page *)
6250		(page_index->page_data + (page_index->page_len *
6251		CTL_PAGE_CURRENT));
6252	saved_cp = (struct scsi_control_page *)
6253		(page_index->page_data + (page_index->page_len *
6254		CTL_PAGE_SAVED));
6255
6256	softc = control_softc;
6257
6258	mtx_lock(&lun->lun_lock);
6259	if (((current_cp->rlec & SCP_DSENSE) == 0)
6260	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6261		/*
6262		 * Descriptor sense is currently turned off and the user
6263		 * wants to turn it on.
6264		 */
6265		current_cp->rlec |= SCP_DSENSE;
6266		saved_cp->rlec |= SCP_DSENSE;
6267		lun->flags |= CTL_LUN_SENSE_DESC;
6268		set_ua = 1;
6269	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6270		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6271		/*
6272		 * Descriptor sense is currently turned on, and the user
6273		 * wants to turn it off.
6274		 */
6275		current_cp->rlec &= ~SCP_DSENSE;
6276		saved_cp->rlec &= ~SCP_DSENSE;
6277		lun->flags &= ~CTL_LUN_SENSE_DESC;
6278		set_ua = 1;
6279	}
6280	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6281	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6282		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6283		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6284		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6285		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6286		set_ua = 1;
6287	}
6288	if ((current_cp->eca_and_aen & SCP_SWP) !=
6289	    (user_cp->eca_and_aen & SCP_SWP)) {
6290		current_cp->eca_and_aen &= ~SCP_SWP;
6291		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6292		saved_cp->eca_and_aen &= ~SCP_SWP;
6293		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6294		set_ua = 1;
6295	}
6296	if (set_ua != 0) {
6297		int i;
6298		/*
6299		 * Let other initiators know that the mode
6300		 * parameters for this LUN have changed.
6301		 */
6302		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6303			if (i == initidx)
6304				continue;
6305
6306			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6307		}
6308	}
6309	mtx_unlock(&lun->lun_lock);
6310
6311	return (0);
6312}
6313
6314int
6315ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6316		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6317{
6318	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6319	struct ctl_lun *lun;
6320	int set_ua;
6321	uint32_t initidx;
6322
6323	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6324	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6325	set_ua = 0;
6326
6327	user_cp = (struct scsi_caching_page *)page_ptr;
6328	current_cp = (struct scsi_caching_page *)
6329		(page_index->page_data + (page_index->page_len *
6330		CTL_PAGE_CURRENT));
6331	saved_cp = (struct scsi_caching_page *)
6332		(page_index->page_data + (page_index->page_len *
6333		CTL_PAGE_SAVED));
6334
6335	mtx_lock(&lun->lun_lock);
6336	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6337	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6338		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6339		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6340		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6341		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6342		set_ua = 1;
6343	}
6344	if (set_ua != 0) {
6345		int i;
6346		/*
6347		 * Let other initiators know that the mode
6348		 * parameters for this LUN have changed.
6349		 */
6350		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6351			if (i == initidx)
6352				continue;
6353
6354			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6355		}
6356	}
6357	mtx_unlock(&lun->lun_lock);
6358
6359	return (0);
6360}
6361
6362int
6363ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6364		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6365{
6366	return (0);
6367}
6368
6369int
6370ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6371			   struct ctl_page_index *page_index, int pc)
6372{
6373	struct copan_power_subpage *page;
6374
6375	page = (struct copan_power_subpage *)page_index->page_data +
6376		(page_index->page_len * pc);
6377
6378	switch (pc) {
6379	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6380		/*
6381		 * We don't update the changable bits for this page.
6382		 */
6383		break;
6384	case SMS_PAGE_CTRL_CURRENT >> 6:
6385	case SMS_PAGE_CTRL_DEFAULT >> 6:
6386	case SMS_PAGE_CTRL_SAVED >> 6:
6387#ifdef NEEDTOPORT
6388		ctl_update_power_subpage(page);
6389#endif
6390		break;
6391	default:
6392#ifdef NEEDTOPORT
6393		EPRINT(0, "Invalid PC %d!!", pc);
6394#endif
6395		break;
6396	}
6397	return (0);
6398}
6399
6400
6401int
6402ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6403		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6404{
6405	struct copan_aps_subpage *user_sp;
6406	struct copan_aps_subpage *current_sp;
6407	union ctl_modepage_info *modepage_info;
6408	struct ctl_softc *softc;
6409	struct ctl_lun *lun;
6410	int retval;
6411
6412	retval = CTL_RETVAL_COMPLETE;
6413	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6414		     (page_index->page_len * CTL_PAGE_CURRENT));
6415	softc = control_softc;
6416	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6417
6418	user_sp = (struct copan_aps_subpage *)page_ptr;
6419
6420	modepage_info = (union ctl_modepage_info *)
6421		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6422
6423	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6424	modepage_info->header.subpage = page_index->subpage;
6425	modepage_info->aps.lock_active = user_sp->lock_active;
6426
6427	mtx_lock(&softc->ctl_lock);
6428
6429	/*
6430	 * If there is a request to lock the LUN and another LUN is locked
6431	 * this is an error. If the requested LUN is already locked ignore
6432	 * the request. If no LUN is locked attempt to lock it.
6433	 * if there is a request to unlock the LUN and the LUN is currently
6434	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6435	 * if another LUN is locked or no LUN is locked.
6436	 */
6437	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6438		if (softc->aps_locked_lun == lun->lun) {
6439			/*
6440			 * This LUN is already locked, so we're done.
6441			 */
6442			retval = CTL_RETVAL_COMPLETE;
6443		} else if (softc->aps_locked_lun == 0) {
6444			/*
6445			 * No one has the lock, pass the request to the
6446			 * backend.
6447			 */
6448			retval = lun->backend->config_write(
6449				(union ctl_io *)ctsio);
6450		} else {
6451			/*
6452			 * Someone else has the lock, throw out the request.
6453			 */
6454			ctl_set_already_locked(ctsio);
6455			free(ctsio->kern_data_ptr, M_CTL);
6456			ctl_done((union ctl_io *)ctsio);
6457
6458			/*
6459			 * Set the return value so that ctl_do_mode_select()
6460			 * won't try to complete the command.  We already
6461			 * completed it here.
6462			 */
6463			retval = CTL_RETVAL_ERROR;
6464		}
6465	} else if (softc->aps_locked_lun == lun->lun) {
6466		/*
6467		 * This LUN is locked, so pass the unlock request to the
6468		 * backend.
6469		 */
6470		retval = lun->backend->config_write((union ctl_io *)ctsio);
6471	}
6472	mtx_unlock(&softc->ctl_lock);
6473
6474	return (retval);
6475}
6476
6477int
6478ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6479				struct ctl_page_index *page_index,
6480				uint8_t *page_ptr)
6481{
6482	uint8_t *c;
6483	int i;
6484
6485	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6486	ctl_time_io_secs =
6487		(c[0] << 8) |
6488		(c[1] << 0) |
6489		0;
6490	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6491	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6492	printf("page data:");
6493	for (i=0; i<8; i++)
6494		printf(" %.2x",page_ptr[i]);
6495	printf("\n");
6496	return (0);
6497}
6498
6499int
6500ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6501			       struct ctl_page_index *page_index,
6502			       int pc)
6503{
6504	struct copan_debugconf_subpage *page;
6505
6506	page = (struct copan_debugconf_subpage *)page_index->page_data +
6507		(page_index->page_len * pc);
6508
6509	switch (pc) {
6510	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6511	case SMS_PAGE_CTRL_DEFAULT >> 6:
6512	case SMS_PAGE_CTRL_SAVED >> 6:
6513		/*
6514		 * We don't update the changable or default bits for this page.
6515		 */
6516		break;
6517	case SMS_PAGE_CTRL_CURRENT >> 6:
6518		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6519		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6520		break;
6521	default:
6522#ifdef NEEDTOPORT
6523		EPRINT(0, "Invalid PC %d!!", pc);
6524#endif /* NEEDTOPORT */
6525		break;
6526	}
6527	return (0);
6528}
6529
6530
6531static int
6532ctl_do_mode_select(union ctl_io *io)
6533{
6534	struct scsi_mode_page_header *page_header;
6535	struct ctl_page_index *page_index;
6536	struct ctl_scsiio *ctsio;
6537	int control_dev, page_len;
6538	int page_len_offset, page_len_size;
6539	union ctl_modepage_info *modepage_info;
6540	struct ctl_lun *lun;
6541	int *len_left, *len_used;
6542	int retval, i;
6543
6544	ctsio = &io->scsiio;
6545	page_index = NULL;
6546	page_len = 0;
6547	retval = CTL_RETVAL_COMPLETE;
6548
6549	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6550
6551	if (lun->be_lun->lun_type != T_DIRECT)
6552		control_dev = 1;
6553	else
6554		control_dev = 0;
6555
6556	modepage_info = (union ctl_modepage_info *)
6557		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6558	len_left = &modepage_info->header.len_left;
6559	len_used = &modepage_info->header.len_used;
6560
6561do_next_page:
6562
6563	page_header = (struct scsi_mode_page_header *)
6564		(ctsio->kern_data_ptr + *len_used);
6565
6566	if (*len_left == 0) {
6567		free(ctsio->kern_data_ptr, M_CTL);
6568		ctl_set_success(ctsio);
6569		ctl_done((union ctl_io *)ctsio);
6570		return (CTL_RETVAL_COMPLETE);
6571	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6572
6573		free(ctsio->kern_data_ptr, M_CTL);
6574		ctl_set_param_len_error(ctsio);
6575		ctl_done((union ctl_io *)ctsio);
6576		return (CTL_RETVAL_COMPLETE);
6577
6578	} else if ((page_header->page_code & SMPH_SPF)
6579		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6580
6581		free(ctsio->kern_data_ptr, M_CTL);
6582		ctl_set_param_len_error(ctsio);
6583		ctl_done((union ctl_io *)ctsio);
6584		return (CTL_RETVAL_COMPLETE);
6585	}
6586
6587
6588	/*
6589	 * XXX KDM should we do something with the block descriptor?
6590	 */
6591	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6592
6593		if ((control_dev != 0)
6594		 && (lun->mode_pages.index[i].page_flags &
6595		     CTL_PAGE_FLAG_DISK_ONLY))
6596			continue;
6597
6598		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6599		    (page_header->page_code & SMPH_PC_MASK))
6600			continue;
6601
6602		/*
6603		 * If neither page has a subpage code, then we've got a
6604		 * match.
6605		 */
6606		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6607		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6608			page_index = &lun->mode_pages.index[i];
6609			page_len = page_header->page_length;
6610			break;
6611		}
6612
6613		/*
6614		 * If both pages have subpages, then the subpage numbers
6615		 * have to match.
6616		 */
6617		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6618		  && (page_header->page_code & SMPH_SPF)) {
6619			struct scsi_mode_page_header_sp *sph;
6620
6621			sph = (struct scsi_mode_page_header_sp *)page_header;
6622
6623			if (lun->mode_pages.index[i].subpage ==
6624			    sph->subpage) {
6625				page_index = &lun->mode_pages.index[i];
6626				page_len = scsi_2btoul(sph->page_length);
6627				break;
6628			}
6629		}
6630	}
6631
6632	/*
6633	 * If we couldn't find the page, or if we don't have a mode select
6634	 * handler for it, send back an error to the user.
6635	 */
6636	if ((page_index == NULL)
6637	 || (page_index->select_handler == NULL)) {
6638		ctl_set_invalid_field(ctsio,
6639				      /*sks_valid*/ 1,
6640				      /*command*/ 0,
6641				      /*field*/ *len_used,
6642				      /*bit_valid*/ 0,
6643				      /*bit*/ 0);
6644		free(ctsio->kern_data_ptr, M_CTL);
6645		ctl_done((union ctl_io *)ctsio);
6646		return (CTL_RETVAL_COMPLETE);
6647	}
6648
6649	if (page_index->page_code & SMPH_SPF) {
6650		page_len_offset = 2;
6651		page_len_size = 2;
6652	} else {
6653		page_len_size = 1;
6654		page_len_offset = 1;
6655	}
6656
6657	/*
6658	 * If the length the initiator gives us isn't the one we specify in
6659	 * the mode page header, or if they didn't specify enough data in
6660	 * the CDB to avoid truncating this page, kick out the request.
6661	 */
6662	if ((page_len != (page_index->page_len - page_len_offset -
6663			  page_len_size))
6664	 || (*len_left < page_index->page_len)) {
6665
6666
6667		ctl_set_invalid_field(ctsio,
6668				      /*sks_valid*/ 1,
6669				      /*command*/ 0,
6670				      /*field*/ *len_used + page_len_offset,
6671				      /*bit_valid*/ 0,
6672				      /*bit*/ 0);
6673		free(ctsio->kern_data_ptr, M_CTL);
6674		ctl_done((union ctl_io *)ctsio);
6675		return (CTL_RETVAL_COMPLETE);
6676	}
6677
6678	/*
6679	 * Run through the mode page, checking to make sure that the bits
6680	 * the user changed are actually legal for him to change.
6681	 */
6682	for (i = 0; i < page_index->page_len; i++) {
6683		uint8_t *user_byte, *change_mask, *current_byte;
6684		int bad_bit;
6685		int j;
6686
6687		user_byte = (uint8_t *)page_header + i;
6688		change_mask = page_index->page_data +
6689			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6690		current_byte = page_index->page_data +
6691			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6692
6693		/*
6694		 * Check to see whether the user set any bits in this byte
6695		 * that he is not allowed to set.
6696		 */
6697		if ((*user_byte & ~(*change_mask)) ==
6698		    (*current_byte & ~(*change_mask)))
6699			continue;
6700
6701		/*
6702		 * Go through bit by bit to determine which one is illegal.
6703		 */
6704		bad_bit = 0;
6705		for (j = 7; j >= 0; j--) {
6706			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6707			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6708				bad_bit = i;
6709				break;
6710			}
6711		}
6712		ctl_set_invalid_field(ctsio,
6713				      /*sks_valid*/ 1,
6714				      /*command*/ 0,
6715				      /*field*/ *len_used + i,
6716				      /*bit_valid*/ 1,
6717				      /*bit*/ bad_bit);
6718		free(ctsio->kern_data_ptr, M_CTL);
6719		ctl_done((union ctl_io *)ctsio);
6720		return (CTL_RETVAL_COMPLETE);
6721	}
6722
6723	/*
6724	 * Decrement these before we call the page handler, since we may
6725	 * end up getting called back one way or another before the handler
6726	 * returns to this context.
6727	 */
6728	*len_left -= page_index->page_len;
6729	*len_used += page_index->page_len;
6730
6731	retval = page_index->select_handler(ctsio, page_index,
6732					    (uint8_t *)page_header);
6733
6734	/*
6735	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6736	 * wait until this queued command completes to finish processing
6737	 * the mode page.  If it returns anything other than
6738	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6739	 * already set the sense information, freed the data pointer, and
6740	 * completed the io for us.
6741	 */
6742	if (retval != CTL_RETVAL_COMPLETE)
6743		goto bailout_no_done;
6744
6745	/*
6746	 * If the initiator sent us more than one page, parse the next one.
6747	 */
6748	if (*len_left > 0)
6749		goto do_next_page;
6750
6751	ctl_set_success(ctsio);
6752	free(ctsio->kern_data_ptr, M_CTL);
6753	ctl_done((union ctl_io *)ctsio);
6754
6755bailout_no_done:
6756
6757	return (CTL_RETVAL_COMPLETE);
6758
6759}
6760
6761int
6762ctl_mode_select(struct ctl_scsiio *ctsio)
6763{
6764	int param_len, pf, sp;
6765	int header_size, bd_len;
6766	int len_left, len_used;
6767	struct ctl_page_index *page_index;
6768	struct ctl_lun *lun;
6769	int control_dev, page_len;
6770	union ctl_modepage_info *modepage_info;
6771	int retval;
6772
6773	pf = 0;
6774	sp = 0;
6775	page_len = 0;
6776	len_used = 0;
6777	len_left = 0;
6778	retval = 0;
6779	bd_len = 0;
6780	page_index = NULL;
6781
6782	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6783
6784	if (lun->be_lun->lun_type != T_DIRECT)
6785		control_dev = 1;
6786	else
6787		control_dev = 0;
6788
6789	switch (ctsio->cdb[0]) {
6790	case MODE_SELECT_6: {
6791		struct scsi_mode_select_6 *cdb;
6792
6793		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6794
6795		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6796		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6797
6798		param_len = cdb->length;
6799		header_size = sizeof(struct scsi_mode_header_6);
6800		break;
6801	}
6802	case MODE_SELECT_10: {
6803		struct scsi_mode_select_10 *cdb;
6804
6805		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6806
6807		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6808		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6809
6810		param_len = scsi_2btoul(cdb->length);
6811		header_size = sizeof(struct scsi_mode_header_10);
6812		break;
6813	}
6814	default:
6815		ctl_set_invalid_opcode(ctsio);
6816		ctl_done((union ctl_io *)ctsio);
6817		return (CTL_RETVAL_COMPLETE);
6818		break; /* NOTREACHED */
6819	}
6820
6821	/*
6822	 * From SPC-3:
6823	 * "A parameter list length of zero indicates that the Data-Out Buffer
6824	 * shall be empty. This condition shall not be considered as an error."
6825	 */
6826	if (param_len == 0) {
6827		ctl_set_success(ctsio);
6828		ctl_done((union ctl_io *)ctsio);
6829		return (CTL_RETVAL_COMPLETE);
6830	}
6831
6832	/*
6833	 * Since we'll hit this the first time through, prior to
6834	 * allocation, we don't need to free a data buffer here.
6835	 */
6836	if (param_len < header_size) {
6837		ctl_set_param_len_error(ctsio);
6838		ctl_done((union ctl_io *)ctsio);
6839		return (CTL_RETVAL_COMPLETE);
6840	}
6841
6842	/*
6843	 * Allocate the data buffer and grab the user's data.  In theory,
6844	 * we shouldn't have to sanity check the parameter list length here
6845	 * because the maximum size is 64K.  We should be able to malloc
6846	 * that much without too many problems.
6847	 */
6848	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6849		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6850		ctsio->kern_data_len = param_len;
6851		ctsio->kern_total_len = param_len;
6852		ctsio->kern_data_resid = 0;
6853		ctsio->kern_rel_offset = 0;
6854		ctsio->kern_sg_entries = 0;
6855		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6856		ctsio->be_move_done = ctl_config_move_done;
6857		ctl_datamove((union ctl_io *)ctsio);
6858
6859		return (CTL_RETVAL_COMPLETE);
6860	}
6861
6862	switch (ctsio->cdb[0]) {
6863	case MODE_SELECT_6: {
6864		struct scsi_mode_header_6 *mh6;
6865
6866		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6867		bd_len = mh6->blk_desc_len;
6868		break;
6869	}
6870	case MODE_SELECT_10: {
6871		struct scsi_mode_header_10 *mh10;
6872
6873		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6874		bd_len = scsi_2btoul(mh10->blk_desc_len);
6875		break;
6876	}
6877	default:
6878		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6879		break;
6880	}
6881
6882	if (param_len < (header_size + bd_len)) {
6883		free(ctsio->kern_data_ptr, M_CTL);
6884		ctl_set_param_len_error(ctsio);
6885		ctl_done((union ctl_io *)ctsio);
6886		return (CTL_RETVAL_COMPLETE);
6887	}
6888
6889	/*
6890	 * Set the IO_CONT flag, so that if this I/O gets passed to
6891	 * ctl_config_write_done(), it'll get passed back to
6892	 * ctl_do_mode_select() for further processing, or completion if
6893	 * we're all done.
6894	 */
6895	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6896	ctsio->io_cont = ctl_do_mode_select;
6897
6898	modepage_info = (union ctl_modepage_info *)
6899		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6900
6901	memset(modepage_info, 0, sizeof(*modepage_info));
6902
6903	len_left = param_len - header_size - bd_len;
6904	len_used = header_size + bd_len;
6905
6906	modepage_info->header.len_left = len_left;
6907	modepage_info->header.len_used = len_used;
6908
6909	return (ctl_do_mode_select((union ctl_io *)ctsio));
6910}
6911
6912int
6913ctl_mode_sense(struct ctl_scsiio *ctsio)
6914{
6915	struct ctl_lun *lun;
6916	int pc, page_code, dbd, llba, subpage;
6917	int alloc_len, page_len, header_len, total_len;
6918	struct scsi_mode_block_descr *block_desc;
6919	struct ctl_page_index *page_index;
6920	int control_dev;
6921
6922	dbd = 0;
6923	llba = 0;
6924	block_desc = NULL;
6925	page_index = NULL;
6926
6927	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6928
6929	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6930
6931	if (lun->be_lun->lun_type != T_DIRECT)
6932		control_dev = 1;
6933	else
6934		control_dev = 0;
6935
6936	if (lun->flags & CTL_LUN_PR_RESERVED) {
6937		uint32_t residx;
6938
6939		/*
6940		 * XXX KDM need a lock here.
6941		 */
6942		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6943		if ((lun->res_type == SPR_TYPE_EX_AC
6944		  && residx != lun->pr_res_idx)
6945		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6946		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6947		  && lun->pr_keys[residx] == 0)) {
6948			ctl_set_reservation_conflict(ctsio);
6949			ctl_done((union ctl_io *)ctsio);
6950			return (CTL_RETVAL_COMPLETE);
6951		}
6952	}
6953
6954	switch (ctsio->cdb[0]) {
6955	case MODE_SENSE_6: {
6956		struct scsi_mode_sense_6 *cdb;
6957
6958		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6959
6960		header_len = sizeof(struct scsi_mode_hdr_6);
6961		if (cdb->byte2 & SMS_DBD)
6962			dbd = 1;
6963		else
6964			header_len += sizeof(struct scsi_mode_block_descr);
6965
6966		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6967		page_code = cdb->page & SMS_PAGE_CODE;
6968		subpage = cdb->subpage;
6969		alloc_len = cdb->length;
6970		break;
6971	}
6972	case MODE_SENSE_10: {
6973		struct scsi_mode_sense_10 *cdb;
6974
6975		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6976
6977		header_len = sizeof(struct scsi_mode_hdr_10);
6978
6979		if (cdb->byte2 & SMS_DBD)
6980			dbd = 1;
6981		else
6982			header_len += sizeof(struct scsi_mode_block_descr);
6983		if (cdb->byte2 & SMS10_LLBAA)
6984			llba = 1;
6985		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6986		page_code = cdb->page & SMS_PAGE_CODE;
6987		subpage = cdb->subpage;
6988		alloc_len = scsi_2btoul(cdb->length);
6989		break;
6990	}
6991	default:
6992		ctl_set_invalid_opcode(ctsio);
6993		ctl_done((union ctl_io *)ctsio);
6994		return (CTL_RETVAL_COMPLETE);
6995		break; /* NOTREACHED */
6996	}
6997
6998	/*
6999	 * We have to make a first pass through to calculate the size of
7000	 * the pages that match the user's query.  Then we allocate enough
7001	 * memory to hold it, and actually copy the data into the buffer.
7002	 */
7003	switch (page_code) {
7004	case SMS_ALL_PAGES_PAGE: {
7005		int i;
7006
7007		page_len = 0;
7008
7009		/*
7010		 * At the moment, values other than 0 and 0xff here are
7011		 * reserved according to SPC-3.
7012		 */
7013		if ((subpage != SMS_SUBPAGE_PAGE_0)
7014		 && (subpage != SMS_SUBPAGE_ALL)) {
7015			ctl_set_invalid_field(ctsio,
7016					      /*sks_valid*/ 1,
7017					      /*command*/ 1,
7018					      /*field*/ 3,
7019					      /*bit_valid*/ 0,
7020					      /*bit*/ 0);
7021			ctl_done((union ctl_io *)ctsio);
7022			return (CTL_RETVAL_COMPLETE);
7023		}
7024
7025		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7026			if ((control_dev != 0)
7027			 && (lun->mode_pages.index[i].page_flags &
7028			     CTL_PAGE_FLAG_DISK_ONLY))
7029				continue;
7030
7031			/*
7032			 * We don't use this subpage if the user didn't
7033			 * request all subpages.
7034			 */
7035			if ((lun->mode_pages.index[i].subpage != 0)
7036			 && (subpage == SMS_SUBPAGE_PAGE_0))
7037				continue;
7038
7039#if 0
7040			printf("found page %#x len %d\n",
7041			       lun->mode_pages.index[i].page_code &
7042			       SMPH_PC_MASK,
7043			       lun->mode_pages.index[i].page_len);
7044#endif
7045			page_len += lun->mode_pages.index[i].page_len;
7046		}
7047		break;
7048	}
7049	default: {
7050		int i;
7051
7052		page_len = 0;
7053
7054		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7055			/* Look for the right page code */
7056			if ((lun->mode_pages.index[i].page_code &
7057			     SMPH_PC_MASK) != page_code)
7058				continue;
7059
7060			/* Look for the right subpage or the subpage wildcard*/
7061			if ((lun->mode_pages.index[i].subpage != subpage)
7062			 && (subpage != SMS_SUBPAGE_ALL))
7063				continue;
7064
7065			/* Make sure the page is supported for this dev type */
7066			if ((control_dev != 0)
7067			 && (lun->mode_pages.index[i].page_flags &
7068			     CTL_PAGE_FLAG_DISK_ONLY))
7069				continue;
7070
7071#if 0
7072			printf("found page %#x len %d\n",
7073			       lun->mode_pages.index[i].page_code &
7074			       SMPH_PC_MASK,
7075			       lun->mode_pages.index[i].page_len);
7076#endif
7077
7078			page_len += lun->mode_pages.index[i].page_len;
7079		}
7080
7081		if (page_len == 0) {
7082			ctl_set_invalid_field(ctsio,
7083					      /*sks_valid*/ 1,
7084					      /*command*/ 1,
7085					      /*field*/ 2,
7086					      /*bit_valid*/ 1,
7087					      /*bit*/ 5);
7088			ctl_done((union ctl_io *)ctsio);
7089			return (CTL_RETVAL_COMPLETE);
7090		}
7091		break;
7092	}
7093	}
7094
7095	total_len = header_len + page_len;
7096#if 0
7097	printf("header_len = %d, page_len = %d, total_len = %d\n",
7098	       header_len, page_len, total_len);
7099#endif
7100
7101	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7102	ctsio->kern_sg_entries = 0;
7103	ctsio->kern_data_resid = 0;
7104	ctsio->kern_rel_offset = 0;
7105	if (total_len < alloc_len) {
7106		ctsio->residual = alloc_len - total_len;
7107		ctsio->kern_data_len = total_len;
7108		ctsio->kern_total_len = total_len;
7109	} else {
7110		ctsio->residual = 0;
7111		ctsio->kern_data_len = alloc_len;
7112		ctsio->kern_total_len = alloc_len;
7113	}
7114
7115	switch (ctsio->cdb[0]) {
7116	case MODE_SENSE_6: {
7117		struct scsi_mode_hdr_6 *header;
7118
7119		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7120
7121		header->datalen = ctl_min(total_len - 1, 254);
7122		if (control_dev == 0) {
7123			header->dev_specific = 0x10; /* DPOFUA */
7124			if ((lun->flags & CTL_LUN_READONLY) ||
7125			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7126			    .eca_and_aen & SCP_SWP) != 0)
7127				    header->dev_specific |= 0x80; /* WP */
7128		}
7129		if (dbd)
7130			header->block_descr_len = 0;
7131		else
7132			header->block_descr_len =
7133				sizeof(struct scsi_mode_block_descr);
7134		block_desc = (struct scsi_mode_block_descr *)&header[1];
7135		break;
7136	}
7137	case MODE_SENSE_10: {
7138		struct scsi_mode_hdr_10 *header;
7139		int datalen;
7140
7141		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7142
7143		datalen = ctl_min(total_len - 2, 65533);
7144		scsi_ulto2b(datalen, header->datalen);
7145		if (control_dev == 0) {
7146			header->dev_specific = 0x10; /* DPOFUA */
7147			if ((lun->flags & CTL_LUN_READONLY) ||
7148			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7149			    .eca_and_aen & SCP_SWP) != 0)
7150				    header->dev_specific |= 0x80; /* WP */
7151		}
7152		if (dbd)
7153			scsi_ulto2b(0, header->block_descr_len);
7154		else
7155			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7156				    header->block_descr_len);
7157		block_desc = (struct scsi_mode_block_descr *)&header[1];
7158		break;
7159	}
7160	default:
7161		panic("invalid CDB type %#x", ctsio->cdb[0]);
7162		break; /* NOTREACHED */
7163	}
7164
7165	/*
7166	 * If we've got a disk, use its blocksize in the block
7167	 * descriptor.  Otherwise, just set it to 0.
7168	 */
7169	if (dbd == 0) {
7170		if (control_dev == 0)
7171			scsi_ulto3b(lun->be_lun->blocksize,
7172				    block_desc->block_len);
7173		else
7174			scsi_ulto3b(0, block_desc->block_len);
7175	}
7176
7177	switch (page_code) {
7178	case SMS_ALL_PAGES_PAGE: {
7179		int i, data_used;
7180
7181		data_used = header_len;
7182		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7183			struct ctl_page_index *page_index;
7184
7185			page_index = &lun->mode_pages.index[i];
7186
7187			if ((control_dev != 0)
7188			 && (page_index->page_flags &
7189			    CTL_PAGE_FLAG_DISK_ONLY))
7190				continue;
7191
7192			/*
7193			 * We don't use this subpage if the user didn't
7194			 * request all subpages.  We already checked (above)
7195			 * to make sure the user only specified a subpage
7196			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7197			 */
7198			if ((page_index->subpage != 0)
7199			 && (subpage == SMS_SUBPAGE_PAGE_0))
7200				continue;
7201
7202			/*
7203			 * Call the handler, if it exists, to update the
7204			 * page to the latest values.
7205			 */
7206			if (page_index->sense_handler != NULL)
7207				page_index->sense_handler(ctsio, page_index,pc);
7208
7209			memcpy(ctsio->kern_data_ptr + data_used,
7210			       page_index->page_data +
7211			       (page_index->page_len * pc),
7212			       page_index->page_len);
7213			data_used += page_index->page_len;
7214		}
7215		break;
7216	}
7217	default: {
7218		int i, data_used;
7219
7220		data_used = header_len;
7221
7222		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7223			struct ctl_page_index *page_index;
7224
7225			page_index = &lun->mode_pages.index[i];
7226
7227			/* Look for the right page code */
7228			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7229				continue;
7230
7231			/* Look for the right subpage or the subpage wildcard*/
7232			if ((page_index->subpage != subpage)
7233			 && (subpage != SMS_SUBPAGE_ALL))
7234				continue;
7235
7236			/* Make sure the page is supported for this dev type */
7237			if ((control_dev != 0)
7238			 && (page_index->page_flags &
7239			     CTL_PAGE_FLAG_DISK_ONLY))
7240				continue;
7241
7242			/*
7243			 * Call the handler, if it exists, to update the
7244			 * page to the latest values.
7245			 */
7246			if (page_index->sense_handler != NULL)
7247				page_index->sense_handler(ctsio, page_index,pc);
7248
7249			memcpy(ctsio->kern_data_ptr + data_used,
7250			       page_index->page_data +
7251			       (page_index->page_len * pc),
7252			       page_index->page_len);
7253			data_used += page_index->page_len;
7254		}
7255		break;
7256	}
7257	}
7258
7259	ctsio->scsi_status = SCSI_STATUS_OK;
7260
7261	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7262	ctsio->be_move_done = ctl_config_move_done;
7263	ctl_datamove((union ctl_io *)ctsio);
7264
7265	return (CTL_RETVAL_COMPLETE);
7266}
7267
7268int
7269ctl_read_capacity(struct ctl_scsiio *ctsio)
7270{
7271	struct scsi_read_capacity *cdb;
7272	struct scsi_read_capacity_data *data;
7273	struct ctl_lun *lun;
7274	uint32_t lba;
7275
7276	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7277
7278	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7279
7280	lba = scsi_4btoul(cdb->addr);
7281	if (((cdb->pmi & SRC_PMI) == 0)
7282	 && (lba != 0)) {
7283		ctl_set_invalid_field(/*ctsio*/ ctsio,
7284				      /*sks_valid*/ 1,
7285				      /*command*/ 1,
7286				      /*field*/ 2,
7287				      /*bit_valid*/ 0,
7288				      /*bit*/ 0);
7289		ctl_done((union ctl_io *)ctsio);
7290		return (CTL_RETVAL_COMPLETE);
7291	}
7292
7293	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7294
7295	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7296	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7297	ctsio->residual = 0;
7298	ctsio->kern_data_len = sizeof(*data);
7299	ctsio->kern_total_len = sizeof(*data);
7300	ctsio->kern_data_resid = 0;
7301	ctsio->kern_rel_offset = 0;
7302	ctsio->kern_sg_entries = 0;
7303
7304	/*
7305	 * If the maximum LBA is greater than 0xfffffffe, the user must
7306	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7307	 * serivce action set.
7308	 */
7309	if (lun->be_lun->maxlba > 0xfffffffe)
7310		scsi_ulto4b(0xffffffff, data->addr);
7311	else
7312		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7313
7314	/*
7315	 * XXX KDM this may not be 512 bytes...
7316	 */
7317	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7318
7319	ctsio->scsi_status = SCSI_STATUS_OK;
7320
7321	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7322	ctsio->be_move_done = ctl_config_move_done;
7323	ctl_datamove((union ctl_io *)ctsio);
7324
7325	return (CTL_RETVAL_COMPLETE);
7326}
7327
7328int
7329ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7330{
7331	struct scsi_read_capacity_16 *cdb;
7332	struct scsi_read_capacity_data_long *data;
7333	struct ctl_lun *lun;
7334	uint64_t lba;
7335	uint32_t alloc_len;
7336
7337	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7338
7339	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7340
7341	alloc_len = scsi_4btoul(cdb->alloc_len);
7342	lba = scsi_8btou64(cdb->addr);
7343
7344	if ((cdb->reladr & SRC16_PMI)
7345	 && (lba != 0)) {
7346		ctl_set_invalid_field(/*ctsio*/ ctsio,
7347				      /*sks_valid*/ 1,
7348				      /*command*/ 1,
7349				      /*field*/ 2,
7350				      /*bit_valid*/ 0,
7351				      /*bit*/ 0);
7352		ctl_done((union ctl_io *)ctsio);
7353		return (CTL_RETVAL_COMPLETE);
7354	}
7355
7356	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7357
7358	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7359	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7360
7361	if (sizeof(*data) < alloc_len) {
7362		ctsio->residual = alloc_len - sizeof(*data);
7363		ctsio->kern_data_len = sizeof(*data);
7364		ctsio->kern_total_len = sizeof(*data);
7365	} else {
7366		ctsio->residual = 0;
7367		ctsio->kern_data_len = alloc_len;
7368		ctsio->kern_total_len = alloc_len;
7369	}
7370	ctsio->kern_data_resid = 0;
7371	ctsio->kern_rel_offset = 0;
7372	ctsio->kern_sg_entries = 0;
7373
7374	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7375	/* XXX KDM this may not be 512 bytes... */
7376	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7377	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7378	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7379	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7380		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7381
7382	ctsio->scsi_status = SCSI_STATUS_OK;
7383
7384	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7385	ctsio->be_move_done = ctl_config_move_done;
7386	ctl_datamove((union ctl_io *)ctsio);
7387
7388	return (CTL_RETVAL_COMPLETE);
7389}
7390
7391int
7392ctl_read_defect(struct ctl_scsiio *ctsio)
7393{
7394	struct scsi_read_defect_data_10 *ccb10;
7395	struct scsi_read_defect_data_12 *ccb12;
7396	struct scsi_read_defect_data_hdr_10 *data10;
7397	struct scsi_read_defect_data_hdr_12 *data12;
7398	struct ctl_lun *lun;
7399	uint32_t alloc_len, data_len;
7400	uint8_t format;
7401
7402	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7403
7404	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7405	if (lun->flags & CTL_LUN_PR_RESERVED) {
7406		uint32_t residx;
7407
7408		/*
7409		 * XXX KDM need a lock here.
7410		 */
7411		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7412		if ((lun->res_type == SPR_TYPE_EX_AC
7413		  && residx != lun->pr_res_idx)
7414		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
7415		   || lun->res_type == SPR_TYPE_EX_AC_AR)
7416		  && lun->pr_keys[residx] == 0)) {
7417			ctl_set_reservation_conflict(ctsio);
7418			ctl_done((union ctl_io *)ctsio);
7419			return (CTL_RETVAL_COMPLETE);
7420	        }
7421	}
7422
7423	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7424		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7425		format = ccb10->format;
7426		alloc_len = scsi_2btoul(ccb10->alloc_length);
7427		data_len = sizeof(*data10);
7428	} else {
7429		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7430		format = ccb12->format;
7431		alloc_len = scsi_4btoul(ccb12->alloc_length);
7432		data_len = sizeof(*data12);
7433	}
7434	if (alloc_len == 0) {
7435		ctl_set_success(ctsio);
7436		ctl_done((union ctl_io *)ctsio);
7437		return (CTL_RETVAL_COMPLETE);
7438	}
7439
7440	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7441	if (data_len < alloc_len) {
7442		ctsio->residual = alloc_len - data_len;
7443		ctsio->kern_data_len = data_len;
7444		ctsio->kern_total_len = data_len;
7445	} else {
7446		ctsio->residual = 0;
7447		ctsio->kern_data_len = alloc_len;
7448		ctsio->kern_total_len = alloc_len;
7449	}
7450	ctsio->kern_data_resid = 0;
7451	ctsio->kern_rel_offset = 0;
7452	ctsio->kern_sg_entries = 0;
7453
7454	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7455		data10 = (struct scsi_read_defect_data_hdr_10 *)
7456		    ctsio->kern_data_ptr;
7457		data10->format = format;
7458		scsi_ulto2b(0, data10->length);
7459	} else {
7460		data12 = (struct scsi_read_defect_data_hdr_12 *)
7461		    ctsio->kern_data_ptr;
7462		data12->format = format;
7463		scsi_ulto2b(0, data12->generation);
7464		scsi_ulto4b(0, data12->length);
7465	}
7466
7467	ctsio->scsi_status = SCSI_STATUS_OK;
7468	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7469	ctsio->be_move_done = ctl_config_move_done;
7470	ctl_datamove((union ctl_io *)ctsio);
7471	return (CTL_RETVAL_COMPLETE);
7472}
7473
7474int
7475ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7476{
7477	struct scsi_maintenance_in *cdb;
7478	int retval;
7479	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7480	int num_target_port_groups, num_target_ports, single;
7481	struct ctl_lun *lun;
7482	struct ctl_softc *softc;
7483	struct ctl_port *port;
7484	struct scsi_target_group_data *rtg_ptr;
7485	struct scsi_target_group_data_extended *rtg_ext_ptr;
7486	struct scsi_target_port_group_descriptor *tpg_desc;
7487
7488	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7489
7490	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7491	softc = control_softc;
7492	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7493
7494	retval = CTL_RETVAL_COMPLETE;
7495
7496	switch (cdb->byte2 & STG_PDF_MASK) {
7497	case STG_PDF_LENGTH:
7498		ext = 0;
7499		break;
7500	case STG_PDF_EXTENDED:
7501		ext = 1;
7502		break;
7503	default:
7504		ctl_set_invalid_field(/*ctsio*/ ctsio,
7505				      /*sks_valid*/ 1,
7506				      /*command*/ 1,
7507				      /*field*/ 2,
7508				      /*bit_valid*/ 1,
7509				      /*bit*/ 5);
7510		ctl_done((union ctl_io *)ctsio);
7511		return(retval);
7512	}
7513
7514	single = ctl_is_single;
7515	if (single)
7516		num_target_port_groups = 1;
7517	else
7518		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7519	num_target_ports = 0;
7520	mtx_lock(&softc->ctl_lock);
7521	STAILQ_FOREACH(port, &softc->port_list, links) {
7522		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7523			continue;
7524		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7525			continue;
7526		num_target_ports++;
7527	}
7528	mtx_unlock(&softc->ctl_lock);
7529
7530	if (ext)
7531		total_len = sizeof(struct scsi_target_group_data_extended);
7532	else
7533		total_len = sizeof(struct scsi_target_group_data);
7534	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7535		num_target_port_groups +
7536	    sizeof(struct scsi_target_port_descriptor) *
7537		num_target_ports * num_target_port_groups;
7538
7539	alloc_len = scsi_4btoul(cdb->length);
7540
7541	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7542
7543	ctsio->kern_sg_entries = 0;
7544
7545	if (total_len < alloc_len) {
7546		ctsio->residual = alloc_len - total_len;
7547		ctsio->kern_data_len = total_len;
7548		ctsio->kern_total_len = total_len;
7549	} else {
7550		ctsio->residual = 0;
7551		ctsio->kern_data_len = alloc_len;
7552		ctsio->kern_total_len = alloc_len;
7553	}
7554	ctsio->kern_data_resid = 0;
7555	ctsio->kern_rel_offset = 0;
7556
7557	if (ext) {
7558		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7559		    ctsio->kern_data_ptr;
7560		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7561		rtg_ext_ptr->format_type = 0x10;
7562		rtg_ext_ptr->implicit_transition_time = 0;
7563		tpg_desc = &rtg_ext_ptr->groups[0];
7564	} else {
7565		rtg_ptr = (struct scsi_target_group_data *)
7566		    ctsio->kern_data_ptr;
7567		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7568		tpg_desc = &rtg_ptr->groups[0];
7569	}
7570
7571	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7572	mtx_lock(&softc->ctl_lock);
7573	for (g = 0; g < num_target_port_groups; g++) {
7574		if (g == pg)
7575			tpg_desc->pref_state = TPG_PRIMARY |
7576			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7577		else
7578			tpg_desc->pref_state =
7579			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7580		tpg_desc->support = TPG_AO_SUP;
7581		if (!single)
7582			tpg_desc->support |= TPG_AN_SUP;
7583		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7584		tpg_desc->status = TPG_IMPLICIT;
7585		pc = 0;
7586		STAILQ_FOREACH(port, &softc->port_list, links) {
7587			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7588				continue;
7589			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7590			    CTL_MAX_LUNS)
7591				continue;
7592			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7593			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7594			    relative_target_port_identifier);
7595			pc++;
7596		}
7597		tpg_desc->target_port_count = pc;
7598		tpg_desc = (struct scsi_target_port_group_descriptor *)
7599		    &tpg_desc->descriptors[pc];
7600	}
7601	mtx_unlock(&softc->ctl_lock);
7602
7603	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7604	ctsio->be_move_done = ctl_config_move_done;
7605
7606	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7607			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7608			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7609			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7610			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7611
7612	ctl_datamove((union ctl_io *)ctsio);
7613	return(retval);
7614}
7615
7616int
7617ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7618{
7619	struct ctl_lun *lun;
7620	struct scsi_report_supported_opcodes *cdb;
7621	const struct ctl_cmd_entry *entry, *sentry;
7622	struct scsi_report_supported_opcodes_all *all;
7623	struct scsi_report_supported_opcodes_descr *descr;
7624	struct scsi_report_supported_opcodes_one *one;
7625	int retval;
7626	int alloc_len, total_len;
7627	int opcode, service_action, i, j, num;
7628
7629	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7630
7631	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7632	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7633
7634	retval = CTL_RETVAL_COMPLETE;
7635
7636	opcode = cdb->requested_opcode;
7637	service_action = scsi_2btoul(cdb->requested_service_action);
7638	switch (cdb->options & RSO_OPTIONS_MASK) {
7639	case RSO_OPTIONS_ALL:
7640		num = 0;
7641		for (i = 0; i < 256; i++) {
7642			entry = &ctl_cmd_table[i];
7643			if (entry->flags & CTL_CMD_FLAG_SA5) {
7644				for (j = 0; j < 32; j++) {
7645					sentry = &((const struct ctl_cmd_entry *)
7646					    entry->execute)[j];
7647					if (ctl_cmd_applicable(
7648					    lun->be_lun->lun_type, sentry))
7649						num++;
7650				}
7651			} else {
7652				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7653				    entry))
7654					num++;
7655			}
7656		}
7657		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7658		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7659		break;
7660	case RSO_OPTIONS_OC:
7661		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7662			ctl_set_invalid_field(/*ctsio*/ ctsio,
7663					      /*sks_valid*/ 1,
7664					      /*command*/ 1,
7665					      /*field*/ 2,
7666					      /*bit_valid*/ 1,
7667					      /*bit*/ 2);
7668			ctl_done((union ctl_io *)ctsio);
7669			return (CTL_RETVAL_COMPLETE);
7670		}
7671		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7672		break;
7673	case RSO_OPTIONS_OC_SA:
7674		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7675		    service_action >= 32) {
7676			ctl_set_invalid_field(/*ctsio*/ ctsio,
7677					      /*sks_valid*/ 1,
7678					      /*command*/ 1,
7679					      /*field*/ 2,
7680					      /*bit_valid*/ 1,
7681					      /*bit*/ 2);
7682			ctl_done((union ctl_io *)ctsio);
7683			return (CTL_RETVAL_COMPLETE);
7684		}
7685		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7686		break;
7687	default:
7688		ctl_set_invalid_field(/*ctsio*/ ctsio,
7689				      /*sks_valid*/ 1,
7690				      /*command*/ 1,
7691				      /*field*/ 2,
7692				      /*bit_valid*/ 1,
7693				      /*bit*/ 2);
7694		ctl_done((union ctl_io *)ctsio);
7695		return (CTL_RETVAL_COMPLETE);
7696	}
7697
7698	alloc_len = scsi_4btoul(cdb->length);
7699
7700	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7701
7702	ctsio->kern_sg_entries = 0;
7703
7704	if (total_len < alloc_len) {
7705		ctsio->residual = alloc_len - total_len;
7706		ctsio->kern_data_len = total_len;
7707		ctsio->kern_total_len = total_len;
7708	} else {
7709		ctsio->residual = 0;
7710		ctsio->kern_data_len = alloc_len;
7711		ctsio->kern_total_len = alloc_len;
7712	}
7713	ctsio->kern_data_resid = 0;
7714	ctsio->kern_rel_offset = 0;
7715
7716	switch (cdb->options & RSO_OPTIONS_MASK) {
7717	case RSO_OPTIONS_ALL:
7718		all = (struct scsi_report_supported_opcodes_all *)
7719		    ctsio->kern_data_ptr;
7720		num = 0;
7721		for (i = 0; i < 256; i++) {
7722			entry = &ctl_cmd_table[i];
7723			if (entry->flags & CTL_CMD_FLAG_SA5) {
7724				for (j = 0; j < 32; j++) {
7725					sentry = &((const struct ctl_cmd_entry *)
7726					    entry->execute)[j];
7727					if (!ctl_cmd_applicable(
7728					    lun->be_lun->lun_type, sentry))
7729						continue;
7730					descr = &all->descr[num++];
7731					descr->opcode = i;
7732					scsi_ulto2b(j, descr->service_action);
7733					descr->flags = RSO_SERVACTV;
7734					scsi_ulto2b(sentry->length,
7735					    descr->cdb_length);
7736				}
7737			} else {
7738				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7739				    entry))
7740					continue;
7741				descr = &all->descr[num++];
7742				descr->opcode = i;
7743				scsi_ulto2b(0, descr->service_action);
7744				descr->flags = 0;
7745				scsi_ulto2b(entry->length, descr->cdb_length);
7746			}
7747		}
7748		scsi_ulto4b(
7749		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7750		    all->length);
7751		break;
7752	case RSO_OPTIONS_OC:
7753		one = (struct scsi_report_supported_opcodes_one *)
7754		    ctsio->kern_data_ptr;
7755		entry = &ctl_cmd_table[opcode];
7756		goto fill_one;
7757	case RSO_OPTIONS_OC_SA:
7758		one = (struct scsi_report_supported_opcodes_one *)
7759		    ctsio->kern_data_ptr;
7760		entry = &ctl_cmd_table[opcode];
7761		entry = &((const struct ctl_cmd_entry *)
7762		    entry->execute)[service_action];
7763fill_one:
7764		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7765			one->support = 3;
7766			scsi_ulto2b(entry->length, one->cdb_length);
7767			one->cdb_usage[0] = opcode;
7768			memcpy(&one->cdb_usage[1], entry->usage,
7769			    entry->length - 1);
7770		} else
7771			one->support = 1;
7772		break;
7773	}
7774
7775	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7776	ctsio->be_move_done = ctl_config_move_done;
7777
7778	ctl_datamove((union ctl_io *)ctsio);
7779	return(retval);
7780}
7781
7782int
7783ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7784{
7785	struct ctl_lun *lun;
7786	struct scsi_report_supported_tmf *cdb;
7787	struct scsi_report_supported_tmf_data *data;
7788	int retval;
7789	int alloc_len, total_len;
7790
7791	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7792
7793	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7794	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7795
7796	retval = CTL_RETVAL_COMPLETE;
7797
7798	total_len = sizeof(struct scsi_report_supported_tmf_data);
7799	alloc_len = scsi_4btoul(cdb->length);
7800
7801	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7802
7803	ctsio->kern_sg_entries = 0;
7804
7805	if (total_len < alloc_len) {
7806		ctsio->residual = alloc_len - total_len;
7807		ctsio->kern_data_len = total_len;
7808		ctsio->kern_total_len = total_len;
7809	} else {
7810		ctsio->residual = 0;
7811		ctsio->kern_data_len = alloc_len;
7812		ctsio->kern_total_len = alloc_len;
7813	}
7814	ctsio->kern_data_resid = 0;
7815	ctsio->kern_rel_offset = 0;
7816
7817	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7818	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7819	data->byte2 |= RST_ITNRS;
7820
7821	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7822	ctsio->be_move_done = ctl_config_move_done;
7823
7824	ctl_datamove((union ctl_io *)ctsio);
7825	return (retval);
7826}
7827
7828int
7829ctl_report_timestamp(struct ctl_scsiio *ctsio)
7830{
7831	struct ctl_lun *lun;
7832	struct scsi_report_timestamp *cdb;
7833	struct scsi_report_timestamp_data *data;
7834	struct timeval tv;
7835	int64_t timestamp;
7836	int retval;
7837	int alloc_len, total_len;
7838
7839	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7840
7841	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7842	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7843
7844	retval = CTL_RETVAL_COMPLETE;
7845
7846	total_len = sizeof(struct scsi_report_timestamp_data);
7847	alloc_len = scsi_4btoul(cdb->length);
7848
7849	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7850
7851	ctsio->kern_sg_entries = 0;
7852
7853	if (total_len < alloc_len) {
7854		ctsio->residual = alloc_len - total_len;
7855		ctsio->kern_data_len = total_len;
7856		ctsio->kern_total_len = total_len;
7857	} else {
7858		ctsio->residual = 0;
7859		ctsio->kern_data_len = alloc_len;
7860		ctsio->kern_total_len = alloc_len;
7861	}
7862	ctsio->kern_data_resid = 0;
7863	ctsio->kern_rel_offset = 0;
7864
7865	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7866	scsi_ulto2b(sizeof(*data) - 2, data->length);
7867	data->origin = RTS_ORIG_OUTSIDE;
7868	getmicrotime(&tv);
7869	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7870	scsi_ulto4b(timestamp >> 16, data->timestamp);
7871	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7872
7873	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7874	ctsio->be_move_done = ctl_config_move_done;
7875
7876	ctl_datamove((union ctl_io *)ctsio);
7877	return (retval);
7878}
7879
7880int
7881ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7882{
7883	struct scsi_per_res_in *cdb;
7884	int alloc_len, total_len = 0;
7885	/* struct scsi_per_res_in_rsrv in_data; */
7886	struct ctl_lun *lun;
7887	struct ctl_softc *softc;
7888
7889	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7890
7891	softc = control_softc;
7892
7893	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7894
7895	alloc_len = scsi_2btoul(cdb->length);
7896
7897	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7898
7899retry:
7900	mtx_lock(&lun->lun_lock);
7901	switch (cdb->action) {
7902	case SPRI_RK: /* read keys */
7903		total_len = sizeof(struct scsi_per_res_in_keys) +
7904			lun->pr_key_count *
7905			sizeof(struct scsi_per_res_key);
7906		break;
7907	case SPRI_RR: /* read reservation */
7908		if (lun->flags & CTL_LUN_PR_RESERVED)
7909			total_len = sizeof(struct scsi_per_res_in_rsrv);
7910		else
7911			total_len = sizeof(struct scsi_per_res_in_header);
7912		break;
7913	case SPRI_RC: /* report capabilities */
7914		total_len = sizeof(struct scsi_per_res_cap);
7915		break;
7916	case SPRI_RS: /* read full status */
7917		total_len = sizeof(struct scsi_per_res_in_header) +
7918		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7919		    lun->pr_key_count;
7920		break;
7921	default:
7922		panic("Invalid PR type %x", cdb->action);
7923	}
7924	mtx_unlock(&lun->lun_lock);
7925
7926	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7927
7928	if (total_len < alloc_len) {
7929		ctsio->residual = alloc_len - total_len;
7930		ctsio->kern_data_len = total_len;
7931		ctsio->kern_total_len = total_len;
7932	} else {
7933		ctsio->residual = 0;
7934		ctsio->kern_data_len = alloc_len;
7935		ctsio->kern_total_len = alloc_len;
7936	}
7937
7938	ctsio->kern_data_resid = 0;
7939	ctsio->kern_rel_offset = 0;
7940	ctsio->kern_sg_entries = 0;
7941
7942	mtx_lock(&lun->lun_lock);
7943	switch (cdb->action) {
7944	case SPRI_RK: { // read keys
7945        struct scsi_per_res_in_keys *res_keys;
7946		int i, key_count;
7947
7948		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7949
7950		/*
7951		 * We had to drop the lock to allocate our buffer, which
7952		 * leaves time for someone to come in with another
7953		 * persistent reservation.  (That is unlikely, though,
7954		 * since this should be the only persistent reservation
7955		 * command active right now.)
7956		 */
7957		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7958		    (lun->pr_key_count *
7959		     sizeof(struct scsi_per_res_key)))){
7960			mtx_unlock(&lun->lun_lock);
7961			free(ctsio->kern_data_ptr, M_CTL);
7962			printf("%s: reservation length changed, retrying\n",
7963			       __func__);
7964			goto retry;
7965		}
7966
7967		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7968
7969		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7970			     lun->pr_key_count, res_keys->header.length);
7971
7972		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7973			if (lun->pr_keys[i] == 0)
7974				continue;
7975
7976			/*
7977			 * We used lun->pr_key_count to calculate the
7978			 * size to allocate.  If it turns out the number of
7979			 * initiators with the registered flag set is
7980			 * larger than that (i.e. they haven't been kept in
7981			 * sync), we've got a problem.
7982			 */
7983			if (key_count >= lun->pr_key_count) {
7984#ifdef NEEDTOPORT
7985				csevent_log(CSC_CTL | CSC_SHELF_SW |
7986					    CTL_PR_ERROR,
7987					    csevent_LogType_Fault,
7988					    csevent_AlertLevel_Yellow,
7989					    csevent_FRU_ShelfController,
7990					    csevent_FRU_Firmware,
7991				        csevent_FRU_Unknown,
7992					    "registered keys %d >= key "
7993					    "count %d", key_count,
7994					    lun->pr_key_count);
7995#endif
7996				key_count++;
7997				continue;
7998			}
7999			scsi_u64to8b(lun->pr_keys[i],
8000			    res_keys->keys[key_count].key);
8001			key_count++;
8002		}
8003		break;
8004	}
8005	case SPRI_RR: { // read reservation
8006		struct scsi_per_res_in_rsrv *res;
8007		int tmp_len, header_only;
8008
8009		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
8010
8011		scsi_ulto4b(lun->PRGeneration, res->header.generation);
8012
8013		if (lun->flags & CTL_LUN_PR_RESERVED)
8014		{
8015			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
8016			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
8017				    res->header.length);
8018			header_only = 0;
8019		} else {
8020			tmp_len = sizeof(struct scsi_per_res_in_header);
8021			scsi_ulto4b(0, res->header.length);
8022			header_only = 1;
8023		}
8024
8025		/*
8026		 * We had to drop the lock to allocate our buffer, which
8027		 * leaves time for someone to come in with another
8028		 * persistent reservation.  (That is unlikely, though,
8029		 * since this should be the only persistent reservation
8030		 * command active right now.)
8031		 */
8032		if (tmp_len != total_len) {
8033			mtx_unlock(&lun->lun_lock);
8034			free(ctsio->kern_data_ptr, M_CTL);
8035			printf("%s: reservation status changed, retrying\n",
8036			       __func__);
8037			goto retry;
8038		}
8039
8040		/*
8041		 * No reservation held, so we're done.
8042		 */
8043		if (header_only != 0)
8044			break;
8045
8046		/*
8047		 * If the registration is an All Registrants type, the key
8048		 * is 0, since it doesn't really matter.
8049		 */
8050		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8051			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
8052			    res->data.reservation);
8053		}
8054		res->data.scopetype = lun->res_type;
8055		break;
8056	}
8057	case SPRI_RC:     //report capabilities
8058	{
8059		struct scsi_per_res_cap *res_cap;
8060		uint16_t type_mask;
8061
8062		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8063		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8064		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8065		type_mask = SPRI_TM_WR_EX_AR |
8066			    SPRI_TM_EX_AC_RO |
8067			    SPRI_TM_WR_EX_RO |
8068			    SPRI_TM_EX_AC |
8069			    SPRI_TM_WR_EX |
8070			    SPRI_TM_EX_AC_AR;
8071		scsi_ulto2b(type_mask, res_cap->type_mask);
8072		break;
8073	}
8074	case SPRI_RS: { // read full status
8075		struct scsi_per_res_in_full *res_status;
8076		struct scsi_per_res_in_full_desc *res_desc;
8077		struct ctl_port *port;
8078		int i, len;
8079
8080		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8081
8082		/*
8083		 * We had to drop the lock to allocate our buffer, which
8084		 * leaves time for someone to come in with another
8085		 * persistent reservation.  (That is unlikely, though,
8086		 * since this should be the only persistent reservation
8087		 * command active right now.)
8088		 */
8089		if (total_len < (sizeof(struct scsi_per_res_in_header) +
8090		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8091		     lun->pr_key_count)){
8092			mtx_unlock(&lun->lun_lock);
8093			free(ctsio->kern_data_ptr, M_CTL);
8094			printf("%s: reservation length changed, retrying\n",
8095			       __func__);
8096			goto retry;
8097		}
8098
8099		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8100
8101		res_desc = &res_status->desc[0];
8102		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8103			if (lun->pr_keys[i] == 0)
8104				continue;
8105
8106			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
8107			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8108			    (lun->pr_res_idx == i ||
8109			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8110				res_desc->flags = SPRI_FULL_R_HOLDER;
8111				res_desc->scopetype = lun->res_type;
8112			}
8113			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8114			    res_desc->rel_trgt_port_id);
8115			len = 0;
8116			port = softc->ctl_ports[
8117			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8118			if (port != NULL)
8119				len = ctl_create_iid(port,
8120				    i % CTL_MAX_INIT_PER_PORT,
8121				    res_desc->transport_id);
8122			scsi_ulto4b(len, res_desc->additional_length);
8123			res_desc = (struct scsi_per_res_in_full_desc *)
8124			    &res_desc->transport_id[len];
8125		}
8126		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8127		    res_status->header.length);
8128		break;
8129	}
8130	default:
8131		/*
8132		 * This is a bug, because we just checked for this above,
8133		 * and should have returned an error.
8134		 */
8135		panic("Invalid PR type %x", cdb->action);
8136		break; /* NOTREACHED */
8137	}
8138	mtx_unlock(&lun->lun_lock);
8139
8140	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8141	ctsio->be_move_done = ctl_config_move_done;
8142
8143	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8144			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8145			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8146			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8147			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8148
8149	ctl_datamove((union ctl_io *)ctsio);
8150
8151	return (CTL_RETVAL_COMPLETE);
8152}
8153
8154/*
8155 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8156 * it should return.
8157 */
8158static int
8159ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8160		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8161		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8162		struct scsi_per_res_out_parms* param)
8163{
8164	union ctl_ha_msg persis_io;
8165	int retval, i;
8166	int isc_retval;
8167
8168	retval = 0;
8169
8170	mtx_lock(&lun->lun_lock);
8171	if (sa_res_key == 0) {
8172		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8173			/* validate scope and type */
8174			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8175			     SPR_LU_SCOPE) {
8176				mtx_unlock(&lun->lun_lock);
8177				ctl_set_invalid_field(/*ctsio*/ ctsio,
8178						      /*sks_valid*/ 1,
8179						      /*command*/ 1,
8180						      /*field*/ 2,
8181						      /*bit_valid*/ 1,
8182						      /*bit*/ 4);
8183				ctl_done((union ctl_io *)ctsio);
8184				return (1);
8185			}
8186
8187		        if (type>8 || type==2 || type==4 || type==0) {
8188				mtx_unlock(&lun->lun_lock);
8189				ctl_set_invalid_field(/*ctsio*/ ctsio,
8190       	           				      /*sks_valid*/ 1,
8191						      /*command*/ 1,
8192						      /*field*/ 2,
8193						      /*bit_valid*/ 1,
8194						      /*bit*/ 0);
8195				ctl_done((union ctl_io *)ctsio);
8196				return (1);
8197		        }
8198
8199			/*
8200			 * Unregister everybody else and build UA for
8201			 * them
8202			 */
8203			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8204				if (i == residx || lun->pr_keys[i] == 0)
8205					continue;
8206
8207				if (!persis_offset
8208				 && i <CTL_MAX_INITIATORS)
8209					lun->pending_ua[i] |=
8210						CTL_UA_REG_PREEMPT;
8211				else if (persis_offset
8212				      && i >= persis_offset)
8213					lun->pending_ua[i-persis_offset] |=
8214						CTL_UA_REG_PREEMPT;
8215				lun->pr_keys[i] = 0;
8216			}
8217			lun->pr_key_count = 1;
8218			lun->res_type = type;
8219			if (lun->res_type != SPR_TYPE_WR_EX_AR
8220			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8221				lun->pr_res_idx = residx;
8222
8223			/* send msg to other side */
8224			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8225			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8226			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8227			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8228			persis_io.pr.pr_info.res_type = type;
8229			memcpy(persis_io.pr.pr_info.sa_res_key,
8230			       param->serv_act_res_key,
8231			       sizeof(param->serv_act_res_key));
8232			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8233			     &persis_io, sizeof(persis_io), 0)) >
8234			     CTL_HA_STATUS_SUCCESS) {
8235				printf("CTL:Persis Out error returned "
8236				       "from ctl_ha_msg_send %d\n",
8237				       isc_retval);
8238			}
8239		} else {
8240			/* not all registrants */
8241			mtx_unlock(&lun->lun_lock);
8242			free(ctsio->kern_data_ptr, M_CTL);
8243			ctl_set_invalid_field(ctsio,
8244					      /*sks_valid*/ 1,
8245					      /*command*/ 0,
8246					      /*field*/ 8,
8247					      /*bit_valid*/ 0,
8248					      /*bit*/ 0);
8249			ctl_done((union ctl_io *)ctsio);
8250			return (1);
8251		}
8252	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8253		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8254		int found = 0;
8255
8256		if (res_key == sa_res_key) {
8257			/* special case */
8258			/*
8259			 * The spec implies this is not good but doesn't
8260			 * say what to do. There are two choices either
8261			 * generate a res conflict or check condition
8262			 * with illegal field in parameter data. Since
8263			 * that is what is done when the sa_res_key is
8264			 * zero I'll take that approach since this has
8265			 * to do with the sa_res_key.
8266			 */
8267			mtx_unlock(&lun->lun_lock);
8268			free(ctsio->kern_data_ptr, M_CTL);
8269			ctl_set_invalid_field(ctsio,
8270					      /*sks_valid*/ 1,
8271					      /*command*/ 0,
8272					      /*field*/ 8,
8273					      /*bit_valid*/ 0,
8274					      /*bit*/ 0);
8275			ctl_done((union ctl_io *)ctsio);
8276			return (1);
8277		}
8278
8279		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8280			if (lun->pr_keys[i] != sa_res_key)
8281				continue;
8282
8283			found = 1;
8284			lun->pr_keys[i] = 0;
8285			lun->pr_key_count--;
8286
8287			if (!persis_offset && i < CTL_MAX_INITIATORS)
8288				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8289			else if (persis_offset && i >= persis_offset)
8290				lun->pending_ua[i-persis_offset] |=
8291					CTL_UA_REG_PREEMPT;
8292		}
8293		if (!found) {
8294			mtx_unlock(&lun->lun_lock);
8295			free(ctsio->kern_data_ptr, M_CTL);
8296			ctl_set_reservation_conflict(ctsio);
8297			ctl_done((union ctl_io *)ctsio);
8298			return (CTL_RETVAL_COMPLETE);
8299		}
8300		/* send msg to other side */
8301		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8302		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8303		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8304		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8305		persis_io.pr.pr_info.res_type = type;
8306		memcpy(persis_io.pr.pr_info.sa_res_key,
8307		       param->serv_act_res_key,
8308		       sizeof(param->serv_act_res_key));
8309		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8310		     &persis_io, sizeof(persis_io), 0)) >
8311		     CTL_HA_STATUS_SUCCESS) {
8312			printf("CTL:Persis Out error returned from "
8313			       "ctl_ha_msg_send %d\n", isc_retval);
8314		}
8315	} else {
8316		/* Reserved but not all registrants */
8317		/* sa_res_key is res holder */
8318		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8319			/* validate scope and type */
8320			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8321			     SPR_LU_SCOPE) {
8322				mtx_unlock(&lun->lun_lock);
8323				ctl_set_invalid_field(/*ctsio*/ ctsio,
8324						      /*sks_valid*/ 1,
8325						      /*command*/ 1,
8326						      /*field*/ 2,
8327						      /*bit_valid*/ 1,
8328						      /*bit*/ 4);
8329				ctl_done((union ctl_io *)ctsio);
8330				return (1);
8331			}
8332
8333			if (type>8 || type==2 || type==4 || type==0) {
8334				mtx_unlock(&lun->lun_lock);
8335				ctl_set_invalid_field(/*ctsio*/ ctsio,
8336						      /*sks_valid*/ 1,
8337						      /*command*/ 1,
8338						      /*field*/ 2,
8339						      /*bit_valid*/ 1,
8340						      /*bit*/ 0);
8341				ctl_done((union ctl_io *)ctsio);
8342				return (1);
8343			}
8344
8345			/*
8346			 * Do the following:
8347			 * if sa_res_key != res_key remove all
8348			 * registrants w/sa_res_key and generate UA
8349			 * for these registrants(Registrations
8350			 * Preempted) if it wasn't an exclusive
8351			 * reservation generate UA(Reservations
8352			 * Preempted) for all other registered nexuses
8353			 * if the type has changed. Establish the new
8354			 * reservation and holder. If res_key and
8355			 * sa_res_key are the same do the above
8356			 * except don't unregister the res holder.
8357			 */
8358
8359			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8360				if (i == residx || lun->pr_keys[i] == 0)
8361					continue;
8362
8363				if (sa_res_key == lun->pr_keys[i]) {
8364					lun->pr_keys[i] = 0;
8365					lun->pr_key_count--;
8366
8367					if (!persis_offset
8368					 && i < CTL_MAX_INITIATORS)
8369						lun->pending_ua[i] |=
8370							CTL_UA_REG_PREEMPT;
8371					else if (persis_offset
8372					      && i >= persis_offset)
8373						lun->pending_ua[i-persis_offset] |=
8374						  CTL_UA_REG_PREEMPT;
8375				} else if (type != lun->res_type
8376					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8377					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8378						if (!persis_offset
8379						 && i < CTL_MAX_INITIATORS)
8380							lun->pending_ua[i] |=
8381							CTL_UA_RES_RELEASE;
8382						else if (persis_offset
8383						      && i >= persis_offset)
8384							lun->pending_ua[
8385							i-persis_offset] |=
8386							CTL_UA_RES_RELEASE;
8387				}
8388			}
8389			lun->res_type = type;
8390			if (lun->res_type != SPR_TYPE_WR_EX_AR
8391			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8392				lun->pr_res_idx = residx;
8393			else
8394				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8395
8396			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8397			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8398			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8399			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8400			persis_io.pr.pr_info.res_type = type;
8401			memcpy(persis_io.pr.pr_info.sa_res_key,
8402			       param->serv_act_res_key,
8403			       sizeof(param->serv_act_res_key));
8404			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8405			     &persis_io, sizeof(persis_io), 0)) >
8406			     CTL_HA_STATUS_SUCCESS) {
8407				printf("CTL:Persis Out error returned "
8408				       "from ctl_ha_msg_send %d\n",
8409				       isc_retval);
8410			}
8411		} else {
8412			/*
8413			 * sa_res_key is not the res holder just
8414			 * remove registrants
8415			 */
8416			int found=0;
8417
8418			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8419				if (sa_res_key != lun->pr_keys[i])
8420					continue;
8421
8422				found = 1;
8423				lun->pr_keys[i] = 0;
8424				lun->pr_key_count--;
8425
8426				if (!persis_offset
8427				 && i < CTL_MAX_INITIATORS)
8428					lun->pending_ua[i] |=
8429						CTL_UA_REG_PREEMPT;
8430				else if (persis_offset
8431				      && i >= persis_offset)
8432					lun->pending_ua[i-persis_offset] |=
8433						CTL_UA_REG_PREEMPT;
8434			}
8435
8436			if (!found) {
8437				mtx_unlock(&lun->lun_lock);
8438				free(ctsio->kern_data_ptr, M_CTL);
8439				ctl_set_reservation_conflict(ctsio);
8440				ctl_done((union ctl_io *)ctsio);
8441		        	return (1);
8442			}
8443			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8444			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8445			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8446			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8447			persis_io.pr.pr_info.res_type = type;
8448			memcpy(persis_io.pr.pr_info.sa_res_key,
8449			       param->serv_act_res_key,
8450			       sizeof(param->serv_act_res_key));
8451			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8452			     &persis_io, sizeof(persis_io), 0)) >
8453			     CTL_HA_STATUS_SUCCESS) {
8454				printf("CTL:Persis Out error returned "
8455				       "from ctl_ha_msg_send %d\n",
8456				isc_retval);
8457			}
8458		}
8459	}
8460
8461	lun->PRGeneration++;
8462	mtx_unlock(&lun->lun_lock);
8463
8464	return (retval);
8465}
8466
8467static void
8468ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8469{
8470	uint64_t sa_res_key;
8471	int i;
8472
8473	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8474
8475	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8476	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8477	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8478		if (sa_res_key == 0) {
8479			/*
8480			 * Unregister everybody else and build UA for
8481			 * them
8482			 */
8483			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8484				if (i == msg->pr.pr_info.residx ||
8485				    lun->pr_keys[i] == 0)
8486					continue;
8487
8488				if (!persis_offset
8489				 && i < CTL_MAX_INITIATORS)
8490					lun->pending_ua[i] |=
8491						CTL_UA_REG_PREEMPT;
8492				else if (persis_offset && i >= persis_offset)
8493					lun->pending_ua[i - persis_offset] |=
8494						CTL_UA_REG_PREEMPT;
8495				lun->pr_keys[i] = 0;
8496			}
8497
8498			lun->pr_key_count = 1;
8499			lun->res_type = msg->pr.pr_info.res_type;
8500			if (lun->res_type != SPR_TYPE_WR_EX_AR
8501			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8502				lun->pr_res_idx = msg->pr.pr_info.residx;
8503		} else {
8504		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8505				if (sa_res_key == lun->pr_keys[i])
8506					continue;
8507
8508				lun->pr_keys[i] = 0;
8509				lun->pr_key_count--;
8510
8511				if (!persis_offset
8512				 && i < persis_offset)
8513					lun->pending_ua[i] |=
8514						CTL_UA_REG_PREEMPT;
8515				else if (persis_offset
8516				      && i >= persis_offset)
8517					lun->pending_ua[i - persis_offset] |=
8518						CTL_UA_REG_PREEMPT;
8519			}
8520		}
8521	} else {
8522		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8523			if (i == msg->pr.pr_info.residx ||
8524			    lun->pr_keys[i] == 0)
8525				continue;
8526
8527			if (sa_res_key == lun->pr_keys[i]) {
8528				lun->pr_keys[i] = 0;
8529				lun->pr_key_count--;
8530				if (!persis_offset
8531				 && i < CTL_MAX_INITIATORS)
8532					lun->pending_ua[i] |=
8533						CTL_UA_REG_PREEMPT;
8534				else if (persis_offset
8535				      && i >= persis_offset)
8536					lun->pending_ua[i - persis_offset] |=
8537						CTL_UA_REG_PREEMPT;
8538			} else if (msg->pr.pr_info.res_type != lun->res_type
8539				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8540				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8541					if (!persis_offset
8542					 && i < persis_offset)
8543						lun->pending_ua[i] |=
8544							CTL_UA_RES_RELEASE;
8545					else if (persis_offset
8546					      && i >= persis_offset)
8547					lun->pending_ua[i - persis_offset] |=
8548						CTL_UA_RES_RELEASE;
8549			}
8550		}
8551		lun->res_type = msg->pr.pr_info.res_type;
8552		if (lun->res_type != SPR_TYPE_WR_EX_AR
8553		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8554			lun->pr_res_idx = msg->pr.pr_info.residx;
8555		else
8556			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8557	}
8558	lun->PRGeneration++;
8559
8560}
8561
8562
8563int
8564ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8565{
8566	int retval;
8567	int isc_retval;
8568	u_int32_t param_len;
8569	struct scsi_per_res_out *cdb;
8570	struct ctl_lun *lun;
8571	struct scsi_per_res_out_parms* param;
8572	struct ctl_softc *softc;
8573	uint32_t residx;
8574	uint64_t res_key, sa_res_key;
8575	uint8_t type;
8576	union ctl_ha_msg persis_io;
8577	int    i;
8578
8579	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8580
8581	retval = CTL_RETVAL_COMPLETE;
8582
8583	softc = control_softc;
8584
8585	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8586	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8587
8588	/*
8589	 * We only support whole-LUN scope.  The scope & type are ignored for
8590	 * register, register and ignore existing key and clear.
8591	 * We sometimes ignore scope and type on preempts too!!
8592	 * Verify reservation type here as well.
8593	 */
8594	type = cdb->scope_type & SPR_TYPE_MASK;
8595	if ((cdb->action == SPRO_RESERVE)
8596	 || (cdb->action == SPRO_RELEASE)) {
8597		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8598			ctl_set_invalid_field(/*ctsio*/ ctsio,
8599					      /*sks_valid*/ 1,
8600					      /*command*/ 1,
8601					      /*field*/ 2,
8602					      /*bit_valid*/ 1,
8603					      /*bit*/ 4);
8604			ctl_done((union ctl_io *)ctsio);
8605			return (CTL_RETVAL_COMPLETE);
8606		}
8607
8608		if (type>8 || type==2 || type==4 || type==0) {
8609			ctl_set_invalid_field(/*ctsio*/ ctsio,
8610					      /*sks_valid*/ 1,
8611					      /*command*/ 1,
8612					      /*field*/ 2,
8613					      /*bit_valid*/ 1,
8614					      /*bit*/ 0);
8615			ctl_done((union ctl_io *)ctsio);
8616			return (CTL_RETVAL_COMPLETE);
8617		}
8618	}
8619
8620	param_len = scsi_4btoul(cdb->length);
8621
8622	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8623		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8624		ctsio->kern_data_len = param_len;
8625		ctsio->kern_total_len = param_len;
8626		ctsio->kern_data_resid = 0;
8627		ctsio->kern_rel_offset = 0;
8628		ctsio->kern_sg_entries = 0;
8629		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8630		ctsio->be_move_done = ctl_config_move_done;
8631		ctl_datamove((union ctl_io *)ctsio);
8632
8633		return (CTL_RETVAL_COMPLETE);
8634	}
8635
8636	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8637
8638	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8639	res_key = scsi_8btou64(param->res_key.key);
8640	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8641
8642	/*
8643	 * Validate the reservation key here except for SPRO_REG_IGNO
8644	 * This must be done for all other service actions
8645	 */
8646	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8647		mtx_lock(&lun->lun_lock);
8648		if (lun->pr_keys[residx] != 0) {
8649		    if (res_key != lun->pr_keys[residx]) {
8650				/*
8651				 * The current key passed in doesn't match
8652				 * the one the initiator previously
8653				 * registered.
8654				 */
8655				mtx_unlock(&lun->lun_lock);
8656				free(ctsio->kern_data_ptr, M_CTL);
8657				ctl_set_reservation_conflict(ctsio);
8658				ctl_done((union ctl_io *)ctsio);
8659				return (CTL_RETVAL_COMPLETE);
8660			}
8661		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8662			/*
8663			 * We are not registered
8664			 */
8665			mtx_unlock(&lun->lun_lock);
8666			free(ctsio->kern_data_ptr, M_CTL);
8667			ctl_set_reservation_conflict(ctsio);
8668			ctl_done((union ctl_io *)ctsio);
8669			return (CTL_RETVAL_COMPLETE);
8670		} else if (res_key != 0) {
8671			/*
8672			 * We are not registered and trying to register but
8673			 * the register key isn't zero.
8674			 */
8675			mtx_unlock(&lun->lun_lock);
8676			free(ctsio->kern_data_ptr, M_CTL);
8677			ctl_set_reservation_conflict(ctsio);
8678			ctl_done((union ctl_io *)ctsio);
8679			return (CTL_RETVAL_COMPLETE);
8680		}
8681		mtx_unlock(&lun->lun_lock);
8682	}
8683
8684	switch (cdb->action & SPRO_ACTION_MASK) {
8685	case SPRO_REGISTER:
8686	case SPRO_REG_IGNO: {
8687
8688#if 0
8689		printf("Registration received\n");
8690#endif
8691
8692		/*
8693		 * We don't support any of these options, as we report in
8694		 * the read capabilities request (see
8695		 * ctl_persistent_reserve_in(), above).
8696		 */
8697		if ((param->flags & SPR_SPEC_I_PT)
8698		 || (param->flags & SPR_ALL_TG_PT)
8699		 || (param->flags & SPR_APTPL)) {
8700			int bit_ptr;
8701
8702			if (param->flags & SPR_APTPL)
8703				bit_ptr = 0;
8704			else if (param->flags & SPR_ALL_TG_PT)
8705				bit_ptr = 2;
8706			else /* SPR_SPEC_I_PT */
8707				bit_ptr = 3;
8708
8709			free(ctsio->kern_data_ptr, M_CTL);
8710			ctl_set_invalid_field(ctsio,
8711					      /*sks_valid*/ 1,
8712					      /*command*/ 0,
8713					      /*field*/ 20,
8714					      /*bit_valid*/ 1,
8715					      /*bit*/ bit_ptr);
8716			ctl_done((union ctl_io *)ctsio);
8717			return (CTL_RETVAL_COMPLETE);
8718		}
8719
8720		mtx_lock(&lun->lun_lock);
8721
8722		/*
8723		 * The initiator wants to clear the
8724		 * key/unregister.
8725		 */
8726		if (sa_res_key == 0) {
8727			if ((res_key == 0
8728			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8729			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8730			  && lun->pr_keys[residx] == 0)) {
8731				mtx_unlock(&lun->lun_lock);
8732				goto done;
8733			}
8734
8735			lun->pr_keys[residx] = 0;
8736			lun->pr_key_count--;
8737
8738			if (residx == lun->pr_res_idx) {
8739				lun->flags &= ~CTL_LUN_PR_RESERVED;
8740				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8741
8742				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8743				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8744				 && lun->pr_key_count) {
8745					/*
8746					 * If the reservation is a registrants
8747					 * only type we need to generate a UA
8748					 * for other registered inits.  The
8749					 * sense code should be RESERVATIONS
8750					 * RELEASED
8751					 */
8752
8753					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8754						if (lun->pr_keys[
8755						    i + persis_offset] == 0)
8756							continue;
8757						lun->pending_ua[i] |=
8758							CTL_UA_RES_RELEASE;
8759					}
8760				}
8761				lun->res_type = 0;
8762			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8763				if (lun->pr_key_count==0) {
8764					lun->flags &= ~CTL_LUN_PR_RESERVED;
8765					lun->res_type = 0;
8766					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8767				}
8768			}
8769			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8770			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8771			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8772			persis_io.pr.pr_info.residx = residx;
8773			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8774			     &persis_io, sizeof(persis_io), 0 )) >
8775			     CTL_HA_STATUS_SUCCESS) {
8776				printf("CTL:Persis Out error returned from "
8777				       "ctl_ha_msg_send %d\n", isc_retval);
8778			}
8779		} else /* sa_res_key != 0 */ {
8780
8781			/*
8782			 * If we aren't registered currently then increment
8783			 * the key count and set the registered flag.
8784			 */
8785			if (lun->pr_keys[residx] == 0)
8786				lun->pr_key_count++;
8787			lun->pr_keys[residx] = sa_res_key;
8788
8789			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8790			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8791			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8792			persis_io.pr.pr_info.residx = residx;
8793			memcpy(persis_io.pr.pr_info.sa_res_key,
8794			       param->serv_act_res_key,
8795			       sizeof(param->serv_act_res_key));
8796			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8797			     &persis_io, sizeof(persis_io), 0)) >
8798			     CTL_HA_STATUS_SUCCESS) {
8799				printf("CTL:Persis Out error returned from "
8800				       "ctl_ha_msg_send %d\n", isc_retval);
8801			}
8802		}
8803		lun->PRGeneration++;
8804		mtx_unlock(&lun->lun_lock);
8805
8806		break;
8807	}
8808	case SPRO_RESERVE:
8809#if 0
8810                printf("Reserve executed type %d\n", type);
8811#endif
8812		mtx_lock(&lun->lun_lock);
8813		if (lun->flags & CTL_LUN_PR_RESERVED) {
8814			/*
8815			 * if this isn't the reservation holder and it's
8816			 * not a "all registrants" type or if the type is
8817			 * different then we have a conflict
8818			 */
8819			if ((lun->pr_res_idx != residx
8820			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8821			 || lun->res_type != type) {
8822				mtx_unlock(&lun->lun_lock);
8823				free(ctsio->kern_data_ptr, M_CTL);
8824				ctl_set_reservation_conflict(ctsio);
8825				ctl_done((union ctl_io *)ctsio);
8826				return (CTL_RETVAL_COMPLETE);
8827			}
8828			mtx_unlock(&lun->lun_lock);
8829		} else /* create a reservation */ {
8830			/*
8831			 * If it's not an "all registrants" type record
8832			 * reservation holder
8833			 */
8834			if (type != SPR_TYPE_WR_EX_AR
8835			 && type != SPR_TYPE_EX_AC_AR)
8836				lun->pr_res_idx = residx; /* Res holder */
8837			else
8838				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8839
8840			lun->flags |= CTL_LUN_PR_RESERVED;
8841			lun->res_type = type;
8842
8843			mtx_unlock(&lun->lun_lock);
8844
8845			/* send msg to other side */
8846			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8847			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8848			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8849			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8850			persis_io.pr.pr_info.res_type = type;
8851			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8852			     &persis_io, sizeof(persis_io), 0)) >
8853			     CTL_HA_STATUS_SUCCESS) {
8854				printf("CTL:Persis Out error returned from "
8855				       "ctl_ha_msg_send %d\n", isc_retval);
8856			}
8857		}
8858		break;
8859
8860	case SPRO_RELEASE:
8861		mtx_lock(&lun->lun_lock);
8862		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8863			/* No reservation exists return good status */
8864			mtx_unlock(&lun->lun_lock);
8865			goto done;
8866		}
8867		/*
8868		 * Is this nexus a reservation holder?
8869		 */
8870		if (lun->pr_res_idx != residx
8871		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8872			/*
8873			 * not a res holder return good status but
8874			 * do nothing
8875			 */
8876			mtx_unlock(&lun->lun_lock);
8877			goto done;
8878		}
8879
8880		if (lun->res_type != type) {
8881			mtx_unlock(&lun->lun_lock);
8882			free(ctsio->kern_data_ptr, M_CTL);
8883			ctl_set_illegal_pr_release(ctsio);
8884			ctl_done((union ctl_io *)ctsio);
8885			return (CTL_RETVAL_COMPLETE);
8886		}
8887
8888		/* okay to release */
8889		lun->flags &= ~CTL_LUN_PR_RESERVED;
8890		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8891		lun->res_type = 0;
8892
8893		/*
8894		 * if this isn't an exclusive access
8895		 * res generate UA for all other
8896		 * registrants.
8897		 */
8898		if (type != SPR_TYPE_EX_AC
8899		 && type != SPR_TYPE_WR_EX) {
8900			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8901				if (i == residx ||
8902				    lun->pr_keys[i + persis_offset] == 0)
8903					continue;
8904				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8905			}
8906		}
8907		mtx_unlock(&lun->lun_lock);
8908		/* Send msg to other side */
8909		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8910		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8911		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8912		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8913		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8914			printf("CTL:Persis Out error returned from "
8915			       "ctl_ha_msg_send %d\n", isc_retval);
8916		}
8917		break;
8918
8919	case SPRO_CLEAR:
8920		/* send msg to other side */
8921
8922		mtx_lock(&lun->lun_lock);
8923		lun->flags &= ~CTL_LUN_PR_RESERVED;
8924		lun->res_type = 0;
8925		lun->pr_key_count = 0;
8926		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8927
8928		lun->pr_keys[residx] = 0;
8929
8930		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8931			if (lun->pr_keys[i] != 0) {
8932				if (!persis_offset && i < CTL_MAX_INITIATORS)
8933					lun->pending_ua[i] |=
8934						CTL_UA_RES_PREEMPT;
8935				else if (persis_offset && i >= persis_offset)
8936					lun->pending_ua[i-persis_offset] |=
8937					    CTL_UA_RES_PREEMPT;
8938
8939				lun->pr_keys[i] = 0;
8940			}
8941		lun->PRGeneration++;
8942		mtx_unlock(&lun->lun_lock);
8943		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8944		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8945		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8946		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8947		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8948			printf("CTL:Persis Out error returned from "
8949			       "ctl_ha_msg_send %d\n", isc_retval);
8950		}
8951		break;
8952
8953	case SPRO_PREEMPT: {
8954		int nretval;
8955
8956		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8957					  residx, ctsio, cdb, param);
8958		if (nretval != 0)
8959			return (CTL_RETVAL_COMPLETE);
8960		break;
8961	}
8962	default:
8963		panic("Invalid PR type %x", cdb->action);
8964	}
8965
8966done:
8967	free(ctsio->kern_data_ptr, M_CTL);
8968	ctl_set_success(ctsio);
8969	ctl_done((union ctl_io *)ctsio);
8970
8971	return (retval);
8972}
8973
8974/*
8975 * This routine is for handling a message from the other SC pertaining to
8976 * persistent reserve out. All the error checking will have been done
8977 * so only perorming the action need be done here to keep the two
8978 * in sync.
8979 */
8980static void
8981ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8982{
8983	struct ctl_lun *lun;
8984	struct ctl_softc *softc;
8985	int i;
8986	uint32_t targ_lun;
8987
8988	softc = control_softc;
8989
8990	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8991	lun = softc->ctl_luns[targ_lun];
8992	mtx_lock(&lun->lun_lock);
8993	switch(msg->pr.pr_info.action) {
8994	case CTL_PR_REG_KEY:
8995		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8996			lun->pr_key_count++;
8997		lun->pr_keys[msg->pr.pr_info.residx] =
8998		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8999		lun->PRGeneration++;
9000		break;
9001
9002	case CTL_PR_UNREG_KEY:
9003		lun->pr_keys[msg->pr.pr_info.residx] = 0;
9004		lun->pr_key_count--;
9005
9006		/* XXX Need to see if the reservation has been released */
9007		/* if so do we need to generate UA? */
9008		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
9009			lun->flags &= ~CTL_LUN_PR_RESERVED;
9010			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9011
9012			if ((lun->res_type == SPR_TYPE_WR_EX_RO
9013			  || lun->res_type == SPR_TYPE_EX_AC_RO)
9014			 && lun->pr_key_count) {
9015				/*
9016				 * If the reservation is a registrants
9017				 * only type we need to generate a UA
9018				 * for other registered inits.  The
9019				 * sense code should be RESERVATIONS
9020				 * RELEASED
9021				 */
9022
9023				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
9024					if (lun->pr_keys[i+
9025					    persis_offset] == 0)
9026						continue;
9027
9028					lun->pending_ua[i] |=
9029						CTL_UA_RES_RELEASE;
9030				}
9031			}
9032			lun->res_type = 0;
9033		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
9034			if (lun->pr_key_count==0) {
9035				lun->flags &= ~CTL_LUN_PR_RESERVED;
9036				lun->res_type = 0;
9037				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9038			}
9039		}
9040		lun->PRGeneration++;
9041		break;
9042
9043	case CTL_PR_RESERVE:
9044		lun->flags |= CTL_LUN_PR_RESERVED;
9045		lun->res_type = msg->pr.pr_info.res_type;
9046		lun->pr_res_idx = msg->pr.pr_info.residx;
9047
9048		break;
9049
9050	case CTL_PR_RELEASE:
9051		/*
9052		 * if this isn't an exclusive access res generate UA for all
9053		 * other registrants.
9054		 */
9055		if (lun->res_type != SPR_TYPE_EX_AC
9056		 && lun->res_type != SPR_TYPE_WR_EX) {
9057			for (i = 0; i < CTL_MAX_INITIATORS; i++)
9058				if (lun->pr_keys[i+persis_offset] != 0)
9059					lun->pending_ua[i] |=
9060						CTL_UA_RES_RELEASE;
9061		}
9062
9063		lun->flags &= ~CTL_LUN_PR_RESERVED;
9064		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9065		lun->res_type = 0;
9066		break;
9067
9068	case CTL_PR_PREEMPT:
9069		ctl_pro_preempt_other(lun, msg);
9070		break;
9071	case CTL_PR_CLEAR:
9072		lun->flags &= ~CTL_LUN_PR_RESERVED;
9073		lun->res_type = 0;
9074		lun->pr_key_count = 0;
9075		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9076
9077		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9078			if (lun->pr_keys[i] == 0)
9079				continue;
9080			if (!persis_offset
9081			 && i < CTL_MAX_INITIATORS)
9082				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9083			else if (persis_offset
9084			      && i >= persis_offset)
9085				lun->pending_ua[i-persis_offset] |=
9086					CTL_UA_RES_PREEMPT;
9087			lun->pr_keys[i] = 0;
9088		}
9089		lun->PRGeneration++;
9090		break;
9091	}
9092
9093	mtx_unlock(&lun->lun_lock);
9094}
9095
9096int
9097ctl_read_write(struct ctl_scsiio *ctsio)
9098{
9099	struct ctl_lun *lun;
9100	struct ctl_lba_len_flags *lbalen;
9101	uint64_t lba;
9102	uint32_t num_blocks;
9103	int flags, retval;
9104	int isread;
9105
9106	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9107
9108	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9109
9110	flags = 0;
9111	retval = CTL_RETVAL_COMPLETE;
9112
9113	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9114	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9115	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9116		uint32_t residx;
9117
9118		/*
9119		 * XXX KDM need a lock here.
9120		 */
9121		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9122		if ((lun->res_type == SPR_TYPE_EX_AC
9123		  && residx != lun->pr_res_idx)
9124		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9125		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9126		  && lun->pr_keys[residx] == 0)) {
9127			ctl_set_reservation_conflict(ctsio);
9128			ctl_done((union ctl_io *)ctsio);
9129			return (CTL_RETVAL_COMPLETE);
9130	        }
9131	}
9132
9133	switch (ctsio->cdb[0]) {
9134	case READ_6:
9135	case WRITE_6: {
9136		struct scsi_rw_6 *cdb;
9137
9138		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9139
9140		lba = scsi_3btoul(cdb->addr);
9141		/* only 5 bits are valid in the most significant address byte */
9142		lba &= 0x1fffff;
9143		num_blocks = cdb->length;
9144		/*
9145		 * This is correct according to SBC-2.
9146		 */
9147		if (num_blocks == 0)
9148			num_blocks = 256;
9149		break;
9150	}
9151	case READ_10:
9152	case WRITE_10: {
9153		struct scsi_rw_10 *cdb;
9154
9155		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9156		if (cdb->byte2 & SRW10_FUA)
9157			flags |= CTL_LLF_FUA;
9158		if (cdb->byte2 & SRW10_DPO)
9159			flags |= CTL_LLF_DPO;
9160		lba = scsi_4btoul(cdb->addr);
9161		num_blocks = scsi_2btoul(cdb->length);
9162		break;
9163	}
9164	case WRITE_VERIFY_10: {
9165		struct scsi_write_verify_10 *cdb;
9166
9167		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9168		flags |= CTL_LLF_FUA;
9169		if (cdb->byte2 & SWV_DPO)
9170			flags |= CTL_LLF_DPO;
9171		lba = scsi_4btoul(cdb->addr);
9172		num_blocks = scsi_2btoul(cdb->length);
9173		break;
9174	}
9175	case READ_12:
9176	case WRITE_12: {
9177		struct scsi_rw_12 *cdb;
9178
9179		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9180		if (cdb->byte2 & SRW12_FUA)
9181			flags |= CTL_LLF_FUA;
9182		if (cdb->byte2 & SRW12_DPO)
9183			flags |= CTL_LLF_DPO;
9184		lba = scsi_4btoul(cdb->addr);
9185		num_blocks = scsi_4btoul(cdb->length);
9186		break;
9187	}
9188	case WRITE_VERIFY_12: {
9189		struct scsi_write_verify_12 *cdb;
9190
9191		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9192		flags |= CTL_LLF_FUA;
9193		if (cdb->byte2 & SWV_DPO)
9194			flags |= CTL_LLF_DPO;
9195		lba = scsi_4btoul(cdb->addr);
9196		num_blocks = scsi_4btoul(cdb->length);
9197		break;
9198	}
9199	case READ_16:
9200	case WRITE_16: {
9201		struct scsi_rw_16 *cdb;
9202
9203		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9204		if (cdb->byte2 & SRW12_FUA)
9205			flags |= CTL_LLF_FUA;
9206		if (cdb->byte2 & SRW12_DPO)
9207			flags |= CTL_LLF_DPO;
9208		lba = scsi_8btou64(cdb->addr);
9209		num_blocks = scsi_4btoul(cdb->length);
9210		break;
9211	}
9212	case WRITE_ATOMIC_16: {
9213		struct scsi_rw_16 *cdb;
9214
9215		if (lun->be_lun->atomicblock == 0) {
9216			ctl_set_invalid_opcode(ctsio);
9217			ctl_done((union ctl_io *)ctsio);
9218			return (CTL_RETVAL_COMPLETE);
9219		}
9220
9221		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9222		if (cdb->byte2 & SRW12_FUA)
9223			flags |= CTL_LLF_FUA;
9224		if (cdb->byte2 & SRW12_DPO)
9225			flags |= CTL_LLF_DPO;
9226		lba = scsi_8btou64(cdb->addr);
9227		num_blocks = scsi_4btoul(cdb->length);
9228		if (num_blocks > lun->be_lun->atomicblock) {
9229			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9230			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9231			    /*bit*/ 0);
9232			ctl_done((union ctl_io *)ctsio);
9233			return (CTL_RETVAL_COMPLETE);
9234		}
9235		break;
9236	}
9237	case WRITE_VERIFY_16: {
9238		struct scsi_write_verify_16 *cdb;
9239
9240		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9241		flags |= CTL_LLF_FUA;
9242		if (cdb->byte2 & SWV_DPO)
9243			flags |= CTL_LLF_DPO;
9244		lba = scsi_8btou64(cdb->addr);
9245		num_blocks = scsi_4btoul(cdb->length);
9246		break;
9247	}
9248	default:
9249		/*
9250		 * We got a command we don't support.  This shouldn't
9251		 * happen, commands should be filtered out above us.
9252		 */
9253		ctl_set_invalid_opcode(ctsio);
9254		ctl_done((union ctl_io *)ctsio);
9255
9256		return (CTL_RETVAL_COMPLETE);
9257		break; /* NOTREACHED */
9258	}
9259
9260	/*
9261	 * The first check is to make sure we're in bounds, the second
9262	 * check is to catch wrap-around problems.  If the lba + num blocks
9263	 * is less than the lba, then we've wrapped around and the block
9264	 * range is invalid anyway.
9265	 */
9266	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9267	 || ((lba + num_blocks) < lba)) {
9268		ctl_set_lba_out_of_range(ctsio);
9269		ctl_done((union ctl_io *)ctsio);
9270		return (CTL_RETVAL_COMPLETE);
9271	}
9272
9273	/*
9274	 * According to SBC-3, a transfer length of 0 is not an error.
9275	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9276	 * translates to 256 blocks for those commands.
9277	 */
9278	if (num_blocks == 0) {
9279		ctl_set_success(ctsio);
9280		ctl_done((union ctl_io *)ctsio);
9281		return (CTL_RETVAL_COMPLETE);
9282	}
9283
9284	/* Set FUA and/or DPO if caches are disabled. */
9285	if (isread) {
9286		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9287		    SCP_RCD) != 0)
9288			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9289	} else {
9290		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9291		    SCP_WCE) == 0)
9292			flags |= CTL_LLF_FUA;
9293	}
9294
9295	lbalen = (struct ctl_lba_len_flags *)
9296	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9297	lbalen->lba = lba;
9298	lbalen->len = num_blocks;
9299	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9300
9301	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9302	ctsio->kern_rel_offset = 0;
9303
9304	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9305
9306	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9307
9308	return (retval);
9309}
9310
9311static int
9312ctl_cnw_cont(union ctl_io *io)
9313{
9314	struct ctl_scsiio *ctsio;
9315	struct ctl_lun *lun;
9316	struct ctl_lba_len_flags *lbalen;
9317	int retval;
9318
9319	ctsio = &io->scsiio;
9320	ctsio->io_hdr.status = CTL_STATUS_NONE;
9321	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9322	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9323	lbalen = (struct ctl_lba_len_flags *)
9324	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9325	lbalen->flags &= ~CTL_LLF_COMPARE;
9326	lbalen->flags |= CTL_LLF_WRITE;
9327
9328	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9329	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9330	return (retval);
9331}
9332
9333int
9334ctl_cnw(struct ctl_scsiio *ctsio)
9335{
9336	struct ctl_lun *lun;
9337	struct ctl_lba_len_flags *lbalen;
9338	uint64_t lba;
9339	uint32_t num_blocks;
9340	int flags, retval;
9341
9342	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9343
9344	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9345
9346	flags = 0;
9347	retval = CTL_RETVAL_COMPLETE;
9348
9349	switch (ctsio->cdb[0]) {
9350	case COMPARE_AND_WRITE: {
9351		struct scsi_compare_and_write *cdb;
9352
9353		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9354		if (cdb->byte2 & SRW10_FUA)
9355			flags |= CTL_LLF_FUA;
9356		if (cdb->byte2 & SRW10_DPO)
9357			flags |= CTL_LLF_DPO;
9358		lba = scsi_8btou64(cdb->addr);
9359		num_blocks = cdb->length;
9360		break;
9361	}
9362	default:
9363		/*
9364		 * We got a command we don't support.  This shouldn't
9365		 * happen, commands should be filtered out above us.
9366		 */
9367		ctl_set_invalid_opcode(ctsio);
9368		ctl_done((union ctl_io *)ctsio);
9369
9370		return (CTL_RETVAL_COMPLETE);
9371		break; /* NOTREACHED */
9372	}
9373
9374	/*
9375	 * The first check is to make sure we're in bounds, the second
9376	 * check is to catch wrap-around problems.  If the lba + num blocks
9377	 * is less than the lba, then we've wrapped around and the block
9378	 * range is invalid anyway.
9379	 */
9380	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9381	 || ((lba + num_blocks) < lba)) {
9382		ctl_set_lba_out_of_range(ctsio);
9383		ctl_done((union ctl_io *)ctsio);
9384		return (CTL_RETVAL_COMPLETE);
9385	}
9386
9387	/*
9388	 * According to SBC-3, a transfer length of 0 is not an error.
9389	 */
9390	if (num_blocks == 0) {
9391		ctl_set_success(ctsio);
9392		ctl_done((union ctl_io *)ctsio);
9393		return (CTL_RETVAL_COMPLETE);
9394	}
9395
9396	/* Set FUA if write cache is disabled. */
9397	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9398	    SCP_WCE) == 0)
9399		flags |= CTL_LLF_FUA;
9400
9401	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9402	ctsio->kern_rel_offset = 0;
9403
9404	/*
9405	 * Set the IO_CONT flag, so that if this I/O gets passed to
9406	 * ctl_data_submit_done(), it'll get passed back to
9407	 * ctl_ctl_cnw_cont() for further processing.
9408	 */
9409	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9410	ctsio->io_cont = ctl_cnw_cont;
9411
9412	lbalen = (struct ctl_lba_len_flags *)
9413	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9414	lbalen->lba = lba;
9415	lbalen->len = num_blocks;
9416	lbalen->flags = CTL_LLF_COMPARE | flags;
9417
9418	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9419	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9420	return (retval);
9421}
9422
9423int
9424ctl_verify(struct ctl_scsiio *ctsio)
9425{
9426	struct ctl_lun *lun;
9427	struct ctl_lba_len_flags *lbalen;
9428	uint64_t lba;
9429	uint32_t num_blocks;
9430	int bytchk, flags;
9431	int retval;
9432
9433	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9434
9435	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9436
9437	bytchk = 0;
9438	flags = CTL_LLF_FUA;
9439	retval = CTL_RETVAL_COMPLETE;
9440
9441	switch (ctsio->cdb[0]) {
9442	case VERIFY_10: {
9443		struct scsi_verify_10 *cdb;
9444
9445		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9446		if (cdb->byte2 & SVFY_BYTCHK)
9447			bytchk = 1;
9448		if (cdb->byte2 & SVFY_DPO)
9449			flags |= CTL_LLF_DPO;
9450		lba = scsi_4btoul(cdb->addr);
9451		num_blocks = scsi_2btoul(cdb->length);
9452		break;
9453	}
9454	case VERIFY_12: {
9455		struct scsi_verify_12 *cdb;
9456
9457		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9458		if (cdb->byte2 & SVFY_BYTCHK)
9459			bytchk = 1;
9460		if (cdb->byte2 & SVFY_DPO)
9461			flags |= CTL_LLF_DPO;
9462		lba = scsi_4btoul(cdb->addr);
9463		num_blocks = scsi_4btoul(cdb->length);
9464		break;
9465	}
9466	case VERIFY_16: {
9467		struct scsi_rw_16 *cdb;
9468
9469		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9470		if (cdb->byte2 & SVFY_BYTCHK)
9471			bytchk = 1;
9472		if (cdb->byte2 & SVFY_DPO)
9473			flags |= CTL_LLF_DPO;
9474		lba = scsi_8btou64(cdb->addr);
9475		num_blocks = scsi_4btoul(cdb->length);
9476		break;
9477	}
9478	default:
9479		/*
9480		 * We got a command we don't support.  This shouldn't
9481		 * happen, commands should be filtered out above us.
9482		 */
9483		ctl_set_invalid_opcode(ctsio);
9484		ctl_done((union ctl_io *)ctsio);
9485		return (CTL_RETVAL_COMPLETE);
9486	}
9487
9488	/*
9489	 * The first check is to make sure we're in bounds, the second
9490	 * check is to catch wrap-around problems.  If the lba + num blocks
9491	 * is less than the lba, then we've wrapped around and the block
9492	 * range is invalid anyway.
9493	 */
9494	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9495	 || ((lba + num_blocks) < lba)) {
9496		ctl_set_lba_out_of_range(ctsio);
9497		ctl_done((union ctl_io *)ctsio);
9498		return (CTL_RETVAL_COMPLETE);
9499	}
9500
9501	/*
9502	 * According to SBC-3, a transfer length of 0 is not an error.
9503	 */
9504	if (num_blocks == 0) {
9505		ctl_set_success(ctsio);
9506		ctl_done((union ctl_io *)ctsio);
9507		return (CTL_RETVAL_COMPLETE);
9508	}
9509
9510	lbalen = (struct ctl_lba_len_flags *)
9511	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9512	lbalen->lba = lba;
9513	lbalen->len = num_blocks;
9514	if (bytchk) {
9515		lbalen->flags = CTL_LLF_COMPARE | flags;
9516		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9517	} else {
9518		lbalen->flags = CTL_LLF_VERIFY | flags;
9519		ctsio->kern_total_len = 0;
9520	}
9521	ctsio->kern_rel_offset = 0;
9522
9523	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9524	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9525	return (retval);
9526}
9527
9528int
9529ctl_report_luns(struct ctl_scsiio *ctsio)
9530{
9531	struct scsi_report_luns *cdb;
9532	struct scsi_report_luns_data *lun_data;
9533	struct ctl_lun *lun, *request_lun;
9534	int num_luns, retval;
9535	uint32_t alloc_len, lun_datalen;
9536	int num_filled, well_known;
9537	uint32_t initidx, targ_lun_id, lun_id;
9538
9539	retval = CTL_RETVAL_COMPLETE;
9540	well_known = 0;
9541
9542	cdb = (struct scsi_report_luns *)ctsio->cdb;
9543
9544	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9545
9546	mtx_lock(&control_softc->ctl_lock);
9547	num_luns = control_softc->num_luns;
9548	mtx_unlock(&control_softc->ctl_lock);
9549
9550	switch (cdb->select_report) {
9551	case RPL_REPORT_DEFAULT:
9552	case RPL_REPORT_ALL:
9553		break;
9554	case RPL_REPORT_WELLKNOWN:
9555		well_known = 1;
9556		num_luns = 0;
9557		break;
9558	default:
9559		ctl_set_invalid_field(ctsio,
9560				      /*sks_valid*/ 1,
9561				      /*command*/ 1,
9562				      /*field*/ 2,
9563				      /*bit_valid*/ 0,
9564				      /*bit*/ 0);
9565		ctl_done((union ctl_io *)ctsio);
9566		return (retval);
9567		break; /* NOTREACHED */
9568	}
9569
9570	alloc_len = scsi_4btoul(cdb->length);
9571	/*
9572	 * The initiator has to allocate at least 16 bytes for this request,
9573	 * so he can at least get the header and the first LUN.  Otherwise
9574	 * we reject the request (per SPC-3 rev 14, section 6.21).
9575	 */
9576	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9577	    sizeof(struct scsi_report_luns_lundata))) {
9578		ctl_set_invalid_field(ctsio,
9579				      /*sks_valid*/ 1,
9580				      /*command*/ 1,
9581				      /*field*/ 6,
9582				      /*bit_valid*/ 0,
9583				      /*bit*/ 0);
9584		ctl_done((union ctl_io *)ctsio);
9585		return (retval);
9586	}
9587
9588	request_lun = (struct ctl_lun *)
9589		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9590
9591	lun_datalen = sizeof(*lun_data) +
9592		(num_luns * sizeof(struct scsi_report_luns_lundata));
9593
9594	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9595	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9596	ctsio->kern_sg_entries = 0;
9597
9598	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9599
9600	mtx_lock(&control_softc->ctl_lock);
9601	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9602		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9603		if (lun_id >= CTL_MAX_LUNS)
9604			continue;
9605		lun = control_softc->ctl_luns[lun_id];
9606		if (lun == NULL)
9607			continue;
9608
9609		if (targ_lun_id <= 0xff) {
9610			/*
9611			 * Peripheral addressing method, bus number 0.
9612			 */
9613			lun_data->luns[num_filled].lundata[0] =
9614				RPL_LUNDATA_ATYP_PERIPH;
9615			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9616			num_filled++;
9617		} else if (targ_lun_id <= 0x3fff) {
9618			/*
9619			 * Flat addressing method.
9620			 */
9621			lun_data->luns[num_filled].lundata[0] =
9622				RPL_LUNDATA_ATYP_FLAT |
9623				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9624#ifdef OLDCTLHEADERS
9625				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9626				(targ_lun_id & SRLD_BUS_LUN_MASK);
9627#endif
9628			lun_data->luns[num_filled].lundata[1] =
9629#ifdef OLDCTLHEADERS
9630				targ_lun_id >> SRLD_BUS_LUN_BITS;
9631#endif
9632				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9633			num_filled++;
9634		} else {
9635			printf("ctl_report_luns: bogus LUN number %jd, "
9636			       "skipping\n", (intmax_t)targ_lun_id);
9637		}
9638		/*
9639		 * According to SPC-3, rev 14 section 6.21:
9640		 *
9641		 * "The execution of a REPORT LUNS command to any valid and
9642		 * installed logical unit shall clear the REPORTED LUNS DATA
9643		 * HAS CHANGED unit attention condition for all logical
9644		 * units of that target with respect to the requesting
9645		 * initiator. A valid and installed logical unit is one
9646		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9647		 * INQUIRY data (see 6.4.2)."
9648		 *
9649		 * If request_lun is NULL, the LUN this report luns command
9650		 * was issued to is either disabled or doesn't exist. In that
9651		 * case, we shouldn't clear any pending lun change unit
9652		 * attention.
9653		 */
9654		if (request_lun != NULL) {
9655			mtx_lock(&lun->lun_lock);
9656			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9657			mtx_unlock(&lun->lun_lock);
9658		}
9659	}
9660	mtx_unlock(&control_softc->ctl_lock);
9661
9662	/*
9663	 * It's quite possible that we've returned fewer LUNs than we allocated
9664	 * space for.  Trim it.
9665	 */
9666	lun_datalen = sizeof(*lun_data) +
9667		(num_filled * sizeof(struct scsi_report_luns_lundata));
9668
9669	if (lun_datalen < alloc_len) {
9670		ctsio->residual = alloc_len - lun_datalen;
9671		ctsio->kern_data_len = lun_datalen;
9672		ctsio->kern_total_len = lun_datalen;
9673	} else {
9674		ctsio->residual = 0;
9675		ctsio->kern_data_len = alloc_len;
9676		ctsio->kern_total_len = alloc_len;
9677	}
9678	ctsio->kern_data_resid = 0;
9679	ctsio->kern_rel_offset = 0;
9680	ctsio->kern_sg_entries = 0;
9681
9682	/*
9683	 * We set this to the actual data length, regardless of how much
9684	 * space we actually have to return results.  If the user looks at
9685	 * this value, he'll know whether or not he allocated enough space
9686	 * and reissue the command if necessary.  We don't support well
9687	 * known logical units, so if the user asks for that, return none.
9688	 */
9689	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9690
9691	/*
9692	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9693	 * this request.
9694	 */
9695	ctsio->scsi_status = SCSI_STATUS_OK;
9696
9697	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9698	ctsio->be_move_done = ctl_config_move_done;
9699	ctl_datamove((union ctl_io *)ctsio);
9700
9701	return (retval);
9702}
9703
9704int
9705ctl_request_sense(struct ctl_scsiio *ctsio)
9706{
9707	struct scsi_request_sense *cdb;
9708	struct scsi_sense_data *sense_ptr;
9709	struct ctl_lun *lun;
9710	uint32_t initidx;
9711	int have_error;
9712	scsi_sense_data_type sense_format;
9713
9714	cdb = (struct scsi_request_sense *)ctsio->cdb;
9715
9716	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9717
9718	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9719
9720	/*
9721	 * Determine which sense format the user wants.
9722	 */
9723	if (cdb->byte2 & SRS_DESC)
9724		sense_format = SSD_TYPE_DESC;
9725	else
9726		sense_format = SSD_TYPE_FIXED;
9727
9728	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9729	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9730	ctsio->kern_sg_entries = 0;
9731
9732	/*
9733	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9734	 * larger than the largest allowed value for the length field in the
9735	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9736	 */
9737	ctsio->residual = 0;
9738	ctsio->kern_data_len = cdb->length;
9739	ctsio->kern_total_len = cdb->length;
9740
9741	ctsio->kern_data_resid = 0;
9742	ctsio->kern_rel_offset = 0;
9743	ctsio->kern_sg_entries = 0;
9744
9745	/*
9746	 * If we don't have a LUN, we don't have any pending sense.
9747	 */
9748	if (lun == NULL)
9749		goto no_sense;
9750
9751	have_error = 0;
9752	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9753	/*
9754	 * Check for pending sense, and then for pending unit attentions.
9755	 * Pending sense gets returned first, then pending unit attentions.
9756	 */
9757	mtx_lock(&lun->lun_lock);
9758#ifdef CTL_WITH_CA
9759	if (ctl_is_set(lun->have_ca, initidx)) {
9760		scsi_sense_data_type stored_format;
9761
9762		/*
9763		 * Check to see which sense format was used for the stored
9764		 * sense data.
9765		 */
9766		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9767
9768		/*
9769		 * If the user requested a different sense format than the
9770		 * one we stored, then we need to convert it to the other
9771		 * format.  If we're going from descriptor to fixed format
9772		 * sense data, we may lose things in translation, depending
9773		 * on what options were used.
9774		 *
9775		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9776		 * for some reason we'll just copy it out as-is.
9777		 */
9778		if ((stored_format == SSD_TYPE_FIXED)
9779		 && (sense_format == SSD_TYPE_DESC))
9780			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9781			    &lun->pending_sense[initidx],
9782			    (struct scsi_sense_data_desc *)sense_ptr);
9783		else if ((stored_format == SSD_TYPE_DESC)
9784		      && (sense_format == SSD_TYPE_FIXED))
9785			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9786			    &lun->pending_sense[initidx],
9787			    (struct scsi_sense_data_fixed *)sense_ptr);
9788		else
9789			memcpy(sense_ptr, &lun->pending_sense[initidx],
9790			       ctl_min(sizeof(*sense_ptr),
9791			       sizeof(lun->pending_sense[initidx])));
9792
9793		ctl_clear_mask(lun->have_ca, initidx);
9794		have_error = 1;
9795	} else
9796#endif
9797	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9798		ctl_ua_type ua_type;
9799
9800		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9801				       sense_ptr, sense_format);
9802		if (ua_type != CTL_UA_NONE)
9803			have_error = 1;
9804	}
9805	mtx_unlock(&lun->lun_lock);
9806
9807	/*
9808	 * We already have a pending error, return it.
9809	 */
9810	if (have_error != 0) {
9811		/*
9812		 * We report the SCSI status as OK, since the status of the
9813		 * request sense command itself is OK.
9814		 */
9815		ctsio->scsi_status = SCSI_STATUS_OK;
9816
9817		/*
9818		 * We report 0 for the sense length, because we aren't doing
9819		 * autosense in this case.  We're reporting sense as
9820		 * parameter data.
9821		 */
9822		ctsio->sense_len = 0;
9823		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9824		ctsio->be_move_done = ctl_config_move_done;
9825		ctl_datamove((union ctl_io *)ctsio);
9826
9827		return (CTL_RETVAL_COMPLETE);
9828	}
9829
9830no_sense:
9831
9832	/*
9833	 * No sense information to report, so we report that everything is
9834	 * okay.
9835	 */
9836	ctl_set_sense_data(sense_ptr,
9837			   lun,
9838			   sense_format,
9839			   /*current_error*/ 1,
9840			   /*sense_key*/ SSD_KEY_NO_SENSE,
9841			   /*asc*/ 0x00,
9842			   /*ascq*/ 0x00,
9843			   SSD_ELEM_NONE);
9844
9845	ctsio->scsi_status = SCSI_STATUS_OK;
9846
9847	/*
9848	 * We report 0 for the sense length, because we aren't doing
9849	 * autosense in this case.  We're reporting sense as parameter data.
9850	 */
9851	ctsio->sense_len = 0;
9852	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9853	ctsio->be_move_done = ctl_config_move_done;
9854	ctl_datamove((union ctl_io *)ctsio);
9855
9856	return (CTL_RETVAL_COMPLETE);
9857}
9858
9859int
9860ctl_tur(struct ctl_scsiio *ctsio)
9861{
9862	struct ctl_lun *lun;
9863
9864	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9865
9866	CTL_DEBUG_PRINT(("ctl_tur\n"));
9867
9868	if (lun == NULL)
9869		return (EINVAL);
9870
9871	ctsio->scsi_status = SCSI_STATUS_OK;
9872	ctsio->io_hdr.status = CTL_SUCCESS;
9873
9874	ctl_done((union ctl_io *)ctsio);
9875
9876	return (CTL_RETVAL_COMPLETE);
9877}
9878
9879#ifdef notyet
9880static int
9881ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9882{
9883
9884}
9885#endif
9886
9887static int
9888ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9889{
9890	struct scsi_vpd_supported_pages *pages;
9891	int sup_page_size;
9892	struct ctl_lun *lun;
9893
9894	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9895
9896	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9897	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9898	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9899	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9900	ctsio->kern_sg_entries = 0;
9901
9902	if (sup_page_size < alloc_len) {
9903		ctsio->residual = alloc_len - sup_page_size;
9904		ctsio->kern_data_len = sup_page_size;
9905		ctsio->kern_total_len = sup_page_size;
9906	} else {
9907		ctsio->residual = 0;
9908		ctsio->kern_data_len = alloc_len;
9909		ctsio->kern_total_len = alloc_len;
9910	}
9911	ctsio->kern_data_resid = 0;
9912	ctsio->kern_rel_offset = 0;
9913	ctsio->kern_sg_entries = 0;
9914
9915	/*
9916	 * The control device is always connected.  The disk device, on the
9917	 * other hand, may not be online all the time.  Need to change this
9918	 * to figure out whether the disk device is actually online or not.
9919	 */
9920	if (lun != NULL)
9921		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9922				lun->be_lun->lun_type;
9923	else
9924		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9925
9926	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9927	/* Supported VPD pages */
9928	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9929	/* Serial Number */
9930	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9931	/* Device Identification */
9932	pages->page_list[2] = SVPD_DEVICE_ID;
9933	/* Extended INQUIRY Data */
9934	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9935	/* Mode Page Policy */
9936	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9937	/* SCSI Ports */
9938	pages->page_list[5] = SVPD_SCSI_PORTS;
9939	/* Third-party Copy */
9940	pages->page_list[6] = SVPD_SCSI_TPC;
9941	/* Block limits */
9942	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9943	/* Block Device Characteristics */
9944	pages->page_list[8] = SVPD_BDC;
9945	/* Logical Block Provisioning */
9946	pages->page_list[9] = SVPD_LBP;
9947
9948	ctsio->scsi_status = SCSI_STATUS_OK;
9949
9950	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9951	ctsio->be_move_done = ctl_config_move_done;
9952	ctl_datamove((union ctl_io *)ctsio);
9953
9954	return (CTL_RETVAL_COMPLETE);
9955}
9956
9957static int
9958ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9959{
9960	struct scsi_vpd_unit_serial_number *sn_ptr;
9961	struct ctl_lun *lun;
9962
9963	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9964
9965	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9966	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9967	ctsio->kern_sg_entries = 0;
9968
9969	if (sizeof(*sn_ptr) < alloc_len) {
9970		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9971		ctsio->kern_data_len = sizeof(*sn_ptr);
9972		ctsio->kern_total_len = sizeof(*sn_ptr);
9973	} else {
9974		ctsio->residual = 0;
9975		ctsio->kern_data_len = alloc_len;
9976		ctsio->kern_total_len = alloc_len;
9977	}
9978	ctsio->kern_data_resid = 0;
9979	ctsio->kern_rel_offset = 0;
9980	ctsio->kern_sg_entries = 0;
9981
9982	/*
9983	 * The control device is always connected.  The disk device, on the
9984	 * other hand, may not be online all the time.  Need to change this
9985	 * to figure out whether the disk device is actually online or not.
9986	 */
9987	if (lun != NULL)
9988		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9989				  lun->be_lun->lun_type;
9990	else
9991		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9992
9993	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9994	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9995	/*
9996	 * If we don't have a LUN, we just leave the serial number as
9997	 * all spaces.
9998	 */
9999	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
10000	if (lun != NULL) {
10001		strncpy((char *)sn_ptr->serial_num,
10002			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
10003	}
10004	ctsio->scsi_status = SCSI_STATUS_OK;
10005
10006	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10007	ctsio->be_move_done = ctl_config_move_done;
10008	ctl_datamove((union ctl_io *)ctsio);
10009
10010	return (CTL_RETVAL_COMPLETE);
10011}
10012
10013
10014static int
10015ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
10016{
10017	struct scsi_vpd_extended_inquiry_data *eid_ptr;
10018	struct ctl_lun *lun;
10019	int data_len;
10020
10021	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10022
10023	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
10024	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10025	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
10026	ctsio->kern_sg_entries = 0;
10027
10028	if (data_len < alloc_len) {
10029		ctsio->residual = alloc_len - data_len;
10030		ctsio->kern_data_len = data_len;
10031		ctsio->kern_total_len = data_len;
10032	} else {
10033		ctsio->residual = 0;
10034		ctsio->kern_data_len = alloc_len;
10035		ctsio->kern_total_len = alloc_len;
10036	}
10037	ctsio->kern_data_resid = 0;
10038	ctsio->kern_rel_offset = 0;
10039	ctsio->kern_sg_entries = 0;
10040
10041	/*
10042	 * The control device is always connected.  The disk device, on the
10043	 * other hand, may not be online all the time.
10044	 */
10045	if (lun != NULL)
10046		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10047				     lun->be_lun->lun_type;
10048	else
10049		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10050	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
10051	eid_ptr->page_length = data_len - 4;
10052	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
10053	eid_ptr->flags3 = SVPD_EID_V_SUP;
10054
10055	ctsio->scsi_status = SCSI_STATUS_OK;
10056	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10057	ctsio->be_move_done = ctl_config_move_done;
10058	ctl_datamove((union ctl_io *)ctsio);
10059
10060	return (CTL_RETVAL_COMPLETE);
10061}
10062
10063static int
10064ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10065{
10066	struct scsi_vpd_mode_page_policy *mpp_ptr;
10067	struct ctl_lun *lun;
10068	int data_len;
10069
10070	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10071
10072	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10073	    sizeof(struct scsi_vpd_mode_page_policy_descr);
10074
10075	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10076	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10077	ctsio->kern_sg_entries = 0;
10078
10079	if (data_len < alloc_len) {
10080		ctsio->residual = alloc_len - data_len;
10081		ctsio->kern_data_len = data_len;
10082		ctsio->kern_total_len = data_len;
10083	} else {
10084		ctsio->residual = 0;
10085		ctsio->kern_data_len = alloc_len;
10086		ctsio->kern_total_len = alloc_len;
10087	}
10088	ctsio->kern_data_resid = 0;
10089	ctsio->kern_rel_offset = 0;
10090	ctsio->kern_sg_entries = 0;
10091
10092	/*
10093	 * The control device is always connected.  The disk device, on the
10094	 * other hand, may not be online all the time.
10095	 */
10096	if (lun != NULL)
10097		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10098				     lun->be_lun->lun_type;
10099	else
10100		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10101	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10102	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10103	mpp_ptr->descr[0].page_code = 0x3f;
10104	mpp_ptr->descr[0].subpage_code = 0xff;
10105	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10106
10107	ctsio->scsi_status = SCSI_STATUS_OK;
10108	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10109	ctsio->be_move_done = ctl_config_move_done;
10110	ctl_datamove((union ctl_io *)ctsio);
10111
10112	return (CTL_RETVAL_COMPLETE);
10113}
10114
10115static int
10116ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10117{
10118	struct scsi_vpd_device_id *devid_ptr;
10119	struct scsi_vpd_id_descriptor *desc;
10120	struct ctl_softc *ctl_softc;
10121	struct ctl_lun *lun;
10122	struct ctl_port *port;
10123	int data_len;
10124	uint8_t proto;
10125
10126	ctl_softc = control_softc;
10127
10128	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10129	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10130
10131	data_len = sizeof(struct scsi_vpd_device_id) +
10132	    sizeof(struct scsi_vpd_id_descriptor) +
10133		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10134	    sizeof(struct scsi_vpd_id_descriptor) +
10135		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10136	if (lun && lun->lun_devid)
10137		data_len += lun->lun_devid->len;
10138	if (port->port_devid)
10139		data_len += port->port_devid->len;
10140	if (port->target_devid)
10141		data_len += port->target_devid->len;
10142
10143	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10144	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10145	ctsio->kern_sg_entries = 0;
10146
10147	if (data_len < alloc_len) {
10148		ctsio->residual = alloc_len - data_len;
10149		ctsio->kern_data_len = data_len;
10150		ctsio->kern_total_len = data_len;
10151	} else {
10152		ctsio->residual = 0;
10153		ctsio->kern_data_len = alloc_len;
10154		ctsio->kern_total_len = alloc_len;
10155	}
10156	ctsio->kern_data_resid = 0;
10157	ctsio->kern_rel_offset = 0;
10158	ctsio->kern_sg_entries = 0;
10159
10160	/*
10161	 * The control device is always connected.  The disk device, on the
10162	 * other hand, may not be online all the time.
10163	 */
10164	if (lun != NULL)
10165		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10166				     lun->be_lun->lun_type;
10167	else
10168		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10169	devid_ptr->page_code = SVPD_DEVICE_ID;
10170	scsi_ulto2b(data_len - 4, devid_ptr->length);
10171
10172	if (port->port_type == CTL_PORT_FC)
10173		proto = SCSI_PROTO_FC << 4;
10174	else if (port->port_type == CTL_PORT_ISCSI)
10175		proto = SCSI_PROTO_ISCSI << 4;
10176	else
10177		proto = SCSI_PROTO_SPI << 4;
10178	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10179
10180	/*
10181	 * We're using a LUN association here.  i.e., this device ID is a
10182	 * per-LUN identifier.
10183	 */
10184	if (lun && lun->lun_devid) {
10185		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10186		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10187		    lun->lun_devid->len);
10188	}
10189
10190	/*
10191	 * This is for the WWPN which is a port association.
10192	 */
10193	if (port->port_devid) {
10194		memcpy(desc, port->port_devid->data, port->port_devid->len);
10195		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10196		    port->port_devid->len);
10197	}
10198
10199	/*
10200	 * This is for the Relative Target Port(type 4h) identifier
10201	 */
10202	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10203	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10204	    SVPD_ID_TYPE_RELTARG;
10205	desc->length = 4;
10206	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10207	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10208	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10209
10210	/*
10211	 * This is for the Target Port Group(type 5h) identifier
10212	 */
10213	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10214	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10215	    SVPD_ID_TYPE_TPORTGRP;
10216	desc->length = 4;
10217	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10218	    &desc->identifier[2]);
10219	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10220	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10221
10222	/*
10223	 * This is for the Target identifier
10224	 */
10225	if (port->target_devid) {
10226		memcpy(desc, port->target_devid->data, port->target_devid->len);
10227	}
10228
10229	ctsio->scsi_status = SCSI_STATUS_OK;
10230	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10231	ctsio->be_move_done = ctl_config_move_done;
10232	ctl_datamove((union ctl_io *)ctsio);
10233
10234	return (CTL_RETVAL_COMPLETE);
10235}
10236
10237static int
10238ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10239{
10240	struct ctl_softc *softc = control_softc;
10241	struct scsi_vpd_scsi_ports *sp;
10242	struct scsi_vpd_port_designation *pd;
10243	struct scsi_vpd_port_designation_cont *pdc;
10244	struct ctl_lun *lun;
10245	struct ctl_port *port;
10246	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10247	int num_target_port_groups, single;
10248
10249	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10250
10251	single = ctl_is_single;
10252	if (single)
10253		num_target_port_groups = 1;
10254	else
10255		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10256	num_target_ports = 0;
10257	iid_len = 0;
10258	id_len = 0;
10259	mtx_lock(&softc->ctl_lock);
10260	STAILQ_FOREACH(port, &softc->port_list, links) {
10261		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10262			continue;
10263		if (lun != NULL &&
10264		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10265		    CTL_MAX_LUNS)
10266			continue;
10267		num_target_ports++;
10268		if (port->init_devid)
10269			iid_len += port->init_devid->len;
10270		if (port->port_devid)
10271			id_len += port->port_devid->len;
10272	}
10273	mtx_unlock(&softc->ctl_lock);
10274
10275	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10276	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10277	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10278	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10279	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10280	ctsio->kern_sg_entries = 0;
10281
10282	if (data_len < alloc_len) {
10283		ctsio->residual = alloc_len - data_len;
10284		ctsio->kern_data_len = data_len;
10285		ctsio->kern_total_len = data_len;
10286	} else {
10287		ctsio->residual = 0;
10288		ctsio->kern_data_len = alloc_len;
10289		ctsio->kern_total_len = alloc_len;
10290	}
10291	ctsio->kern_data_resid = 0;
10292	ctsio->kern_rel_offset = 0;
10293	ctsio->kern_sg_entries = 0;
10294
10295	/*
10296	 * The control device is always connected.  The disk device, on the
10297	 * other hand, may not be online all the time.  Need to change this
10298	 * to figure out whether the disk device is actually online or not.
10299	 */
10300	if (lun != NULL)
10301		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10302				  lun->be_lun->lun_type;
10303	else
10304		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10305
10306	sp->page_code = SVPD_SCSI_PORTS;
10307	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10308	    sp->page_length);
10309	pd = &sp->design[0];
10310
10311	mtx_lock(&softc->ctl_lock);
10312	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10313		pg = 0;
10314	else
10315		pg = 1;
10316	for (g = 0; g < num_target_port_groups; g++) {
10317		STAILQ_FOREACH(port, &softc->port_list, links) {
10318			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10319				continue;
10320			if (lun != NULL &&
10321			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10322			    CTL_MAX_LUNS)
10323				continue;
10324			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10325			scsi_ulto2b(p, pd->relative_port_id);
10326			if (port->init_devid && g == pg) {
10327				iid_len = port->init_devid->len;
10328				memcpy(pd->initiator_transportid,
10329				    port->init_devid->data, port->init_devid->len);
10330			} else
10331				iid_len = 0;
10332			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10333			pdc = (struct scsi_vpd_port_designation_cont *)
10334			    (&pd->initiator_transportid[iid_len]);
10335			if (port->port_devid && g == pg) {
10336				id_len = port->port_devid->len;
10337				memcpy(pdc->target_port_descriptors,
10338				    port->port_devid->data, port->port_devid->len);
10339			} else
10340				id_len = 0;
10341			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10342			pd = (struct scsi_vpd_port_designation *)
10343			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10344		}
10345	}
10346	mtx_unlock(&softc->ctl_lock);
10347
10348	ctsio->scsi_status = SCSI_STATUS_OK;
10349	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10350	ctsio->be_move_done = ctl_config_move_done;
10351	ctl_datamove((union ctl_io *)ctsio);
10352
10353	return (CTL_RETVAL_COMPLETE);
10354}
10355
10356static int
10357ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10358{
10359	struct scsi_vpd_block_limits *bl_ptr;
10360	struct ctl_lun *lun;
10361	int bs;
10362
10363	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10364
10365	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10366	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10367	ctsio->kern_sg_entries = 0;
10368
10369	if (sizeof(*bl_ptr) < alloc_len) {
10370		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10371		ctsio->kern_data_len = sizeof(*bl_ptr);
10372		ctsio->kern_total_len = sizeof(*bl_ptr);
10373	} else {
10374		ctsio->residual = 0;
10375		ctsio->kern_data_len = alloc_len;
10376		ctsio->kern_total_len = alloc_len;
10377	}
10378	ctsio->kern_data_resid = 0;
10379	ctsio->kern_rel_offset = 0;
10380	ctsio->kern_sg_entries = 0;
10381
10382	/*
10383	 * The control device is always connected.  The disk device, on the
10384	 * other hand, may not be online all the time.  Need to change this
10385	 * to figure out whether the disk device is actually online or not.
10386	 */
10387	if (lun != NULL)
10388		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10389				  lun->be_lun->lun_type;
10390	else
10391		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10392
10393	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10394	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10395	bl_ptr->max_cmp_write_len = 0xff;
10396	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10397	if (lun != NULL) {
10398		bs = lun->be_lun->blocksize;
10399		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10400		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10401			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10402			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10403			if (lun->be_lun->pblockexp != 0) {
10404				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10405				    bl_ptr->opt_unmap_grain);
10406				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10407				    bl_ptr->unmap_grain_align);
10408			}
10409		}
10410		scsi_ulto4b(lun->be_lun->atomicblock,
10411		    bl_ptr->max_atomic_transfer_length);
10412		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10413		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10414	}
10415	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10416
10417	ctsio->scsi_status = SCSI_STATUS_OK;
10418	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10419	ctsio->be_move_done = ctl_config_move_done;
10420	ctl_datamove((union ctl_io *)ctsio);
10421
10422	return (CTL_RETVAL_COMPLETE);
10423}
10424
10425static int
10426ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10427{
10428	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10429	struct ctl_lun *lun;
10430
10431	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10432
10433	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10434	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10435	ctsio->kern_sg_entries = 0;
10436
10437	if (sizeof(*bdc_ptr) < alloc_len) {
10438		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10439		ctsio->kern_data_len = sizeof(*bdc_ptr);
10440		ctsio->kern_total_len = sizeof(*bdc_ptr);
10441	} else {
10442		ctsio->residual = 0;
10443		ctsio->kern_data_len = alloc_len;
10444		ctsio->kern_total_len = alloc_len;
10445	}
10446	ctsio->kern_data_resid = 0;
10447	ctsio->kern_rel_offset = 0;
10448	ctsio->kern_sg_entries = 0;
10449
10450	/*
10451	 * The control device is always connected.  The disk device, on the
10452	 * other hand, may not be online all the time.  Need to change this
10453	 * to figure out whether the disk device is actually online or not.
10454	 */
10455	if (lun != NULL)
10456		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10457				  lun->be_lun->lun_type;
10458	else
10459		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10460	bdc_ptr->page_code = SVPD_BDC;
10461	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10462	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10463	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10464
10465	ctsio->scsi_status = SCSI_STATUS_OK;
10466	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10467	ctsio->be_move_done = ctl_config_move_done;
10468	ctl_datamove((union ctl_io *)ctsio);
10469
10470	return (CTL_RETVAL_COMPLETE);
10471}
10472
10473static int
10474ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10475{
10476	struct scsi_vpd_logical_block_prov *lbp_ptr;
10477	struct ctl_lun *lun;
10478
10479	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10480
10481	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10482	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10483	ctsio->kern_sg_entries = 0;
10484
10485	if (sizeof(*lbp_ptr) < alloc_len) {
10486		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10487		ctsio->kern_data_len = sizeof(*lbp_ptr);
10488		ctsio->kern_total_len = sizeof(*lbp_ptr);
10489	} else {
10490		ctsio->residual = 0;
10491		ctsio->kern_data_len = alloc_len;
10492		ctsio->kern_total_len = alloc_len;
10493	}
10494	ctsio->kern_data_resid = 0;
10495	ctsio->kern_rel_offset = 0;
10496	ctsio->kern_sg_entries = 0;
10497
10498	/*
10499	 * The control device is always connected.  The disk device, on the
10500	 * other hand, may not be online all the time.  Need to change this
10501	 * to figure out whether the disk device is actually online or not.
10502	 */
10503	if (lun != NULL)
10504		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10505				  lun->be_lun->lun_type;
10506	else
10507		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10508
10509	lbp_ptr->page_code = SVPD_LBP;
10510	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10511	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10512		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10513		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10514		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10515	}
10516
10517	ctsio->scsi_status = SCSI_STATUS_OK;
10518	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10519	ctsio->be_move_done = ctl_config_move_done;
10520	ctl_datamove((union ctl_io *)ctsio);
10521
10522	return (CTL_RETVAL_COMPLETE);
10523}
10524
10525static int
10526ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10527{
10528	struct scsi_inquiry *cdb;
10529	struct ctl_lun *lun;
10530	int alloc_len, retval;
10531
10532	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10533	cdb = (struct scsi_inquiry *)ctsio->cdb;
10534
10535	retval = CTL_RETVAL_COMPLETE;
10536
10537	alloc_len = scsi_2btoul(cdb->length);
10538
10539	switch (cdb->page_code) {
10540	case SVPD_SUPPORTED_PAGES:
10541		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10542		break;
10543	case SVPD_UNIT_SERIAL_NUMBER:
10544		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10545		break;
10546	case SVPD_DEVICE_ID:
10547		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10548		break;
10549	case SVPD_EXTENDED_INQUIRY_DATA:
10550		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10551		break;
10552	case SVPD_MODE_PAGE_POLICY:
10553		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10554		break;
10555	case SVPD_SCSI_PORTS:
10556		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10557		break;
10558	case SVPD_SCSI_TPC:
10559		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10560		break;
10561	case SVPD_BLOCK_LIMITS:
10562		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10563		break;
10564	case SVPD_BDC:
10565		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10566		break;
10567	case SVPD_LBP:
10568		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10569		break;
10570	default:
10571		ctl_set_invalid_field(ctsio,
10572				      /*sks_valid*/ 1,
10573				      /*command*/ 1,
10574				      /*field*/ 2,
10575				      /*bit_valid*/ 0,
10576				      /*bit*/ 0);
10577		ctl_done((union ctl_io *)ctsio);
10578		retval = CTL_RETVAL_COMPLETE;
10579		break;
10580	}
10581
10582	return (retval);
10583}
10584
10585static int
10586ctl_inquiry_std(struct ctl_scsiio *ctsio)
10587{
10588	struct scsi_inquiry_data *inq_ptr;
10589	struct scsi_inquiry *cdb;
10590	struct ctl_softc *ctl_softc;
10591	struct ctl_lun *lun;
10592	char *val;
10593	uint32_t alloc_len, data_len;
10594	ctl_port_type port_type;
10595
10596	ctl_softc = control_softc;
10597
10598	/*
10599	 * Figure out whether we're talking to a Fibre Channel port or not.
10600	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10601	 * SCSI front ends.
10602	 */
10603	port_type = ctl_softc->ctl_ports[
10604	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10605	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10606		port_type = CTL_PORT_SCSI;
10607
10608	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10609	cdb = (struct scsi_inquiry *)ctsio->cdb;
10610	alloc_len = scsi_2btoul(cdb->length);
10611
10612	/*
10613	 * We malloc the full inquiry data size here and fill it
10614	 * in.  If the user only asks for less, we'll give him
10615	 * that much.
10616	 */
10617	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10618	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10619	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10620	ctsio->kern_sg_entries = 0;
10621	ctsio->kern_data_resid = 0;
10622	ctsio->kern_rel_offset = 0;
10623
10624	if (data_len < alloc_len) {
10625		ctsio->residual = alloc_len - data_len;
10626		ctsio->kern_data_len = data_len;
10627		ctsio->kern_total_len = data_len;
10628	} else {
10629		ctsio->residual = 0;
10630		ctsio->kern_data_len = alloc_len;
10631		ctsio->kern_total_len = alloc_len;
10632	}
10633
10634	/*
10635	 * If we have a LUN configured, report it as connected.  Otherwise,
10636	 * report that it is offline or no device is supported, depending
10637	 * on the value of inquiry_pq_no_lun.
10638	 *
10639	 * According to the spec (SPC-4 r34), the peripheral qualifier
10640	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10641	 *
10642	 * "A peripheral device having the specified peripheral device type
10643	 * is not connected to this logical unit. However, the device
10644	 * server is capable of supporting the specified peripheral device
10645	 * type on this logical unit."
10646	 *
10647	 * According to the same spec, the peripheral qualifier
10648	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10649	 *
10650	 * "The device server is not capable of supporting a peripheral
10651	 * device on this logical unit. For this peripheral qualifier the
10652	 * peripheral device type shall be set to 1Fh. All other peripheral
10653	 * device type values are reserved for this peripheral qualifier."
10654	 *
10655	 * Given the text, it would seem that we probably want to report that
10656	 * the LUN is offline here.  There is no LUN connected, but we can
10657	 * support a LUN at the given LUN number.
10658	 *
10659	 * In the real world, though, it sounds like things are a little
10660	 * different:
10661	 *
10662	 * - Linux, when presented with a LUN with the offline peripheral
10663	 *   qualifier, will create an sg driver instance for it.  So when
10664	 *   you attach it to CTL, you wind up with a ton of sg driver
10665	 *   instances.  (One for every LUN that Linux bothered to probe.)
10666	 *   Linux does this despite the fact that it issues a REPORT LUNs
10667	 *   to LUN 0 to get the inventory of supported LUNs.
10668	 *
10669	 * - There is other anecdotal evidence (from Emulex folks) about
10670	 *   arrays that use the offline peripheral qualifier for LUNs that
10671	 *   are on the "passive" path in an active/passive array.
10672	 *
10673	 * So the solution is provide a hopefully reasonable default
10674	 * (return bad/no LUN) and allow the user to change the behavior
10675	 * with a tunable/sysctl variable.
10676	 */
10677	if (lun != NULL)
10678		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10679				  lun->be_lun->lun_type;
10680	else if (ctl_softc->inquiry_pq_no_lun == 0)
10681		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10682	else
10683		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10684
10685	/* RMB in byte 2 is 0 */
10686	inq_ptr->version = SCSI_REV_SPC4;
10687
10688	/*
10689	 * According to SAM-3, even if a device only supports a single
10690	 * level of LUN addressing, it should still set the HISUP bit:
10691	 *
10692	 * 4.9.1 Logical unit numbers overview
10693	 *
10694	 * All logical unit number formats described in this standard are
10695	 * hierarchical in structure even when only a single level in that
10696	 * hierarchy is used. The HISUP bit shall be set to one in the
10697	 * standard INQUIRY data (see SPC-2) when any logical unit number
10698	 * format described in this standard is used.  Non-hierarchical
10699	 * formats are outside the scope of this standard.
10700	 *
10701	 * Therefore we set the HiSup bit here.
10702	 *
10703	 * The reponse format is 2, per SPC-3.
10704	 */
10705	inq_ptr->response_format = SID_HiSup | 2;
10706
10707	inq_ptr->additional_length = data_len -
10708	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10709	CTL_DEBUG_PRINT(("additional_length = %d\n",
10710			 inq_ptr->additional_length));
10711
10712	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10713	/* 16 bit addressing */
10714	if (port_type == CTL_PORT_SCSI)
10715		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10716	/* XXX set the SID_MultiP bit here if we're actually going to
10717	   respond on multiple ports */
10718	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10719
10720	/* 16 bit data bus, synchronous transfers */
10721	if (port_type == CTL_PORT_SCSI)
10722		inq_ptr->flags = SID_WBus16 | SID_Sync;
10723	/*
10724	 * XXX KDM do we want to support tagged queueing on the control
10725	 * device at all?
10726	 */
10727	if ((lun == NULL)
10728	 || (lun->be_lun->lun_type != T_PROCESSOR))
10729		inq_ptr->flags |= SID_CmdQue;
10730	/*
10731	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10732	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10733	 * name and 4 bytes for the revision.
10734	 */
10735	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10736	    "vendor")) == NULL) {
10737		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10738	} else {
10739		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10740		strncpy(inq_ptr->vendor, val,
10741		    min(sizeof(inq_ptr->vendor), strlen(val)));
10742	}
10743	if (lun == NULL) {
10744		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10745		    sizeof(inq_ptr->product));
10746	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10747		switch (lun->be_lun->lun_type) {
10748		case T_DIRECT:
10749			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10750			    sizeof(inq_ptr->product));
10751			break;
10752		case T_PROCESSOR:
10753			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10754			    sizeof(inq_ptr->product));
10755			break;
10756		default:
10757			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10758			    sizeof(inq_ptr->product));
10759			break;
10760		}
10761	} else {
10762		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10763		strncpy(inq_ptr->product, val,
10764		    min(sizeof(inq_ptr->product), strlen(val)));
10765	}
10766
10767	/*
10768	 * XXX make this a macro somewhere so it automatically gets
10769	 * incremented when we make changes.
10770	 */
10771	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10772	    "revision")) == NULL) {
10773		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10774	} else {
10775		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10776		strncpy(inq_ptr->revision, val,
10777		    min(sizeof(inq_ptr->revision), strlen(val)));
10778	}
10779
10780	/*
10781	 * For parallel SCSI, we support double transition and single
10782	 * transition clocking.  We also support QAS (Quick Arbitration
10783	 * and Selection) and Information Unit transfers on both the
10784	 * control and array devices.
10785	 */
10786	if (port_type == CTL_PORT_SCSI)
10787		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10788				    SID_SPI_IUS;
10789
10790	/* SAM-5 (no version claimed) */
10791	scsi_ulto2b(0x00A0, inq_ptr->version1);
10792	/* SPC-4 (no version claimed) */
10793	scsi_ulto2b(0x0460, inq_ptr->version2);
10794	if (port_type == CTL_PORT_FC) {
10795		/* FCP-2 ANSI INCITS.350:2003 */
10796		scsi_ulto2b(0x0917, inq_ptr->version3);
10797	} else if (port_type == CTL_PORT_SCSI) {
10798		/* SPI-4 ANSI INCITS.362:200x */
10799		scsi_ulto2b(0x0B56, inq_ptr->version3);
10800	} else if (port_type == CTL_PORT_ISCSI) {
10801		/* iSCSI (no version claimed) */
10802		scsi_ulto2b(0x0960, inq_ptr->version3);
10803	} else if (port_type == CTL_PORT_SAS) {
10804		/* SAS (no version claimed) */
10805		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10806	}
10807
10808	if (lun == NULL) {
10809		/* SBC-4 (no version claimed) */
10810		scsi_ulto2b(0x0600, inq_ptr->version4);
10811	} else {
10812		switch (lun->be_lun->lun_type) {
10813		case T_DIRECT:
10814			/* SBC-4 (no version claimed) */
10815			scsi_ulto2b(0x0600, inq_ptr->version4);
10816			break;
10817		case T_PROCESSOR:
10818		default:
10819			break;
10820		}
10821	}
10822
10823	ctsio->scsi_status = SCSI_STATUS_OK;
10824	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10825	ctsio->be_move_done = ctl_config_move_done;
10826	ctl_datamove((union ctl_io *)ctsio);
10827	return (CTL_RETVAL_COMPLETE);
10828}
10829
10830int
10831ctl_inquiry(struct ctl_scsiio *ctsio)
10832{
10833	struct scsi_inquiry *cdb;
10834	int retval;
10835
10836	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10837
10838	cdb = (struct scsi_inquiry *)ctsio->cdb;
10839	if (cdb->byte2 & SI_EVPD)
10840		retval = ctl_inquiry_evpd(ctsio);
10841	else if (cdb->page_code == 0)
10842		retval = ctl_inquiry_std(ctsio);
10843	else {
10844		ctl_set_invalid_field(ctsio,
10845				      /*sks_valid*/ 1,
10846				      /*command*/ 1,
10847				      /*field*/ 2,
10848				      /*bit_valid*/ 0,
10849				      /*bit*/ 0);
10850		ctl_done((union ctl_io *)ctsio);
10851		return (CTL_RETVAL_COMPLETE);
10852	}
10853
10854	return (retval);
10855}
10856
10857/*
10858 * For known CDB types, parse the LBA and length.
10859 */
10860static int
10861ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10862{
10863	if (io->io_hdr.io_type != CTL_IO_SCSI)
10864		return (1);
10865
10866	switch (io->scsiio.cdb[0]) {
10867	case COMPARE_AND_WRITE: {
10868		struct scsi_compare_and_write *cdb;
10869
10870		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10871
10872		*lba = scsi_8btou64(cdb->addr);
10873		*len = cdb->length;
10874		break;
10875	}
10876	case READ_6:
10877	case WRITE_6: {
10878		struct scsi_rw_6 *cdb;
10879
10880		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10881
10882		*lba = scsi_3btoul(cdb->addr);
10883		/* only 5 bits are valid in the most significant address byte */
10884		*lba &= 0x1fffff;
10885		*len = cdb->length;
10886		break;
10887	}
10888	case READ_10:
10889	case WRITE_10: {
10890		struct scsi_rw_10 *cdb;
10891
10892		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10893
10894		*lba = scsi_4btoul(cdb->addr);
10895		*len = scsi_2btoul(cdb->length);
10896		break;
10897	}
10898	case WRITE_VERIFY_10: {
10899		struct scsi_write_verify_10 *cdb;
10900
10901		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10902
10903		*lba = scsi_4btoul(cdb->addr);
10904		*len = scsi_2btoul(cdb->length);
10905		break;
10906	}
10907	case READ_12:
10908	case WRITE_12: {
10909		struct scsi_rw_12 *cdb;
10910
10911		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10912
10913		*lba = scsi_4btoul(cdb->addr);
10914		*len = scsi_4btoul(cdb->length);
10915		break;
10916	}
10917	case WRITE_VERIFY_12: {
10918		struct scsi_write_verify_12 *cdb;
10919
10920		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10921
10922		*lba = scsi_4btoul(cdb->addr);
10923		*len = scsi_4btoul(cdb->length);
10924		break;
10925	}
10926	case READ_16:
10927	case WRITE_16:
10928	case WRITE_ATOMIC_16: {
10929		struct scsi_rw_16 *cdb;
10930
10931		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10932
10933		*lba = scsi_8btou64(cdb->addr);
10934		*len = scsi_4btoul(cdb->length);
10935		break;
10936	}
10937	case WRITE_VERIFY_16: {
10938		struct scsi_write_verify_16 *cdb;
10939
10940		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10941
10942		*lba = scsi_8btou64(cdb->addr);
10943		*len = scsi_4btoul(cdb->length);
10944		break;
10945	}
10946	case WRITE_SAME_10: {
10947		struct scsi_write_same_10 *cdb;
10948
10949		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10950
10951		*lba = scsi_4btoul(cdb->addr);
10952		*len = scsi_2btoul(cdb->length);
10953		break;
10954	}
10955	case WRITE_SAME_16: {
10956		struct scsi_write_same_16 *cdb;
10957
10958		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10959
10960		*lba = scsi_8btou64(cdb->addr);
10961		*len = scsi_4btoul(cdb->length);
10962		break;
10963	}
10964	case VERIFY_10: {
10965		struct scsi_verify_10 *cdb;
10966
10967		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10968
10969		*lba = scsi_4btoul(cdb->addr);
10970		*len = scsi_2btoul(cdb->length);
10971		break;
10972	}
10973	case VERIFY_12: {
10974		struct scsi_verify_12 *cdb;
10975
10976		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10977
10978		*lba = scsi_4btoul(cdb->addr);
10979		*len = scsi_4btoul(cdb->length);
10980		break;
10981	}
10982	case VERIFY_16: {
10983		struct scsi_verify_16 *cdb;
10984
10985		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10986
10987		*lba = scsi_8btou64(cdb->addr);
10988		*len = scsi_4btoul(cdb->length);
10989		break;
10990	}
10991	case UNMAP: {
10992		*lba = 0;
10993		*len = UINT64_MAX;
10994		break;
10995	}
10996	default:
10997		return (1);
10998		break; /* NOTREACHED */
10999	}
11000
11001	return (0);
11002}
11003
11004static ctl_action
11005ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
11006{
11007	uint64_t endlba1, endlba2;
11008
11009	endlba1 = lba1 + len1 - 1;
11010	endlba2 = lba2 + len2 - 1;
11011
11012	if ((endlba1 < lba2)
11013	 || (endlba2 < lba1))
11014		return (CTL_ACTION_PASS);
11015	else
11016		return (CTL_ACTION_BLOCK);
11017}
11018
11019static int
11020ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
11021{
11022	struct ctl_ptr_len_flags *ptrlen;
11023	struct scsi_unmap_desc *buf, *end, *range;
11024	uint64_t lba;
11025	uint32_t len;
11026
11027	/* If not UNMAP -- go other way. */
11028	if (io->io_hdr.io_type != CTL_IO_SCSI ||
11029	    io->scsiio.cdb[0] != UNMAP)
11030		return (CTL_ACTION_ERROR);
11031
11032	/* If UNMAP without data -- block and wait for data. */
11033	ptrlen = (struct ctl_ptr_len_flags *)
11034	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
11035	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
11036	    ptrlen->ptr == NULL)
11037		return (CTL_ACTION_BLOCK);
11038
11039	/* UNMAP with data -- check for collision. */
11040	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11041	end = buf + ptrlen->len / sizeof(*buf);
11042	for (range = buf; range < end; range++) {
11043		lba = scsi_8btou64(range->lba);
11044		len = scsi_4btoul(range->length);
11045		if ((lba < lba2 + len2) && (lba + len > lba2))
11046			return (CTL_ACTION_BLOCK);
11047	}
11048	return (CTL_ACTION_PASS);
11049}
11050
11051static ctl_action
11052ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
11053{
11054	uint64_t lba1, lba2;
11055	uint64_t len1, len2;
11056	int retval;
11057
11058	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11059		return (CTL_ACTION_ERROR);
11060
11061	retval = ctl_extent_check_unmap(io2, lba1, len1);
11062	if (retval != CTL_ACTION_ERROR)
11063		return (retval);
11064
11065	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11066		return (CTL_ACTION_ERROR);
11067
11068	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
11069}
11070
11071static ctl_action
11072ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11073    union ctl_io *ooa_io)
11074{
11075	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11076	ctl_serialize_action *serialize_row;
11077
11078	/*
11079	 * The initiator attempted multiple untagged commands at the same
11080	 * time.  Can't do that.
11081	 */
11082	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11083	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11084	 && ((pending_io->io_hdr.nexus.targ_port ==
11085	      ooa_io->io_hdr.nexus.targ_port)
11086	  && (pending_io->io_hdr.nexus.initid.id ==
11087	      ooa_io->io_hdr.nexus.initid.id))
11088	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11089		return (CTL_ACTION_OVERLAP);
11090
11091	/*
11092	 * The initiator attempted to send multiple tagged commands with
11093	 * the same ID.  (It's fine if different initiators have the same
11094	 * tag ID.)
11095	 *
11096	 * Even if all of those conditions are true, we don't kill the I/O
11097	 * if the command ahead of us has been aborted.  We won't end up
11098	 * sending it to the FETD, and it's perfectly legal to resend a
11099	 * command with the same tag number as long as the previous
11100	 * instance of this tag number has been aborted somehow.
11101	 */
11102	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11103	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11104	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11105	 && ((pending_io->io_hdr.nexus.targ_port ==
11106	      ooa_io->io_hdr.nexus.targ_port)
11107	  && (pending_io->io_hdr.nexus.initid.id ==
11108	      ooa_io->io_hdr.nexus.initid.id))
11109	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11110		return (CTL_ACTION_OVERLAP_TAG);
11111
11112	/*
11113	 * If we get a head of queue tag, SAM-3 says that we should
11114	 * immediately execute it.
11115	 *
11116	 * What happens if this command would normally block for some other
11117	 * reason?  e.g. a request sense with a head of queue tag
11118	 * immediately after a write.  Normally that would block, but this
11119	 * will result in its getting executed immediately...
11120	 *
11121	 * We currently return "pass" instead of "skip", so we'll end up
11122	 * going through the rest of the queue to check for overlapped tags.
11123	 *
11124	 * XXX KDM check for other types of blockage first??
11125	 */
11126	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11127		return (CTL_ACTION_PASS);
11128
11129	/*
11130	 * Ordered tags have to block until all items ahead of them
11131	 * have completed.  If we get called with an ordered tag, we always
11132	 * block, if something else is ahead of us in the queue.
11133	 */
11134	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11135		return (CTL_ACTION_BLOCK);
11136
11137	/*
11138	 * Simple tags get blocked until all head of queue and ordered tags
11139	 * ahead of them have completed.  I'm lumping untagged commands in
11140	 * with simple tags here.  XXX KDM is that the right thing to do?
11141	 */
11142	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11143	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11144	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11145	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11146		return (CTL_ACTION_BLOCK);
11147
11148	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11149	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11150
11151	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11152
11153	switch (serialize_row[pending_entry->seridx]) {
11154	case CTL_SER_BLOCK:
11155		return (CTL_ACTION_BLOCK);
11156	case CTL_SER_EXTENT:
11157		return (ctl_extent_check(pending_io, ooa_io));
11158	case CTL_SER_EXTENTOPT:
11159		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11160		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11161			return (ctl_extent_check(pending_io, ooa_io));
11162		/* FALLTHROUGH */
11163	case CTL_SER_PASS:
11164		return (CTL_ACTION_PASS);
11165	case CTL_SER_BLOCKOPT:
11166		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11167		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11168			return (CTL_ACTION_BLOCK);
11169		return (CTL_ACTION_PASS);
11170	case CTL_SER_SKIP:
11171		return (CTL_ACTION_SKIP);
11172	default:
11173		panic("invalid serialization value %d",
11174		      serialize_row[pending_entry->seridx]);
11175	}
11176
11177	return (CTL_ACTION_ERROR);
11178}
11179
11180/*
11181 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11182 * Assumptions:
11183 * - pending_io is generally either incoming, or on the blocked queue
11184 * - starting I/O is the I/O we want to start the check with.
11185 */
11186static ctl_action
11187ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11188	      union ctl_io *starting_io)
11189{
11190	union ctl_io *ooa_io;
11191	ctl_action action;
11192
11193	mtx_assert(&lun->lun_lock, MA_OWNED);
11194
11195	/*
11196	 * Run back along the OOA queue, starting with the current
11197	 * blocked I/O and going through every I/O before it on the
11198	 * queue.  If starting_io is NULL, we'll just end up returning
11199	 * CTL_ACTION_PASS.
11200	 */
11201	for (ooa_io = starting_io; ooa_io != NULL;
11202	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11203	     ooa_links)){
11204
11205		/*
11206		 * This routine just checks to see whether
11207		 * cur_blocked is blocked by ooa_io, which is ahead
11208		 * of it in the queue.  It doesn't queue/dequeue
11209		 * cur_blocked.
11210		 */
11211		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11212		switch (action) {
11213		case CTL_ACTION_BLOCK:
11214		case CTL_ACTION_OVERLAP:
11215		case CTL_ACTION_OVERLAP_TAG:
11216		case CTL_ACTION_SKIP:
11217		case CTL_ACTION_ERROR:
11218			return (action);
11219			break; /* NOTREACHED */
11220		case CTL_ACTION_PASS:
11221			break;
11222		default:
11223			panic("invalid action %d", action);
11224			break;  /* NOTREACHED */
11225		}
11226	}
11227
11228	return (CTL_ACTION_PASS);
11229}
11230
11231/*
11232 * Assumptions:
11233 * - An I/O has just completed, and has been removed from the per-LUN OOA
11234 *   queue, so some items on the blocked queue may now be unblocked.
11235 */
11236static int
11237ctl_check_blocked(struct ctl_lun *lun)
11238{
11239	union ctl_io *cur_blocked, *next_blocked;
11240
11241	mtx_assert(&lun->lun_lock, MA_OWNED);
11242
11243	/*
11244	 * Run forward from the head of the blocked queue, checking each
11245	 * entry against the I/Os prior to it on the OOA queue to see if
11246	 * there is still any blockage.
11247	 *
11248	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11249	 * with our removing a variable on it while it is traversing the
11250	 * list.
11251	 */
11252	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11253	     cur_blocked != NULL; cur_blocked = next_blocked) {
11254		union ctl_io *prev_ooa;
11255		ctl_action action;
11256
11257		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11258							  blocked_links);
11259
11260		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11261						      ctl_ooaq, ooa_links);
11262
11263		/*
11264		 * If cur_blocked happens to be the first item in the OOA
11265		 * queue now, prev_ooa will be NULL, and the action
11266		 * returned will just be CTL_ACTION_PASS.
11267		 */
11268		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11269
11270		switch (action) {
11271		case CTL_ACTION_BLOCK:
11272			/* Nothing to do here, still blocked */
11273			break;
11274		case CTL_ACTION_OVERLAP:
11275		case CTL_ACTION_OVERLAP_TAG:
11276			/*
11277			 * This shouldn't happen!  In theory we've already
11278			 * checked this command for overlap...
11279			 */
11280			break;
11281		case CTL_ACTION_PASS:
11282		case CTL_ACTION_SKIP: {
11283			struct ctl_softc *softc;
11284			const struct ctl_cmd_entry *entry;
11285			uint32_t initidx;
11286			int isc_retval;
11287
11288			/*
11289			 * The skip case shouldn't happen, this transaction
11290			 * should have never made it onto the blocked queue.
11291			 */
11292			/*
11293			 * This I/O is no longer blocked, we can remove it
11294			 * from the blocked queue.  Since this is a TAILQ
11295			 * (doubly linked list), we can do O(1) removals
11296			 * from any place on the list.
11297			 */
11298			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11299				     blocked_links);
11300			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11301
11302			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11303				/*
11304				 * Need to send IO back to original side to
11305				 * run
11306				 */
11307				union ctl_ha_msg msg_info;
11308
11309				msg_info.hdr.original_sc =
11310					cur_blocked->io_hdr.original_sc;
11311				msg_info.hdr.serializing_sc = cur_blocked;
11312				msg_info.hdr.msg_type = CTL_MSG_R2R;
11313				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11314				     &msg_info, sizeof(msg_info), 0)) >
11315				     CTL_HA_STATUS_SUCCESS) {
11316					printf("CTL:Check Blocked error from "
11317					       "ctl_ha_msg_send %d\n",
11318					       isc_retval);
11319				}
11320				break;
11321			}
11322			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11323			softc = control_softc;
11324
11325			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11326
11327			/*
11328			 * Check this I/O for LUN state changes that may
11329			 * have happened while this command was blocked.
11330			 * The LUN state may have been changed by a command
11331			 * ahead of us in the queue, so we need to re-check
11332			 * for any states that can be caused by SCSI
11333			 * commands.
11334			 */
11335			if (ctl_scsiio_lun_check(softc, lun, entry,
11336						 &cur_blocked->scsiio) == 0) {
11337				cur_blocked->io_hdr.flags |=
11338				                      CTL_FLAG_IS_WAS_ON_RTR;
11339				ctl_enqueue_rtr(cur_blocked);
11340			} else
11341				ctl_done(cur_blocked);
11342			break;
11343		}
11344		default:
11345			/*
11346			 * This probably shouldn't happen -- we shouldn't
11347			 * get CTL_ACTION_ERROR, or anything else.
11348			 */
11349			break;
11350		}
11351	}
11352
11353	return (CTL_RETVAL_COMPLETE);
11354}
11355
11356/*
11357 * This routine (with one exception) checks LUN flags that can be set by
11358 * commands ahead of us in the OOA queue.  These flags have to be checked
11359 * when a command initially comes in, and when we pull a command off the
11360 * blocked queue and are preparing to execute it.  The reason we have to
11361 * check these flags for commands on the blocked queue is that the LUN
11362 * state may have been changed by a command ahead of us while we're on the
11363 * blocked queue.
11364 *
11365 * Ordering is somewhat important with these checks, so please pay
11366 * careful attention to the placement of any new checks.
11367 */
11368static int
11369ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11370    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11371{
11372	int retval;
11373	uint32_t residx;
11374
11375	retval = 0;
11376
11377	mtx_assert(&lun->lun_lock, MA_OWNED);
11378
11379	/*
11380	 * If this shelf is a secondary shelf controller, we have to reject
11381	 * any media access commands.
11382	 */
11383#if 0
11384	/* No longer needed for HA */
11385	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11386	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11387		ctl_set_lun_standby(ctsio);
11388		retval = 1;
11389		goto bailout;
11390	}
11391#endif
11392
11393	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11394		if (lun->flags & CTL_LUN_READONLY) {
11395			ctl_set_sense(ctsio, /*current_error*/ 1,
11396			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11397			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11398			retval = 1;
11399			goto bailout;
11400		}
11401		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11402		    .eca_and_aen & SCP_SWP) != 0) {
11403			ctl_set_sense(ctsio, /*current_error*/ 1,
11404			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11405			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11406			retval = 1;
11407			goto bailout;
11408		}
11409	}
11410
11411	/*
11412	 * Check for a reservation conflict.  If this command isn't allowed
11413	 * even on reserved LUNs, and if this initiator isn't the one who
11414	 * reserved us, reject the command with a reservation conflict.
11415	 */
11416	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11417	if ((lun->flags & CTL_LUN_RESERVED)
11418	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11419		if (lun->res_idx != residx) {
11420			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11421			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11422			retval = 1;
11423			goto bailout;
11424		}
11425	}
11426
11427	if ((lun->flags & CTL_LUN_PR_RESERVED)
11428	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11429		/*
11430		 * if we aren't registered or it's a res holder type
11431		 * reservation and this isn't the res holder then set a
11432		 * conflict.
11433		 * NOTE: Commands which might be allowed on write exclusive
11434		 * type reservations are checked in the particular command
11435		 * for a conflict. Read and SSU are the only ones.
11436		 */
11437		if (lun->pr_keys[residx] == 0
11438		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11439			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11440			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11441			retval = 1;
11442			goto bailout;
11443		}
11444
11445	}
11446
11447	if ((lun->flags & CTL_LUN_OFFLINE)
11448	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11449		ctl_set_lun_not_ready(ctsio);
11450		retval = 1;
11451		goto bailout;
11452	}
11453
11454	/*
11455	 * If the LUN is stopped, see if this particular command is allowed
11456	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11457	 */
11458	if ((lun->flags & CTL_LUN_STOPPED)
11459	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11460		/* "Logical unit not ready, initializing cmd. required" */
11461		ctl_set_lun_stopped(ctsio);
11462		retval = 1;
11463		goto bailout;
11464	}
11465
11466	if ((lun->flags & CTL_LUN_INOPERABLE)
11467	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11468		/* "Medium format corrupted" */
11469		ctl_set_medium_format_corrupted(ctsio);
11470		retval = 1;
11471		goto bailout;
11472	}
11473
11474bailout:
11475	return (retval);
11476
11477}
11478
11479static void
11480ctl_failover_io(union ctl_io *io, int have_lock)
11481{
11482	ctl_set_busy(&io->scsiio);
11483	ctl_done(io);
11484}
11485
11486static void
11487ctl_failover(void)
11488{
11489	struct ctl_lun *lun;
11490	struct ctl_softc *ctl_softc;
11491	union ctl_io *next_io, *pending_io;
11492	union ctl_io *io;
11493	int lun_idx;
11494	int i;
11495
11496	ctl_softc = control_softc;
11497
11498	mtx_lock(&ctl_softc->ctl_lock);
11499	/*
11500	 * Remove any cmds from the other SC from the rtr queue.  These
11501	 * will obviously only be for LUNs for which we're the primary.
11502	 * We can't send status or get/send data for these commands.
11503	 * Since they haven't been executed yet, we can just remove them.
11504	 * We'll either abort them or delete them below, depending on
11505	 * which HA mode we're in.
11506	 */
11507#ifdef notyet
11508	mtx_lock(&ctl_softc->queue_lock);
11509	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11510	     io != NULL; io = next_io) {
11511		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11512		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11513			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11514				      ctl_io_hdr, links);
11515	}
11516	mtx_unlock(&ctl_softc->queue_lock);
11517#endif
11518
11519	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11520		lun = ctl_softc->ctl_luns[lun_idx];
11521		if (lun==NULL)
11522			continue;
11523
11524		/*
11525		 * Processor LUNs are primary on both sides.
11526		 * XXX will this always be true?
11527		 */
11528		if (lun->be_lun->lun_type == T_PROCESSOR)
11529			continue;
11530
11531		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11532		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11533			printf("FAILOVER: primary lun %d\n", lun_idx);
11534		        /*
11535			 * Remove all commands from the other SC. First from the
11536			 * blocked queue then from the ooa queue. Once we have
11537			 * removed them. Call ctl_check_blocked to see if there
11538			 * is anything that can run.
11539			 */
11540			for (io = (union ctl_io *)TAILQ_FIRST(
11541			     &lun->blocked_queue); io != NULL; io = next_io) {
11542
11543		        	next_io = (union ctl_io *)TAILQ_NEXT(
11544				    &io->io_hdr, blocked_links);
11545
11546				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11547					TAILQ_REMOVE(&lun->blocked_queue,
11548						     &io->io_hdr,blocked_links);
11549					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11550					TAILQ_REMOVE(&lun->ooa_queue,
11551						     &io->io_hdr, ooa_links);
11552
11553					ctl_free_io(io);
11554				}
11555			}
11556
11557			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11558	     		     io != NULL; io = next_io) {
11559
11560		        	next_io = (union ctl_io *)TAILQ_NEXT(
11561				    &io->io_hdr, ooa_links);
11562
11563				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11564
11565					TAILQ_REMOVE(&lun->ooa_queue,
11566						&io->io_hdr,
11567					     	ooa_links);
11568
11569					ctl_free_io(io);
11570				}
11571			}
11572			ctl_check_blocked(lun);
11573		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11574			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11575
11576			printf("FAILOVER: primary lun %d\n", lun_idx);
11577			/*
11578			 * Abort all commands from the other SC.  We can't
11579			 * send status back for them now.  These should get
11580			 * cleaned up when they are completed or come out
11581			 * for a datamove operation.
11582			 */
11583			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11584	     		     io != NULL; io = next_io) {
11585		        	next_io = (union ctl_io *)TAILQ_NEXT(
11586					&io->io_hdr, ooa_links);
11587
11588				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11589					io->io_hdr.flags |= CTL_FLAG_ABORT;
11590			}
11591		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11592			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11593
11594			printf("FAILOVER: secondary lun %d\n", lun_idx);
11595
11596			lun->flags |= CTL_LUN_PRIMARY_SC;
11597
11598			/*
11599			 * We send all I/O that was sent to this controller
11600			 * and redirected to the other side back with
11601			 * busy status, and have the initiator retry it.
11602			 * Figuring out how much data has been transferred,
11603			 * etc. and picking up where we left off would be
11604			 * very tricky.
11605			 *
11606			 * XXX KDM need to remove I/O from the blocked
11607			 * queue as well!
11608			 */
11609			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11610			     &lun->ooa_queue); pending_io != NULL;
11611			     pending_io = next_io) {
11612
11613				next_io =  (union ctl_io *)TAILQ_NEXT(
11614					&pending_io->io_hdr, ooa_links);
11615
11616				pending_io->io_hdr.flags &=
11617					~CTL_FLAG_SENT_2OTHER_SC;
11618
11619				if (pending_io->io_hdr.flags &
11620				    CTL_FLAG_IO_ACTIVE) {
11621					pending_io->io_hdr.flags |=
11622						CTL_FLAG_FAILOVER;
11623				} else {
11624					ctl_set_busy(&pending_io->scsiio);
11625					ctl_done(pending_io);
11626				}
11627			}
11628
11629			/*
11630			 * Build Unit Attention
11631			 */
11632			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11633				lun->pending_ua[i] |=
11634				                     CTL_UA_ASYM_ACC_CHANGE;
11635			}
11636		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11637			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11638			printf("FAILOVER: secondary lun %d\n", lun_idx);
11639			/*
11640			 * if the first io on the OOA is not on the RtR queue
11641			 * add it.
11642			 */
11643			lun->flags |= CTL_LUN_PRIMARY_SC;
11644
11645			pending_io = (union ctl_io *)TAILQ_FIRST(
11646			    &lun->ooa_queue);
11647			if (pending_io==NULL) {
11648				printf("Nothing on OOA queue\n");
11649				continue;
11650			}
11651
11652			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11653			if ((pending_io->io_hdr.flags &
11654			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11655				pending_io->io_hdr.flags |=
11656				    CTL_FLAG_IS_WAS_ON_RTR;
11657				ctl_enqueue_rtr(pending_io);
11658			}
11659#if 0
11660			else
11661			{
11662				printf("Tag 0x%04x is running\n",
11663				      pending_io->scsiio.tag_num);
11664			}
11665#endif
11666
11667			next_io = (union ctl_io *)TAILQ_NEXT(
11668			    &pending_io->io_hdr, ooa_links);
11669			for (pending_io=next_io; pending_io != NULL;
11670			     pending_io = next_io) {
11671				pending_io->io_hdr.flags &=
11672				    ~CTL_FLAG_SENT_2OTHER_SC;
11673				next_io = (union ctl_io *)TAILQ_NEXT(
11674					&pending_io->io_hdr, ooa_links);
11675				if (pending_io->io_hdr.flags &
11676				    CTL_FLAG_IS_WAS_ON_RTR) {
11677#if 0
11678				        printf("Tag 0x%04x is running\n",
11679				      		pending_io->scsiio.tag_num);
11680#endif
11681					continue;
11682				}
11683
11684				switch (ctl_check_ooa(lun, pending_io,
11685			            (union ctl_io *)TAILQ_PREV(
11686				    &pending_io->io_hdr, ctl_ooaq,
11687				    ooa_links))) {
11688
11689				case CTL_ACTION_BLOCK:
11690					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11691							  &pending_io->io_hdr,
11692							  blocked_links);
11693					pending_io->io_hdr.flags |=
11694					    CTL_FLAG_BLOCKED;
11695					break;
11696				case CTL_ACTION_PASS:
11697				case CTL_ACTION_SKIP:
11698					pending_io->io_hdr.flags |=
11699					    CTL_FLAG_IS_WAS_ON_RTR;
11700					ctl_enqueue_rtr(pending_io);
11701					break;
11702				case CTL_ACTION_OVERLAP:
11703					ctl_set_overlapped_cmd(
11704					    (struct ctl_scsiio *)pending_io);
11705					ctl_done(pending_io);
11706					break;
11707				case CTL_ACTION_OVERLAP_TAG:
11708					ctl_set_overlapped_tag(
11709					    (struct ctl_scsiio *)pending_io,
11710					    pending_io->scsiio.tag_num & 0xff);
11711					ctl_done(pending_io);
11712					break;
11713				case CTL_ACTION_ERROR:
11714				default:
11715					ctl_set_internal_failure(
11716						(struct ctl_scsiio *)pending_io,
11717						0,  // sks_valid
11718						0); //retry count
11719					ctl_done(pending_io);
11720					break;
11721				}
11722			}
11723
11724			/*
11725			 * Build Unit Attention
11726			 */
11727			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11728				lun->pending_ua[i] |=
11729				                     CTL_UA_ASYM_ACC_CHANGE;
11730			}
11731		} else {
11732			panic("Unhandled HA mode failover, LUN flags = %#x, "
11733			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11734		}
11735	}
11736	ctl_pause_rtr = 0;
11737	mtx_unlock(&ctl_softc->ctl_lock);
11738}
11739
11740static int
11741ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11742{
11743	struct ctl_lun *lun;
11744	const struct ctl_cmd_entry *entry;
11745	uint32_t initidx, targ_lun;
11746	int retval;
11747
11748	retval = 0;
11749
11750	lun = NULL;
11751
11752	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11753	if ((targ_lun < CTL_MAX_LUNS)
11754	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11755		lun = ctl_softc->ctl_luns[targ_lun];
11756		/*
11757		 * If the LUN is invalid, pretend that it doesn't exist.
11758		 * It will go away as soon as all pending I/O has been
11759		 * completed.
11760		 */
11761		if (lun->flags & CTL_LUN_DISABLED) {
11762			lun = NULL;
11763		} else {
11764			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11765			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11766				lun->be_lun;
11767			if (lun->be_lun->lun_type == T_PROCESSOR) {
11768				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11769			}
11770
11771			/*
11772			 * Every I/O goes into the OOA queue for a
11773			 * particular LUN, and stays there until completion.
11774			 */
11775			mtx_lock(&lun->lun_lock);
11776			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11777			    ooa_links);
11778		}
11779	} else {
11780		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11781		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11782	}
11783
11784	/* Get command entry and return error if it is unsuppotyed. */
11785	entry = ctl_validate_command(ctsio);
11786	if (entry == NULL) {
11787		if (lun)
11788			mtx_unlock(&lun->lun_lock);
11789		return (retval);
11790	}
11791
11792	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11793	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11794
11795	/*
11796	 * Check to see whether we can send this command to LUNs that don't
11797	 * exist.  This should pretty much only be the case for inquiry
11798	 * and request sense.  Further checks, below, really require having
11799	 * a LUN, so we can't really check the command anymore.  Just put
11800	 * it on the rtr queue.
11801	 */
11802	if (lun == NULL) {
11803		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11804			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11805			ctl_enqueue_rtr((union ctl_io *)ctsio);
11806			return (retval);
11807		}
11808
11809		ctl_set_unsupported_lun(ctsio);
11810		ctl_done((union ctl_io *)ctsio);
11811		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11812		return (retval);
11813	} else {
11814		/*
11815		 * Make sure we support this particular command on this LUN.
11816		 * e.g., we don't support writes to the control LUN.
11817		 */
11818		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11819			mtx_unlock(&lun->lun_lock);
11820			ctl_set_invalid_opcode(ctsio);
11821			ctl_done((union ctl_io *)ctsio);
11822			return (retval);
11823		}
11824	}
11825
11826	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11827
11828#ifdef CTL_WITH_CA
11829	/*
11830	 * If we've got a request sense, it'll clear the contingent
11831	 * allegiance condition.  Otherwise, if we have a CA condition for
11832	 * this initiator, clear it, because it sent down a command other
11833	 * than request sense.
11834	 */
11835	if ((ctsio->cdb[0] != REQUEST_SENSE)
11836	 && (ctl_is_set(lun->have_ca, initidx)))
11837		ctl_clear_mask(lun->have_ca, initidx);
11838#endif
11839
11840	/*
11841	 * If the command has this flag set, it handles its own unit
11842	 * attention reporting, we shouldn't do anything.  Otherwise we
11843	 * check for any pending unit attentions, and send them back to the
11844	 * initiator.  We only do this when a command initially comes in,
11845	 * not when we pull it off the blocked queue.
11846	 *
11847	 * According to SAM-3, section 5.3.2, the order that things get
11848	 * presented back to the host is basically unit attentions caused
11849	 * by some sort of reset event, busy status, reservation conflicts
11850	 * or task set full, and finally any other status.
11851	 *
11852	 * One issue here is that some of the unit attentions we report
11853	 * don't fall into the "reset" category (e.g. "reported luns data
11854	 * has changed").  So reporting it here, before the reservation
11855	 * check, may be technically wrong.  I guess the only thing to do
11856	 * would be to check for and report the reset events here, and then
11857	 * check for the other unit attention types after we check for a
11858	 * reservation conflict.
11859	 *
11860	 * XXX KDM need to fix this
11861	 */
11862	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11863		ctl_ua_type ua_type;
11864
11865		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11866			scsi_sense_data_type sense_format;
11867
11868			if (lun != NULL)
11869				sense_format = (lun->flags &
11870				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11871				    SSD_TYPE_FIXED;
11872			else
11873				sense_format = SSD_TYPE_FIXED;
11874
11875			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11876			    &ctsio->sense_data, sense_format);
11877			if (ua_type != CTL_UA_NONE) {
11878				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11879				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11880						       CTL_AUTOSENSE;
11881				ctsio->sense_len = SSD_FULL_SIZE;
11882				mtx_unlock(&lun->lun_lock);
11883				ctl_done((union ctl_io *)ctsio);
11884				return (retval);
11885			}
11886		}
11887	}
11888
11889
11890	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11891		mtx_unlock(&lun->lun_lock);
11892		ctl_done((union ctl_io *)ctsio);
11893		return (retval);
11894	}
11895
11896	/*
11897	 * XXX CHD this is where we want to send IO to other side if
11898	 * this LUN is secondary on this SC. We will need to make a copy
11899	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11900	 * the copy we send as FROM_OTHER.
11901	 * We also need to stuff the address of the original IO so we can
11902	 * find it easily. Something similar will need be done on the other
11903	 * side so when we are done we can find the copy.
11904	 */
11905	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11906		union ctl_ha_msg msg_info;
11907		int isc_retval;
11908
11909		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11910
11911		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11912		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11913#if 0
11914		printf("1. ctsio %p\n", ctsio);
11915#endif
11916		msg_info.hdr.serializing_sc = NULL;
11917		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11918		msg_info.scsi.tag_num = ctsio->tag_num;
11919		msg_info.scsi.tag_type = ctsio->tag_type;
11920		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11921
11922		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11923
11924		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11925		    (void *)&msg_info, sizeof(msg_info), 0)) >
11926		    CTL_HA_STATUS_SUCCESS) {
11927			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11928			       isc_retval);
11929			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11930		} else {
11931#if 0
11932			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11933#endif
11934		}
11935
11936		/*
11937		 * XXX KDM this I/O is off the incoming queue, but hasn't
11938		 * been inserted on any other queue.  We may need to come
11939		 * up with a holding queue while we wait for serialization
11940		 * so that we have an idea of what we're waiting for from
11941		 * the other side.
11942		 */
11943		mtx_unlock(&lun->lun_lock);
11944		return (retval);
11945	}
11946
11947	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11948			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11949			      ctl_ooaq, ooa_links))) {
11950	case CTL_ACTION_BLOCK:
11951		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11952		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11953				  blocked_links);
11954		mtx_unlock(&lun->lun_lock);
11955		return (retval);
11956	case CTL_ACTION_PASS:
11957	case CTL_ACTION_SKIP:
11958		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11959		mtx_unlock(&lun->lun_lock);
11960		ctl_enqueue_rtr((union ctl_io *)ctsio);
11961		break;
11962	case CTL_ACTION_OVERLAP:
11963		mtx_unlock(&lun->lun_lock);
11964		ctl_set_overlapped_cmd(ctsio);
11965		ctl_done((union ctl_io *)ctsio);
11966		break;
11967	case CTL_ACTION_OVERLAP_TAG:
11968		mtx_unlock(&lun->lun_lock);
11969		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11970		ctl_done((union ctl_io *)ctsio);
11971		break;
11972	case CTL_ACTION_ERROR:
11973	default:
11974		mtx_unlock(&lun->lun_lock);
11975		ctl_set_internal_failure(ctsio,
11976					 /*sks_valid*/ 0,
11977					 /*retry_count*/ 0);
11978		ctl_done((union ctl_io *)ctsio);
11979		break;
11980	}
11981	return (retval);
11982}
11983
11984const struct ctl_cmd_entry *
11985ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11986{
11987	const struct ctl_cmd_entry *entry;
11988	int service_action;
11989
11990	entry = &ctl_cmd_table[ctsio->cdb[0]];
11991	if (sa)
11992		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11993	if (entry->flags & CTL_CMD_FLAG_SA5) {
11994		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11995		entry = &((const struct ctl_cmd_entry *)
11996		    entry->execute)[service_action];
11997	}
11998	return (entry);
11999}
12000
12001const struct ctl_cmd_entry *
12002ctl_validate_command(struct ctl_scsiio *ctsio)
12003{
12004	const struct ctl_cmd_entry *entry;
12005	int i, sa;
12006	uint8_t diff;
12007
12008	entry = ctl_get_cmd_entry(ctsio, &sa);
12009	if (entry->execute == NULL) {
12010		if (sa)
12011			ctl_set_invalid_field(ctsio,
12012					      /*sks_valid*/ 1,
12013					      /*command*/ 1,
12014					      /*field*/ 1,
12015					      /*bit_valid*/ 1,
12016					      /*bit*/ 4);
12017		else
12018			ctl_set_invalid_opcode(ctsio);
12019		ctl_done((union ctl_io *)ctsio);
12020		return (NULL);
12021	}
12022	KASSERT(entry->length > 0,
12023	    ("Not defined length for command 0x%02x/0x%02x",
12024	     ctsio->cdb[0], ctsio->cdb[1]));
12025	for (i = 1; i < entry->length; i++) {
12026		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
12027		if (diff == 0)
12028			continue;
12029		ctl_set_invalid_field(ctsio,
12030				      /*sks_valid*/ 1,
12031				      /*command*/ 1,
12032				      /*field*/ i,
12033				      /*bit_valid*/ 1,
12034				      /*bit*/ fls(diff) - 1);
12035		ctl_done((union ctl_io *)ctsio);
12036		return (NULL);
12037	}
12038	return (entry);
12039}
12040
12041static int
12042ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12043{
12044
12045	switch (lun_type) {
12046	case T_PROCESSOR:
12047		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
12048		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12049			return (0);
12050		break;
12051	case T_DIRECT:
12052		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
12053		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12054			return (0);
12055		break;
12056	default:
12057		return (0);
12058	}
12059	return (1);
12060}
12061
12062static int
12063ctl_scsiio(struct ctl_scsiio *ctsio)
12064{
12065	int retval;
12066	const struct ctl_cmd_entry *entry;
12067
12068	retval = CTL_RETVAL_COMPLETE;
12069
12070	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12071
12072	entry = ctl_get_cmd_entry(ctsio, NULL);
12073
12074	/*
12075	 * If this I/O has been aborted, just send it straight to
12076	 * ctl_done() without executing it.
12077	 */
12078	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12079		ctl_done((union ctl_io *)ctsio);
12080		goto bailout;
12081	}
12082
12083	/*
12084	 * All the checks should have been handled by ctl_scsiio_precheck().
12085	 * We should be clear now to just execute the I/O.
12086	 */
12087	retval = entry->execute(ctsio);
12088
12089bailout:
12090	return (retval);
12091}
12092
12093/*
12094 * Since we only implement one target right now, a bus reset simply resets
12095 * our single target.
12096 */
12097static int
12098ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12099{
12100	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12101}
12102
12103static int
12104ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12105		 ctl_ua_type ua_type)
12106{
12107	struct ctl_lun *lun;
12108	int retval;
12109
12110	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12111		union ctl_ha_msg msg_info;
12112
12113		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12114		msg_info.hdr.nexus = io->io_hdr.nexus;
12115		if (ua_type==CTL_UA_TARG_RESET)
12116			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12117		else
12118			msg_info.task.task_action = CTL_TASK_BUS_RESET;
12119		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12120		msg_info.hdr.original_sc = NULL;
12121		msg_info.hdr.serializing_sc = NULL;
12122		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12123		    (void *)&msg_info, sizeof(msg_info), 0)) {
12124		}
12125	}
12126	retval = 0;
12127
12128	mtx_lock(&ctl_softc->ctl_lock);
12129	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12130		retval += ctl_lun_reset(lun, io, ua_type);
12131	mtx_unlock(&ctl_softc->ctl_lock);
12132
12133	return (retval);
12134}
12135
12136/*
12137 * The LUN should always be set.  The I/O is optional, and is used to
12138 * distinguish between I/Os sent by this initiator, and by other
12139 * initiators.  We set unit attention for initiators other than this one.
12140 * SAM-3 is vague on this point.  It does say that a unit attention should
12141 * be established for other initiators when a LUN is reset (see section
12142 * 5.7.3), but it doesn't specifically say that the unit attention should
12143 * be established for this particular initiator when a LUN is reset.  Here
12144 * is the relevant text, from SAM-3 rev 8:
12145 *
12146 * 5.7.2 When a SCSI initiator port aborts its own tasks
12147 *
12148 * When a SCSI initiator port causes its own task(s) to be aborted, no
12149 * notification that the task(s) have been aborted shall be returned to
12150 * the SCSI initiator port other than the completion response for the
12151 * command or task management function action that caused the task(s) to
12152 * be aborted and notification(s) associated with related effects of the
12153 * action (e.g., a reset unit attention condition).
12154 *
12155 * XXX KDM for now, we're setting unit attention for all initiators.
12156 */
12157static int
12158ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12159{
12160	union ctl_io *xio;
12161#if 0
12162	uint32_t initindex;
12163#endif
12164	int i;
12165
12166	mtx_lock(&lun->lun_lock);
12167	/*
12168	 * Run through the OOA queue and abort each I/O.
12169	 */
12170#if 0
12171	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12172#endif
12173	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12174	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12175		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12176	}
12177
12178	/*
12179	 * This version sets unit attention for every
12180	 */
12181#if 0
12182	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12183	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12184		if (initindex == i)
12185			continue;
12186		lun->pending_ua[i] |= ua_type;
12187	}
12188#endif
12189
12190	/*
12191	 * A reset (any kind, really) clears reservations established with
12192	 * RESERVE/RELEASE.  It does not clear reservations established
12193	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12194	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12195	 * reservations made with the RESERVE/RELEASE commands, because
12196	 * those commands are obsolete in SPC-3.
12197	 */
12198	lun->flags &= ~CTL_LUN_RESERVED;
12199
12200	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12201#ifdef CTL_WITH_CA
12202		ctl_clear_mask(lun->have_ca, i);
12203#endif
12204		lun->pending_ua[i] |= ua_type;
12205	}
12206	mtx_unlock(&lun->lun_lock);
12207
12208	return (0);
12209}
12210
12211static void
12212ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12213    int other_sc)
12214{
12215	union ctl_io *xio;
12216
12217	mtx_assert(&lun->lun_lock, MA_OWNED);
12218
12219	/*
12220	 * Run through the OOA queue and attempt to find the given I/O.
12221	 * The target port, initiator ID, tag type and tag number have to
12222	 * match the values that we got from the initiator.  If we have an
12223	 * untagged command to abort, simply abort the first untagged command
12224	 * we come to.  We only allow one untagged command at a time of course.
12225	 */
12226	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12227	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12228
12229		if ((targ_port == UINT32_MAX ||
12230		     targ_port == xio->io_hdr.nexus.targ_port) &&
12231		    (init_id == UINT32_MAX ||
12232		     init_id == xio->io_hdr.nexus.initid.id)) {
12233			if (targ_port != xio->io_hdr.nexus.targ_port ||
12234			    init_id != xio->io_hdr.nexus.initid.id)
12235				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12236			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12237			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12238				union ctl_ha_msg msg_info;
12239
12240				msg_info.hdr.nexus = xio->io_hdr.nexus;
12241				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12242				msg_info.task.tag_num = xio->scsiio.tag_num;
12243				msg_info.task.tag_type = xio->scsiio.tag_type;
12244				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12245				msg_info.hdr.original_sc = NULL;
12246				msg_info.hdr.serializing_sc = NULL;
12247				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12248				    (void *)&msg_info, sizeof(msg_info), 0);
12249			}
12250		}
12251	}
12252}
12253
12254static int
12255ctl_abort_task_set(union ctl_io *io)
12256{
12257	struct ctl_softc *softc = control_softc;
12258	struct ctl_lun *lun;
12259	uint32_t targ_lun;
12260
12261	/*
12262	 * Look up the LUN.
12263	 */
12264	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12265	mtx_lock(&softc->ctl_lock);
12266	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12267		lun = softc->ctl_luns[targ_lun];
12268	else {
12269		mtx_unlock(&softc->ctl_lock);
12270		return (1);
12271	}
12272
12273	mtx_lock(&lun->lun_lock);
12274	mtx_unlock(&softc->ctl_lock);
12275	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12276		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12277		    io->io_hdr.nexus.initid.id,
12278		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12279	} else { /* CTL_TASK_CLEAR_TASK_SET */
12280		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12281		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12282	}
12283	mtx_unlock(&lun->lun_lock);
12284	return (0);
12285}
12286
12287static int
12288ctl_i_t_nexus_reset(union ctl_io *io)
12289{
12290	struct ctl_softc *softc = control_softc;
12291	struct ctl_lun *lun;
12292	uint32_t initindex, residx;
12293
12294	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12295	residx = ctl_get_resindex(&io->io_hdr.nexus);
12296	mtx_lock(&softc->ctl_lock);
12297	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12298		mtx_lock(&lun->lun_lock);
12299		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12300		    io->io_hdr.nexus.initid.id,
12301		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12302#ifdef CTL_WITH_CA
12303		ctl_clear_mask(lun->have_ca, initindex);
12304#endif
12305		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12306			lun->flags &= ~CTL_LUN_RESERVED;
12307		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12308		mtx_unlock(&lun->lun_lock);
12309	}
12310	mtx_unlock(&softc->ctl_lock);
12311	return (0);
12312}
12313
12314static int
12315ctl_abort_task(union ctl_io *io)
12316{
12317	union ctl_io *xio;
12318	struct ctl_lun *lun;
12319	struct ctl_softc *ctl_softc;
12320#if 0
12321	struct sbuf sb;
12322	char printbuf[128];
12323#endif
12324	int found;
12325	uint32_t targ_lun;
12326
12327	ctl_softc = control_softc;
12328	found = 0;
12329
12330	/*
12331	 * Look up the LUN.
12332	 */
12333	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12334	mtx_lock(&ctl_softc->ctl_lock);
12335	if ((targ_lun < CTL_MAX_LUNS)
12336	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12337		lun = ctl_softc->ctl_luns[targ_lun];
12338	else {
12339		mtx_unlock(&ctl_softc->ctl_lock);
12340		return (1);
12341	}
12342
12343#if 0
12344	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12345	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12346#endif
12347
12348	mtx_lock(&lun->lun_lock);
12349	mtx_unlock(&ctl_softc->ctl_lock);
12350	/*
12351	 * Run through the OOA queue and attempt to find the given I/O.
12352	 * The target port, initiator ID, tag type and tag number have to
12353	 * match the values that we got from the initiator.  If we have an
12354	 * untagged command to abort, simply abort the first untagged command
12355	 * we come to.  We only allow one untagged command at a time of course.
12356	 */
12357#if 0
12358	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12359#endif
12360	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12361	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12362#if 0
12363		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12364
12365		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12366			    lun->lun, xio->scsiio.tag_num,
12367			    xio->scsiio.tag_type,
12368			    (xio->io_hdr.blocked_links.tqe_prev
12369			    == NULL) ? "" : " BLOCKED",
12370			    (xio->io_hdr.flags &
12371			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12372			    (xio->io_hdr.flags &
12373			    CTL_FLAG_ABORT) ? " ABORT" : "",
12374			    (xio->io_hdr.flags &
12375			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12376		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12377		sbuf_finish(&sb);
12378		printf("%s\n", sbuf_data(&sb));
12379#endif
12380
12381		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12382		 && (xio->io_hdr.nexus.initid.id ==
12383		     io->io_hdr.nexus.initid.id)) {
12384			/*
12385			 * If the abort says that the task is untagged, the
12386			 * task in the queue must be untagged.  Otherwise,
12387			 * we just check to see whether the tag numbers
12388			 * match.  This is because the QLogic firmware
12389			 * doesn't pass back the tag type in an abort
12390			 * request.
12391			 */
12392#if 0
12393			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12394			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12395			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12396#endif
12397			/*
12398			 * XXX KDM we've got problems with FC, because it
12399			 * doesn't send down a tag type with aborts.  So we
12400			 * can only really go by the tag number...
12401			 * This may cause problems with parallel SCSI.
12402			 * Need to figure that out!!
12403			 */
12404			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12405				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12406				found = 1;
12407				if ((io->io_hdr.flags &
12408				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12409				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12410					union ctl_ha_msg msg_info;
12411
12412					io->io_hdr.flags |=
12413					                CTL_FLAG_SENT_2OTHER_SC;
12414					msg_info.hdr.nexus = io->io_hdr.nexus;
12415					msg_info.task.task_action =
12416						CTL_TASK_ABORT_TASK;
12417					msg_info.task.tag_num =
12418						io->taskio.tag_num;
12419					msg_info.task.tag_type =
12420						io->taskio.tag_type;
12421					msg_info.hdr.msg_type =
12422						CTL_MSG_MANAGE_TASKS;
12423					msg_info.hdr.original_sc = NULL;
12424					msg_info.hdr.serializing_sc = NULL;
12425#if 0
12426					printf("Sent Abort to other side\n");
12427#endif
12428					if (CTL_HA_STATUS_SUCCESS !=
12429					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12430		    				(void *)&msg_info,
12431						sizeof(msg_info), 0)) {
12432					}
12433				}
12434#if 0
12435				printf("ctl_abort_task: found I/O to abort\n");
12436#endif
12437				break;
12438			}
12439		}
12440	}
12441	mtx_unlock(&lun->lun_lock);
12442
12443	if (found == 0) {
12444		/*
12445		 * This isn't really an error.  It's entirely possible for
12446		 * the abort and command completion to cross on the wire.
12447		 * This is more of an informative/diagnostic error.
12448		 */
12449#if 0
12450		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12451		       "%d:%d:%d:%d tag %d type %d\n",
12452		       io->io_hdr.nexus.initid.id,
12453		       io->io_hdr.nexus.targ_port,
12454		       io->io_hdr.nexus.targ_target.id,
12455		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12456		       io->taskio.tag_type);
12457#endif
12458	}
12459	return (0);
12460}
12461
12462static void
12463ctl_run_task(union ctl_io *io)
12464{
12465	struct ctl_softc *ctl_softc = control_softc;
12466	int retval = 1;
12467	const char *task_desc;
12468
12469	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12470
12471	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12472	    ("ctl_run_task: Unextected io_type %d\n",
12473	     io->io_hdr.io_type));
12474
12475	task_desc = ctl_scsi_task_string(&io->taskio);
12476	if (task_desc != NULL) {
12477#ifdef NEEDTOPORT
12478		csevent_log(CSC_CTL | CSC_SHELF_SW |
12479			    CTL_TASK_REPORT,
12480			    csevent_LogType_Trace,
12481			    csevent_Severity_Information,
12482			    csevent_AlertLevel_Green,
12483			    csevent_FRU_Firmware,
12484			    csevent_FRU_Unknown,
12485			    "CTL: received task: %s",task_desc);
12486#endif
12487	} else {
12488#ifdef NEEDTOPORT
12489		csevent_log(CSC_CTL | CSC_SHELF_SW |
12490			    CTL_TASK_REPORT,
12491			    csevent_LogType_Trace,
12492			    csevent_Severity_Information,
12493			    csevent_AlertLevel_Green,
12494			    csevent_FRU_Firmware,
12495			    csevent_FRU_Unknown,
12496			    "CTL: received unknown task "
12497			    "type: %d (%#x)",
12498			    io->taskio.task_action,
12499			    io->taskio.task_action);
12500#endif
12501	}
12502	switch (io->taskio.task_action) {
12503	case CTL_TASK_ABORT_TASK:
12504		retval = ctl_abort_task(io);
12505		break;
12506	case CTL_TASK_ABORT_TASK_SET:
12507	case CTL_TASK_CLEAR_TASK_SET:
12508		retval = ctl_abort_task_set(io);
12509		break;
12510	case CTL_TASK_CLEAR_ACA:
12511		break;
12512	case CTL_TASK_I_T_NEXUS_RESET:
12513		retval = ctl_i_t_nexus_reset(io);
12514		break;
12515	case CTL_TASK_LUN_RESET: {
12516		struct ctl_lun *lun;
12517		uint32_t targ_lun;
12518
12519		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12520		mtx_lock(&ctl_softc->ctl_lock);
12521		if ((targ_lun < CTL_MAX_LUNS)
12522		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12523			lun = ctl_softc->ctl_luns[targ_lun];
12524		else {
12525			mtx_unlock(&ctl_softc->ctl_lock);
12526			retval = 1;
12527			break;
12528		}
12529
12530		if (!(io->io_hdr.flags &
12531		    CTL_FLAG_FROM_OTHER_SC)) {
12532			union ctl_ha_msg msg_info;
12533
12534			io->io_hdr.flags |=
12535				CTL_FLAG_SENT_2OTHER_SC;
12536			msg_info.hdr.msg_type =
12537				CTL_MSG_MANAGE_TASKS;
12538			msg_info.hdr.nexus = io->io_hdr.nexus;
12539			msg_info.task.task_action =
12540				CTL_TASK_LUN_RESET;
12541			msg_info.hdr.original_sc = NULL;
12542			msg_info.hdr.serializing_sc = NULL;
12543			if (CTL_HA_STATUS_SUCCESS !=
12544			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12545			    (void *)&msg_info,
12546			    sizeof(msg_info), 0)) {
12547			}
12548		}
12549
12550		retval = ctl_lun_reset(lun, io,
12551				       CTL_UA_LUN_RESET);
12552		mtx_unlock(&ctl_softc->ctl_lock);
12553		break;
12554	}
12555	case CTL_TASK_TARGET_RESET:
12556		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12557		break;
12558	case CTL_TASK_BUS_RESET:
12559		retval = ctl_bus_reset(ctl_softc, io);
12560		break;
12561	case CTL_TASK_PORT_LOGIN:
12562		break;
12563	case CTL_TASK_PORT_LOGOUT:
12564		break;
12565	default:
12566		printf("ctl_run_task: got unknown task management event %d\n",
12567		       io->taskio.task_action);
12568		break;
12569	}
12570	if (retval == 0)
12571		io->io_hdr.status = CTL_SUCCESS;
12572	else
12573		io->io_hdr.status = CTL_ERROR;
12574	ctl_done(io);
12575}
12576
12577/*
12578 * For HA operation.  Handle commands that come in from the other
12579 * controller.
12580 */
12581static void
12582ctl_handle_isc(union ctl_io *io)
12583{
12584	int free_io;
12585	struct ctl_lun *lun;
12586	struct ctl_softc *ctl_softc;
12587	uint32_t targ_lun;
12588
12589	ctl_softc = control_softc;
12590
12591	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12592	lun = ctl_softc->ctl_luns[targ_lun];
12593
12594	switch (io->io_hdr.msg_type) {
12595	case CTL_MSG_SERIALIZE:
12596		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12597		break;
12598	case CTL_MSG_R2R: {
12599		const struct ctl_cmd_entry *entry;
12600
12601		/*
12602		 * This is only used in SER_ONLY mode.
12603		 */
12604		free_io = 0;
12605		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12606		mtx_lock(&lun->lun_lock);
12607		if (ctl_scsiio_lun_check(ctl_softc, lun,
12608		    entry, (struct ctl_scsiio *)io) != 0) {
12609			mtx_unlock(&lun->lun_lock);
12610			ctl_done(io);
12611			break;
12612		}
12613		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12614		mtx_unlock(&lun->lun_lock);
12615		ctl_enqueue_rtr(io);
12616		break;
12617	}
12618	case CTL_MSG_FINISH_IO:
12619		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12620			free_io = 0;
12621			ctl_done(io);
12622		} else {
12623			free_io = 1;
12624			mtx_lock(&lun->lun_lock);
12625			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12626				     ooa_links);
12627			ctl_check_blocked(lun);
12628			mtx_unlock(&lun->lun_lock);
12629		}
12630		break;
12631	case CTL_MSG_PERS_ACTION:
12632		ctl_hndl_per_res_out_on_other_sc(
12633			(union ctl_ha_msg *)&io->presio.pr_msg);
12634		free_io = 1;
12635		break;
12636	case CTL_MSG_BAD_JUJU:
12637		free_io = 0;
12638		ctl_done(io);
12639		break;
12640	case CTL_MSG_DATAMOVE:
12641		/* Only used in XFER mode */
12642		free_io = 0;
12643		ctl_datamove_remote(io);
12644		break;
12645	case CTL_MSG_DATAMOVE_DONE:
12646		/* Only used in XFER mode */
12647		free_io = 0;
12648		io->scsiio.be_move_done(io);
12649		break;
12650	default:
12651		free_io = 1;
12652		printf("%s: Invalid message type %d\n",
12653		       __func__, io->io_hdr.msg_type);
12654		break;
12655	}
12656	if (free_io)
12657		ctl_free_io(io);
12658
12659}
12660
12661
12662/*
12663 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12664 * there is no match.
12665 */
12666static ctl_lun_error_pattern
12667ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12668{
12669	const struct ctl_cmd_entry *entry;
12670	ctl_lun_error_pattern filtered_pattern, pattern;
12671
12672	pattern = desc->error_pattern;
12673
12674	/*
12675	 * XXX KDM we need more data passed into this function to match a
12676	 * custom pattern, and we actually need to implement custom pattern
12677	 * matching.
12678	 */
12679	if (pattern & CTL_LUN_PAT_CMD)
12680		return (CTL_LUN_PAT_CMD);
12681
12682	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12683		return (CTL_LUN_PAT_ANY);
12684
12685	entry = ctl_get_cmd_entry(ctsio, NULL);
12686
12687	filtered_pattern = entry->pattern & pattern;
12688
12689	/*
12690	 * If the user requested specific flags in the pattern (e.g.
12691	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12692	 * flags.
12693	 *
12694	 * If the user did not specify any flags, it doesn't matter whether
12695	 * or not the command supports the flags.
12696	 */
12697	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12698	     (pattern & ~CTL_LUN_PAT_MASK))
12699		return (CTL_LUN_PAT_NONE);
12700
12701	/*
12702	 * If the user asked for a range check, see if the requested LBA
12703	 * range overlaps with this command's LBA range.
12704	 */
12705	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12706		uint64_t lba1;
12707		uint64_t len1;
12708		ctl_action action;
12709		int retval;
12710
12711		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12712		if (retval != 0)
12713			return (CTL_LUN_PAT_NONE);
12714
12715		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12716					      desc->lba_range.len);
12717		/*
12718		 * A "pass" means that the LBA ranges don't overlap, so
12719		 * this doesn't match the user's range criteria.
12720		 */
12721		if (action == CTL_ACTION_PASS)
12722			return (CTL_LUN_PAT_NONE);
12723	}
12724
12725	return (filtered_pattern);
12726}
12727
12728static void
12729ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12730{
12731	struct ctl_error_desc *desc, *desc2;
12732
12733	mtx_assert(&lun->lun_lock, MA_OWNED);
12734
12735	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12736		ctl_lun_error_pattern pattern;
12737		/*
12738		 * Check to see whether this particular command matches
12739		 * the pattern in the descriptor.
12740		 */
12741		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12742		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12743			continue;
12744
12745		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12746		case CTL_LUN_INJ_ABORTED:
12747			ctl_set_aborted(&io->scsiio);
12748			break;
12749		case CTL_LUN_INJ_MEDIUM_ERR:
12750			ctl_set_medium_error(&io->scsiio);
12751			break;
12752		case CTL_LUN_INJ_UA:
12753			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12754			 * OCCURRED */
12755			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12756			break;
12757		case CTL_LUN_INJ_CUSTOM:
12758			/*
12759			 * We're assuming the user knows what he is doing.
12760			 * Just copy the sense information without doing
12761			 * checks.
12762			 */
12763			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12764			      ctl_min(sizeof(desc->custom_sense),
12765				      sizeof(io->scsiio.sense_data)));
12766			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12767			io->scsiio.sense_len = SSD_FULL_SIZE;
12768			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12769			break;
12770		case CTL_LUN_INJ_NONE:
12771		default:
12772			/*
12773			 * If this is an error injection type we don't know
12774			 * about, clear the continuous flag (if it is set)
12775			 * so it will get deleted below.
12776			 */
12777			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12778			break;
12779		}
12780		/*
12781		 * By default, each error injection action is a one-shot
12782		 */
12783		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12784			continue;
12785
12786		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12787
12788		free(desc, M_CTL);
12789	}
12790}
12791
12792#ifdef CTL_IO_DELAY
12793static void
12794ctl_datamove_timer_wakeup(void *arg)
12795{
12796	union ctl_io *io;
12797
12798	io = (union ctl_io *)arg;
12799
12800	ctl_datamove(io);
12801}
12802#endif /* CTL_IO_DELAY */
12803
12804void
12805ctl_datamove(union ctl_io *io)
12806{
12807	void (*fe_datamove)(union ctl_io *io);
12808
12809	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12810
12811	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12812
12813#ifdef CTL_TIME_IO
12814	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12815		char str[256];
12816		char path_str[64];
12817		struct sbuf sb;
12818
12819		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12820		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12821
12822		sbuf_cat(&sb, path_str);
12823		switch (io->io_hdr.io_type) {
12824		case CTL_IO_SCSI:
12825			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12826			sbuf_printf(&sb, "\n");
12827			sbuf_cat(&sb, path_str);
12828			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12829				    io->scsiio.tag_num, io->scsiio.tag_type);
12830			break;
12831		case CTL_IO_TASK:
12832			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12833				    "Tag Type: %d\n", io->taskio.task_action,
12834				    io->taskio.tag_num, io->taskio.tag_type);
12835			break;
12836		default:
12837			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12838			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12839			break;
12840		}
12841		sbuf_cat(&sb, path_str);
12842		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12843			    (intmax_t)time_uptime - io->io_hdr.start_time);
12844		sbuf_finish(&sb);
12845		printf("%s", sbuf_data(&sb));
12846	}
12847#endif /* CTL_TIME_IO */
12848
12849#ifdef CTL_IO_DELAY
12850	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12851		struct ctl_lun *lun;
12852
12853		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12854
12855		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12856	} else {
12857		struct ctl_lun *lun;
12858
12859		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12860		if ((lun != NULL)
12861		 && (lun->delay_info.datamove_delay > 0)) {
12862			struct callout *callout;
12863
12864			callout = (struct callout *)&io->io_hdr.timer_bytes;
12865			callout_init(callout, /*mpsafe*/ 1);
12866			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12867			callout_reset(callout,
12868				      lun->delay_info.datamove_delay * hz,
12869				      ctl_datamove_timer_wakeup, io);
12870			if (lun->delay_info.datamove_type ==
12871			    CTL_DELAY_TYPE_ONESHOT)
12872				lun->delay_info.datamove_delay = 0;
12873			return;
12874		}
12875	}
12876#endif
12877
12878	/*
12879	 * This command has been aborted.  Set the port status, so we fail
12880	 * the data move.
12881	 */
12882	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12883		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12884		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12885		       io->io_hdr.nexus.targ_port,
12886		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12887		       io->io_hdr.nexus.targ_lun);
12888		io->io_hdr.port_status = 31337;
12889		/*
12890		 * Note that the backend, in this case, will get the
12891		 * callback in its context.  In other cases it may get
12892		 * called in the frontend's interrupt thread context.
12893		 */
12894		io->scsiio.be_move_done(io);
12895		return;
12896	}
12897
12898	/* Don't confuse frontend with zero length data move. */
12899	if (io->scsiio.kern_data_len == 0) {
12900		io->scsiio.be_move_done(io);
12901		return;
12902	}
12903
12904	/*
12905	 * If we're in XFER mode and this I/O is from the other shelf
12906	 * controller, we need to send the DMA to the other side to
12907	 * actually transfer the data to/from the host.  In serialize only
12908	 * mode the transfer happens below CTL and ctl_datamove() is only
12909	 * called on the machine that originally received the I/O.
12910	 */
12911	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12912	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12913		union ctl_ha_msg msg;
12914		uint32_t sg_entries_sent;
12915		int do_sg_copy;
12916		int i;
12917
12918		memset(&msg, 0, sizeof(msg));
12919		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12920		msg.hdr.original_sc = io->io_hdr.original_sc;
12921		msg.hdr.serializing_sc = io;
12922		msg.hdr.nexus = io->io_hdr.nexus;
12923		msg.dt.flags = io->io_hdr.flags;
12924		/*
12925		 * We convert everything into a S/G list here.  We can't
12926		 * pass by reference, only by value between controllers.
12927		 * So we can't pass a pointer to the S/G list, only as many
12928		 * S/G entries as we can fit in here.  If it's possible for
12929		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12930		 * then we need to break this up into multiple transfers.
12931		 */
12932		if (io->scsiio.kern_sg_entries == 0) {
12933			msg.dt.kern_sg_entries = 1;
12934			/*
12935			 * If this is in cached memory, flush the cache
12936			 * before we send the DMA request to the other
12937			 * controller.  We want to do this in either the
12938			 * read or the write case.  The read case is
12939			 * straightforward.  In the write case, we want to
12940			 * make sure nothing is in the local cache that
12941			 * could overwrite the DMAed data.
12942			 */
12943			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12944				/*
12945				 * XXX KDM use bus_dmamap_sync() here.
12946				 */
12947			}
12948
12949			/*
12950			 * Convert to a physical address if this is a
12951			 * virtual address.
12952			 */
12953			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12954				msg.dt.sg_list[0].addr =
12955					io->scsiio.kern_data_ptr;
12956			} else {
12957				/*
12958				 * XXX KDM use busdma here!
12959				 */
12960#if 0
12961				msg.dt.sg_list[0].addr = (void *)
12962					vtophys(io->scsiio.kern_data_ptr);
12963#endif
12964			}
12965
12966			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12967			do_sg_copy = 0;
12968		} else {
12969			struct ctl_sg_entry *sgl;
12970
12971			do_sg_copy = 1;
12972			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12973			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12974			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12975				/*
12976				 * XXX KDM use bus_dmamap_sync() here.
12977				 */
12978			}
12979		}
12980
12981		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12982		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12983		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12984		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12985		msg.dt.sg_sequence = 0;
12986
12987		/*
12988		 * Loop until we've sent all of the S/G entries.  On the
12989		 * other end, we'll recompose these S/G entries into one
12990		 * contiguous list before passing it to the
12991		 */
12992		for (sg_entries_sent = 0; sg_entries_sent <
12993		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12994			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12995				sizeof(msg.dt.sg_list[0])),
12996				msg.dt.kern_sg_entries - sg_entries_sent);
12997
12998			if (do_sg_copy != 0) {
12999				struct ctl_sg_entry *sgl;
13000				int j;
13001
13002				sgl = (struct ctl_sg_entry *)
13003					io->scsiio.kern_data_ptr;
13004				/*
13005				 * If this is in cached memory, flush the cache
13006				 * before we send the DMA request to the other
13007				 * controller.  We want to do this in either
13008				 * the * read or the write case.  The read
13009				 * case is straightforward.  In the write
13010				 * case, we want to make sure nothing is
13011				 * in the local cache that could overwrite
13012				 * the DMAed data.
13013				 */
13014
13015				for (i = sg_entries_sent, j = 0;
13016				     i < msg.dt.cur_sg_entries; i++, j++) {
13017					if ((io->io_hdr.flags &
13018					     CTL_FLAG_NO_DATASYNC) == 0) {
13019						/*
13020						 * XXX KDM use bus_dmamap_sync()
13021						 */
13022					}
13023					if ((io->io_hdr.flags &
13024					     CTL_FLAG_BUS_ADDR) == 0) {
13025						/*
13026						 * XXX KDM use busdma.
13027						 */
13028#if 0
13029						msg.dt.sg_list[j].addr =(void *)
13030						       vtophys(sgl[i].addr);
13031#endif
13032					} else {
13033						msg.dt.sg_list[j].addr =
13034							sgl[i].addr;
13035					}
13036					msg.dt.sg_list[j].len = sgl[i].len;
13037				}
13038			}
13039
13040			sg_entries_sent += msg.dt.cur_sg_entries;
13041			if (sg_entries_sent >= msg.dt.kern_sg_entries)
13042				msg.dt.sg_last = 1;
13043			else
13044				msg.dt.sg_last = 0;
13045
13046			/*
13047			 * XXX KDM drop and reacquire the lock here?
13048			 */
13049			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13050			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13051				/*
13052				 * XXX do something here.
13053				 */
13054			}
13055
13056			msg.dt.sent_sg_entries = sg_entries_sent;
13057		}
13058		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13059		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
13060			ctl_failover_io(io, /*have_lock*/ 0);
13061
13062	} else {
13063
13064		/*
13065		 * Lookup the fe_datamove() function for this particular
13066		 * front end.
13067		 */
13068		fe_datamove =
13069		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13070
13071		fe_datamove(io);
13072	}
13073}
13074
13075static void
13076ctl_send_datamove_done(union ctl_io *io, int have_lock)
13077{
13078	union ctl_ha_msg msg;
13079	int isc_status;
13080
13081	memset(&msg, 0, sizeof(msg));
13082
13083	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13084	msg.hdr.original_sc = io;
13085	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13086	msg.hdr.nexus = io->io_hdr.nexus;
13087	msg.hdr.status = io->io_hdr.status;
13088	msg.scsi.tag_num = io->scsiio.tag_num;
13089	msg.scsi.tag_type = io->scsiio.tag_type;
13090	msg.scsi.scsi_status = io->scsiio.scsi_status;
13091	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13092	       sizeof(io->scsiio.sense_data));
13093	msg.scsi.sense_len = io->scsiio.sense_len;
13094	msg.scsi.sense_residual = io->scsiio.sense_residual;
13095	msg.scsi.fetd_status = io->io_hdr.port_status;
13096	msg.scsi.residual = io->scsiio.residual;
13097	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13098
13099	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13100		ctl_failover_io(io, /*have_lock*/ have_lock);
13101		return;
13102	}
13103
13104	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13105	if (isc_status > CTL_HA_STATUS_SUCCESS) {
13106		/* XXX do something if this fails */
13107	}
13108
13109}
13110
13111/*
13112 * The DMA to the remote side is done, now we need to tell the other side
13113 * we're done so it can continue with its data movement.
13114 */
13115static void
13116ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13117{
13118	union ctl_io *io;
13119
13120	io = rq->context;
13121
13122	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13123		printf("%s: ISC DMA write failed with error %d", __func__,
13124		       rq->ret);
13125		ctl_set_internal_failure(&io->scsiio,
13126					 /*sks_valid*/ 1,
13127					 /*retry_count*/ rq->ret);
13128	}
13129
13130	ctl_dt_req_free(rq);
13131
13132	/*
13133	 * In this case, we had to malloc the memory locally.  Free it.
13134	 */
13135	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13136		int i;
13137		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13138			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13139	}
13140	/*
13141	 * The data is in local and remote memory, so now we need to send
13142	 * status (good or back) back to the other side.
13143	 */
13144	ctl_send_datamove_done(io, /*have_lock*/ 0);
13145}
13146
13147/*
13148 * We've moved the data from the host/controller into local memory.  Now we
13149 * need to push it over to the remote controller's memory.
13150 */
13151static int
13152ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13153{
13154	int retval;
13155
13156	retval = 0;
13157
13158	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13159					  ctl_datamove_remote_write_cb);
13160
13161	return (retval);
13162}
13163
13164static void
13165ctl_datamove_remote_write(union ctl_io *io)
13166{
13167	int retval;
13168	void (*fe_datamove)(union ctl_io *io);
13169
13170	/*
13171	 * - Get the data from the host/HBA into local memory.
13172	 * - DMA memory from the local controller to the remote controller.
13173	 * - Send status back to the remote controller.
13174	 */
13175
13176	retval = ctl_datamove_remote_sgl_setup(io);
13177	if (retval != 0)
13178		return;
13179
13180	/* Switch the pointer over so the FETD knows what to do */
13181	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13182
13183	/*
13184	 * Use a custom move done callback, since we need to send completion
13185	 * back to the other controller, not to the backend on this side.
13186	 */
13187	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13188
13189	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13190
13191	fe_datamove(io);
13192
13193	return;
13194
13195}
13196
13197static int
13198ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13199{
13200#if 0
13201	char str[256];
13202	char path_str[64];
13203	struct sbuf sb;
13204#endif
13205
13206	/*
13207	 * In this case, we had to malloc the memory locally.  Free it.
13208	 */
13209	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13210		int i;
13211		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13212			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13213	}
13214
13215#if 0
13216	scsi_path_string(io, path_str, sizeof(path_str));
13217	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13218	sbuf_cat(&sb, path_str);
13219	scsi_command_string(&io->scsiio, NULL, &sb);
13220	sbuf_printf(&sb, "\n");
13221	sbuf_cat(&sb, path_str);
13222	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13223		    io->scsiio.tag_num, io->scsiio.tag_type);
13224	sbuf_cat(&sb, path_str);
13225	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13226		    io->io_hdr.flags, io->io_hdr.status);
13227	sbuf_finish(&sb);
13228	printk("%s", sbuf_data(&sb));
13229#endif
13230
13231
13232	/*
13233	 * The read is done, now we need to send status (good or bad) back
13234	 * to the other side.
13235	 */
13236	ctl_send_datamove_done(io, /*have_lock*/ 0);
13237
13238	return (0);
13239}
13240
13241static void
13242ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13243{
13244	union ctl_io *io;
13245	void (*fe_datamove)(union ctl_io *io);
13246
13247	io = rq->context;
13248
13249	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13250		printf("%s: ISC DMA read failed with error %d", __func__,
13251		       rq->ret);
13252		ctl_set_internal_failure(&io->scsiio,
13253					 /*sks_valid*/ 1,
13254					 /*retry_count*/ rq->ret);
13255	}
13256
13257	ctl_dt_req_free(rq);
13258
13259	/* Switch the pointer over so the FETD knows what to do */
13260	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13261
13262	/*
13263	 * Use a custom move done callback, since we need to send completion
13264	 * back to the other controller, not to the backend on this side.
13265	 */
13266	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13267
13268	/* XXX KDM add checks like the ones in ctl_datamove? */
13269
13270	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13271
13272	fe_datamove(io);
13273}
13274
13275static int
13276ctl_datamove_remote_sgl_setup(union ctl_io *io)
13277{
13278	struct ctl_sg_entry *local_sglist, *remote_sglist;
13279	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13280	struct ctl_softc *softc;
13281	int retval;
13282	int i;
13283
13284	retval = 0;
13285	softc = control_softc;
13286
13287	local_sglist = io->io_hdr.local_sglist;
13288	local_dma_sglist = io->io_hdr.local_dma_sglist;
13289	remote_sglist = io->io_hdr.remote_sglist;
13290	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13291
13292	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13293		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13294			local_sglist[i].len = remote_sglist[i].len;
13295
13296			/*
13297			 * XXX Detect the situation where the RS-level I/O
13298			 * redirector on the other side has already read the
13299			 * data off of the AOR RS on this side, and
13300			 * transferred it to remote (mirror) memory on the
13301			 * other side.  Since we already have the data in
13302			 * memory here, we just need to use it.
13303			 *
13304			 * XXX KDM this can probably be removed once we
13305			 * get the cache device code in and take the
13306			 * current AOR implementation out.
13307			 */
13308#ifdef NEEDTOPORT
13309			if ((remote_sglist[i].addr >=
13310			     (void *)vtophys(softc->mirr->addr))
13311			 && (remote_sglist[i].addr <
13312			     ((void *)vtophys(softc->mirr->addr) +
13313			     CacheMirrorOffset))) {
13314				local_sglist[i].addr = remote_sglist[i].addr -
13315					CacheMirrorOffset;
13316				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13317				     CTL_FLAG_DATA_IN)
13318					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13319			} else {
13320				local_sglist[i].addr = remote_sglist[i].addr +
13321					CacheMirrorOffset;
13322			}
13323#endif
13324#if 0
13325			printf("%s: local %p, remote %p, len %d\n",
13326			       __func__, local_sglist[i].addr,
13327			       remote_sglist[i].addr, local_sglist[i].len);
13328#endif
13329		}
13330	} else {
13331		uint32_t len_to_go;
13332
13333		/*
13334		 * In this case, we don't have automatically allocated
13335		 * memory for this I/O on this controller.  This typically
13336		 * happens with internal CTL I/O -- e.g. inquiry, mode
13337		 * sense, etc.  Anything coming from RAIDCore will have
13338		 * a mirror area available.
13339		 */
13340		len_to_go = io->scsiio.kern_data_len;
13341
13342		/*
13343		 * Clear the no datasync flag, we have to use malloced
13344		 * buffers.
13345		 */
13346		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13347
13348		/*
13349		 * The difficult thing here is that the size of the various
13350		 * S/G segments may be different than the size from the
13351		 * remote controller.  That'll make it harder when DMAing
13352		 * the data back to the other side.
13353		 */
13354		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13355		     sizeof(io->io_hdr.remote_sglist[0])) &&
13356		     (len_to_go > 0); i++) {
13357			local_sglist[i].len = ctl_min(len_to_go, 131072);
13358			CTL_SIZE_8B(local_dma_sglist[i].len,
13359				    local_sglist[i].len);
13360			local_sglist[i].addr =
13361				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13362
13363			local_dma_sglist[i].addr = local_sglist[i].addr;
13364
13365			if (local_sglist[i].addr == NULL) {
13366				int j;
13367
13368				printf("malloc failed for %zd bytes!",
13369				       local_dma_sglist[i].len);
13370				for (j = 0; j < i; j++) {
13371					free(local_sglist[j].addr, M_CTL);
13372				}
13373				ctl_set_internal_failure(&io->scsiio,
13374							 /*sks_valid*/ 1,
13375							 /*retry_count*/ 4857);
13376				retval = 1;
13377				goto bailout_error;
13378
13379			}
13380			/* XXX KDM do we need a sync here? */
13381
13382			len_to_go -= local_sglist[i].len;
13383		}
13384		/*
13385		 * Reset the number of S/G entries accordingly.  The
13386		 * original number of S/G entries is available in
13387		 * rem_sg_entries.
13388		 */
13389		io->scsiio.kern_sg_entries = i;
13390
13391#if 0
13392		printf("%s: kern_sg_entries = %d\n", __func__,
13393		       io->scsiio.kern_sg_entries);
13394		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13395			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13396			       local_sglist[i].addr, local_sglist[i].len,
13397			       local_dma_sglist[i].len);
13398#endif
13399	}
13400
13401
13402	return (retval);
13403
13404bailout_error:
13405
13406	ctl_send_datamove_done(io, /*have_lock*/ 0);
13407
13408	return (retval);
13409}
13410
13411static int
13412ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13413			 ctl_ha_dt_cb callback)
13414{
13415	struct ctl_ha_dt_req *rq;
13416	struct ctl_sg_entry *remote_sglist, *local_sglist;
13417	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13418	uint32_t local_used, remote_used, total_used;
13419	int retval;
13420	int i, j;
13421
13422	retval = 0;
13423
13424	rq = ctl_dt_req_alloc();
13425
13426	/*
13427	 * If we failed to allocate the request, and if the DMA didn't fail
13428	 * anyway, set busy status.  This is just a resource allocation
13429	 * failure.
13430	 */
13431	if ((rq == NULL)
13432	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13433		ctl_set_busy(&io->scsiio);
13434
13435	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13436
13437		if (rq != NULL)
13438			ctl_dt_req_free(rq);
13439
13440		/*
13441		 * The data move failed.  We need to return status back
13442		 * to the other controller.  No point in trying to DMA
13443		 * data to the remote controller.
13444		 */
13445
13446		ctl_send_datamove_done(io, /*have_lock*/ 0);
13447
13448		retval = 1;
13449
13450		goto bailout;
13451	}
13452
13453	local_sglist = io->io_hdr.local_sglist;
13454	local_dma_sglist = io->io_hdr.local_dma_sglist;
13455	remote_sglist = io->io_hdr.remote_sglist;
13456	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13457	local_used = 0;
13458	remote_used = 0;
13459	total_used = 0;
13460
13461	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13462		rq->ret = CTL_HA_STATUS_SUCCESS;
13463		rq->context = io;
13464		callback(rq);
13465		goto bailout;
13466	}
13467
13468	/*
13469	 * Pull/push the data over the wire from/to the other controller.
13470	 * This takes into account the possibility that the local and
13471	 * remote sglists may not be identical in terms of the size of
13472	 * the elements and the number of elements.
13473	 *
13474	 * One fundamental assumption here is that the length allocated for
13475	 * both the local and remote sglists is identical.  Otherwise, we've
13476	 * essentially got a coding error of some sort.
13477	 */
13478	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13479		int isc_ret;
13480		uint32_t cur_len, dma_length;
13481		uint8_t *tmp_ptr;
13482
13483		rq->id = CTL_HA_DATA_CTL;
13484		rq->command = command;
13485		rq->context = io;
13486
13487		/*
13488		 * Both pointers should be aligned.  But it is possible
13489		 * that the allocation length is not.  They should both
13490		 * also have enough slack left over at the end, though,
13491		 * to round up to the next 8 byte boundary.
13492		 */
13493		cur_len = ctl_min(local_sglist[i].len - local_used,
13494				  remote_sglist[j].len - remote_used);
13495
13496		/*
13497		 * In this case, we have a size issue and need to decrease
13498		 * the size, except in the case where we actually have less
13499		 * than 8 bytes left.  In that case, we need to increase
13500		 * the DMA length to get the last bit.
13501		 */
13502		if ((cur_len & 0x7) != 0) {
13503			if (cur_len > 0x7) {
13504				cur_len = cur_len - (cur_len & 0x7);
13505				dma_length = cur_len;
13506			} else {
13507				CTL_SIZE_8B(dma_length, cur_len);
13508			}
13509
13510		} else
13511			dma_length = cur_len;
13512
13513		/*
13514		 * If we had to allocate memory for this I/O, instead of using
13515		 * the non-cached mirror memory, we'll need to flush the cache
13516		 * before trying to DMA to the other controller.
13517		 *
13518		 * We could end up doing this multiple times for the same
13519		 * segment if we have a larger local segment than remote
13520		 * segment.  That shouldn't be an issue.
13521		 */
13522		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13523			/*
13524			 * XXX KDM use bus_dmamap_sync() here.
13525			 */
13526		}
13527
13528		rq->size = dma_length;
13529
13530		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13531		tmp_ptr += local_used;
13532
13533		/* Use physical addresses when talking to ISC hardware */
13534		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13535			/* XXX KDM use busdma */
13536#if 0
13537			rq->local = vtophys(tmp_ptr);
13538#endif
13539		} else
13540			rq->local = tmp_ptr;
13541
13542		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13543		tmp_ptr += remote_used;
13544		rq->remote = tmp_ptr;
13545
13546		rq->callback = NULL;
13547
13548		local_used += cur_len;
13549		if (local_used >= local_sglist[i].len) {
13550			i++;
13551			local_used = 0;
13552		}
13553
13554		remote_used += cur_len;
13555		if (remote_used >= remote_sglist[j].len) {
13556			j++;
13557			remote_used = 0;
13558		}
13559		total_used += cur_len;
13560
13561		if (total_used >= io->scsiio.kern_data_len)
13562			rq->callback = callback;
13563
13564		if ((rq->size & 0x7) != 0) {
13565			printf("%s: warning: size %d is not on 8b boundary\n",
13566			       __func__, rq->size);
13567		}
13568		if (((uintptr_t)rq->local & 0x7) != 0) {
13569			printf("%s: warning: local %p not on 8b boundary\n",
13570			       __func__, rq->local);
13571		}
13572		if (((uintptr_t)rq->remote & 0x7) != 0) {
13573			printf("%s: warning: remote %p not on 8b boundary\n",
13574			       __func__, rq->local);
13575		}
13576#if 0
13577		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13578		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13579		       rq->local, rq->remote, rq->size);
13580#endif
13581
13582		isc_ret = ctl_dt_single(rq);
13583		if (isc_ret == CTL_HA_STATUS_WAIT)
13584			continue;
13585
13586		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13587			rq->ret = CTL_HA_STATUS_SUCCESS;
13588		} else {
13589			rq->ret = isc_ret;
13590		}
13591		callback(rq);
13592		goto bailout;
13593	}
13594
13595bailout:
13596	return (retval);
13597
13598}
13599
13600static void
13601ctl_datamove_remote_read(union ctl_io *io)
13602{
13603	int retval;
13604	int i;
13605
13606	/*
13607	 * This will send an error to the other controller in the case of a
13608	 * failure.
13609	 */
13610	retval = ctl_datamove_remote_sgl_setup(io);
13611	if (retval != 0)
13612		return;
13613
13614	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13615					  ctl_datamove_remote_read_cb);
13616	if ((retval != 0)
13617	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13618		/*
13619		 * Make sure we free memory if there was an error..  The
13620		 * ctl_datamove_remote_xfer() function will send the
13621		 * datamove done message, or call the callback with an
13622		 * error if there is a problem.
13623		 */
13624		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13625			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13626	}
13627
13628	return;
13629}
13630
13631/*
13632 * Process a datamove request from the other controller.  This is used for
13633 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13634 * first.  Once that is complete, the data gets DMAed into the remote
13635 * controller's memory.  For reads, we DMA from the remote controller's
13636 * memory into our memory first, and then move it out to the FETD.
13637 */
13638static void
13639ctl_datamove_remote(union ctl_io *io)
13640{
13641	struct ctl_softc *softc;
13642
13643	softc = control_softc;
13644
13645	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13646
13647	/*
13648	 * Note that we look for an aborted I/O here, but don't do some of
13649	 * the other checks that ctl_datamove() normally does.
13650	 * We don't need to run the datamove delay code, since that should
13651	 * have been done if need be on the other controller.
13652	 */
13653	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13654		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13655		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13656		       io->io_hdr.nexus.targ_port,
13657		       io->io_hdr.nexus.targ_target.id,
13658		       io->io_hdr.nexus.targ_lun);
13659		io->io_hdr.port_status = 31338;
13660		ctl_send_datamove_done(io, /*have_lock*/ 0);
13661		return;
13662	}
13663
13664	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13665		ctl_datamove_remote_write(io);
13666	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13667		ctl_datamove_remote_read(io);
13668	} else {
13669		union ctl_ha_msg msg;
13670		struct scsi_sense_data *sense;
13671		uint8_t sks[3];
13672		int retry_count;
13673
13674		memset(&msg, 0, sizeof(msg));
13675
13676		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13677		msg.hdr.status = CTL_SCSI_ERROR;
13678		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13679
13680		retry_count = 4243;
13681
13682		sense = &msg.scsi.sense_data;
13683		sks[0] = SSD_SCS_VALID;
13684		sks[1] = (retry_count >> 8) & 0xff;
13685		sks[2] = retry_count & 0xff;
13686
13687		/* "Internal target failure" */
13688		scsi_set_sense_data(sense,
13689				    /*sense_format*/ SSD_TYPE_NONE,
13690				    /*current_error*/ 1,
13691				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13692				    /*asc*/ 0x44,
13693				    /*ascq*/ 0x00,
13694				    /*type*/ SSD_ELEM_SKS,
13695				    /*size*/ sizeof(sks),
13696				    /*data*/ sks,
13697				    SSD_ELEM_NONE);
13698
13699		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13700		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13701			ctl_failover_io(io, /*have_lock*/ 1);
13702			return;
13703		}
13704
13705		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13706		    CTL_HA_STATUS_SUCCESS) {
13707			/* XXX KDM what to do if this fails? */
13708		}
13709		return;
13710	}
13711
13712}
13713
13714static int
13715ctl_process_done(union ctl_io *io)
13716{
13717	struct ctl_lun *lun;
13718	struct ctl_softc *ctl_softc;
13719	void (*fe_done)(union ctl_io *io);
13720	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13721
13722	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13723
13724	fe_done =
13725	    control_softc->ctl_ports[targ_port]->fe_done;
13726
13727#ifdef CTL_TIME_IO
13728	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13729		char str[256];
13730		char path_str[64];
13731		struct sbuf sb;
13732
13733		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13734		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13735
13736		sbuf_cat(&sb, path_str);
13737		switch (io->io_hdr.io_type) {
13738		case CTL_IO_SCSI:
13739			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13740			sbuf_printf(&sb, "\n");
13741			sbuf_cat(&sb, path_str);
13742			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13743				    io->scsiio.tag_num, io->scsiio.tag_type);
13744			break;
13745		case CTL_IO_TASK:
13746			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13747				    "Tag Type: %d\n", io->taskio.task_action,
13748				    io->taskio.tag_num, io->taskio.tag_type);
13749			break;
13750		default:
13751			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13752			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13753			break;
13754		}
13755		sbuf_cat(&sb, path_str);
13756		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13757			    (intmax_t)time_uptime - io->io_hdr.start_time);
13758		sbuf_finish(&sb);
13759		printf("%s", sbuf_data(&sb));
13760	}
13761#endif /* CTL_TIME_IO */
13762
13763	switch (io->io_hdr.io_type) {
13764	case CTL_IO_SCSI:
13765		break;
13766	case CTL_IO_TASK:
13767		if (bootverbose || verbose > 0)
13768			ctl_io_error_print(io, NULL);
13769		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13770			ctl_free_io(io);
13771		else
13772			fe_done(io);
13773		return (CTL_RETVAL_COMPLETE);
13774		break;
13775	default:
13776		printf("ctl_process_done: invalid io type %d\n",
13777		       io->io_hdr.io_type);
13778		panic("ctl_process_done: invalid io type %d\n",
13779		      io->io_hdr.io_type);
13780		break; /* NOTREACHED */
13781	}
13782
13783	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13784	if (lun == NULL) {
13785		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13786				 io->io_hdr.nexus.targ_mapped_lun));
13787		fe_done(io);
13788		goto bailout;
13789	}
13790	ctl_softc = lun->ctl_softc;
13791
13792	mtx_lock(&lun->lun_lock);
13793
13794	/*
13795	 * Check to see if we have any errors to inject here.  We only
13796	 * inject errors for commands that don't already have errors set.
13797	 */
13798	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13799	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13800		ctl_inject_error(lun, io);
13801
13802	/*
13803	 * XXX KDM how do we treat commands that aren't completed
13804	 * successfully?
13805	 *
13806	 * XXX KDM should we also track I/O latency?
13807	 */
13808	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13809	    io->io_hdr.io_type == CTL_IO_SCSI) {
13810#ifdef CTL_TIME_IO
13811		struct bintime cur_bt;
13812#endif
13813		int type;
13814
13815		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13816		    CTL_FLAG_DATA_IN)
13817			type = CTL_STATS_READ;
13818		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13819		    CTL_FLAG_DATA_OUT)
13820			type = CTL_STATS_WRITE;
13821		else
13822			type = CTL_STATS_NO_IO;
13823
13824		lun->stats.ports[targ_port].bytes[type] +=
13825		    io->scsiio.kern_total_len;
13826		lun->stats.ports[targ_port].operations[type]++;
13827#ifdef CTL_TIME_IO
13828		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13829		   &io->io_hdr.dma_bt);
13830		lun->stats.ports[targ_port].num_dmas[type] +=
13831		    io->io_hdr.num_dmas;
13832		getbintime(&cur_bt);
13833		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13834		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13835#endif
13836	}
13837
13838	/*
13839	 * Remove this from the OOA queue.
13840	 */
13841	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13842
13843	/*
13844	 * Run through the blocked queue on this LUN and see if anything
13845	 * has become unblocked, now that this transaction is done.
13846	 */
13847	ctl_check_blocked(lun);
13848
13849	/*
13850	 * If the LUN has been invalidated, free it if there is nothing
13851	 * left on its OOA queue.
13852	 */
13853	if ((lun->flags & CTL_LUN_INVALID)
13854	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13855		mtx_unlock(&lun->lun_lock);
13856		mtx_lock(&ctl_softc->ctl_lock);
13857		ctl_free_lun(lun);
13858		mtx_unlock(&ctl_softc->ctl_lock);
13859	} else
13860		mtx_unlock(&lun->lun_lock);
13861
13862	/*
13863	 * If this command has been aborted, make sure we set the status
13864	 * properly.  The FETD is responsible for freeing the I/O and doing
13865	 * whatever it needs to do to clean up its state.
13866	 */
13867	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13868		ctl_set_task_aborted(&io->scsiio);
13869
13870	/*
13871	 * We print out status for every task management command.  For SCSI
13872	 * commands, we filter out any unit attention errors; they happen
13873	 * on every boot, and would clutter up the log.  Note:  task
13874	 * management commands aren't printed here, they are printed above,
13875	 * since they should never even make it down here.
13876	 */
13877	switch (io->io_hdr.io_type) {
13878	case CTL_IO_SCSI: {
13879		int error_code, sense_key, asc, ascq;
13880
13881		sense_key = 0;
13882
13883		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13884		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13885			/*
13886			 * Since this is just for printing, no need to
13887			 * show errors here.
13888			 */
13889			scsi_extract_sense_len(&io->scsiio.sense_data,
13890					       io->scsiio.sense_len,
13891					       &error_code,
13892					       &sense_key,
13893					       &asc,
13894					       &ascq,
13895					       /*show_errors*/ 0);
13896		}
13897
13898		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13899		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13900		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13901		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13902
13903			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13904				ctl_softc->skipped_prints++;
13905			} else {
13906				uint32_t skipped_prints;
13907
13908				skipped_prints = ctl_softc->skipped_prints;
13909
13910				ctl_softc->skipped_prints = 0;
13911				ctl_softc->last_print_jiffies = time_uptime;
13912
13913				if (skipped_prints > 0) {
13914#ifdef NEEDTOPORT
13915					csevent_log(CSC_CTL | CSC_SHELF_SW |
13916					    CTL_ERROR_REPORT,
13917					    csevent_LogType_Trace,
13918					    csevent_Severity_Information,
13919					    csevent_AlertLevel_Green,
13920					    csevent_FRU_Firmware,
13921					    csevent_FRU_Unknown,
13922					    "High CTL error volume, %d prints "
13923					    "skipped", skipped_prints);
13924#endif
13925				}
13926				if (bootverbose || verbose > 0)
13927					ctl_io_error_print(io, NULL);
13928			}
13929		}
13930		break;
13931	}
13932	case CTL_IO_TASK:
13933		if (bootverbose || verbose > 0)
13934			ctl_io_error_print(io, NULL);
13935		break;
13936	default:
13937		break;
13938	}
13939
13940	/*
13941	 * Tell the FETD or the other shelf controller we're done with this
13942	 * command.  Note that only SCSI commands get to this point.  Task
13943	 * management commands are completed above.
13944	 *
13945	 * We only send status to the other controller if we're in XFER
13946	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13947	 * received the I/O (from CTL's perspective), and so the status is
13948	 * generated there.
13949	 *
13950	 * XXX KDM if we hold the lock here, we could cause a deadlock
13951	 * if the frontend comes back in in this context to queue
13952	 * something.
13953	 */
13954	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13955	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13956		union ctl_ha_msg msg;
13957
13958		memset(&msg, 0, sizeof(msg));
13959		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13960		msg.hdr.original_sc = io->io_hdr.original_sc;
13961		msg.hdr.nexus = io->io_hdr.nexus;
13962		msg.hdr.status = io->io_hdr.status;
13963		msg.scsi.scsi_status = io->scsiio.scsi_status;
13964		msg.scsi.tag_num = io->scsiio.tag_num;
13965		msg.scsi.tag_type = io->scsiio.tag_type;
13966		msg.scsi.sense_len = io->scsiio.sense_len;
13967		msg.scsi.sense_residual = io->scsiio.sense_residual;
13968		msg.scsi.residual = io->scsiio.residual;
13969		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13970		       sizeof(io->scsiio.sense_data));
13971		/*
13972		 * We copy this whether or not this is an I/O-related
13973		 * command.  Otherwise, we'd have to go and check to see
13974		 * whether it's a read/write command, and it really isn't
13975		 * worth it.
13976		 */
13977		memcpy(&msg.scsi.lbalen,
13978		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13979		       sizeof(msg.scsi.lbalen));
13980
13981		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13982				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13983			/* XXX do something here */
13984		}
13985
13986		ctl_free_io(io);
13987	} else
13988		fe_done(io);
13989
13990bailout:
13991
13992	return (CTL_RETVAL_COMPLETE);
13993}
13994
13995#ifdef CTL_WITH_CA
13996/*
13997 * Front end should call this if it doesn't do autosense.  When the request
13998 * sense comes back in from the initiator, we'll dequeue this and send it.
13999 */
14000int
14001ctl_queue_sense(union ctl_io *io)
14002{
14003	struct ctl_lun *lun;
14004	struct ctl_softc *ctl_softc;
14005	uint32_t initidx, targ_lun;
14006
14007	ctl_softc = control_softc;
14008
14009	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
14010
14011	/*
14012	 * LUN lookup will likely move to the ctl_work_thread() once we
14013	 * have our new queueing infrastructure (that doesn't put things on
14014	 * a per-LUN queue initially).  That is so that we can handle
14015	 * things like an INQUIRY to a LUN that we don't have enabled.  We
14016	 * can't deal with that right now.
14017	 */
14018	mtx_lock(&ctl_softc->ctl_lock);
14019
14020	/*
14021	 * If we don't have a LUN for this, just toss the sense
14022	 * information.
14023	 */
14024	targ_lun = io->io_hdr.nexus.targ_lun;
14025	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
14026	if ((targ_lun < CTL_MAX_LUNS)
14027	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
14028		lun = ctl_softc->ctl_luns[targ_lun];
14029	else
14030		goto bailout;
14031
14032	initidx = ctl_get_initindex(&io->io_hdr.nexus);
14033
14034	mtx_lock(&lun->lun_lock);
14035	/*
14036	 * Already have CA set for this LUN...toss the sense information.
14037	 */
14038	if (ctl_is_set(lun->have_ca, initidx)) {
14039		mtx_unlock(&lun->lun_lock);
14040		goto bailout;
14041	}
14042
14043	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
14044	       ctl_min(sizeof(lun->pending_sense[initidx]),
14045	       sizeof(io->scsiio.sense_data)));
14046	ctl_set_mask(lun->have_ca, initidx);
14047	mtx_unlock(&lun->lun_lock);
14048
14049bailout:
14050	mtx_unlock(&ctl_softc->ctl_lock);
14051
14052	ctl_free_io(io);
14053
14054	return (CTL_RETVAL_COMPLETE);
14055}
14056#endif
14057
14058/*
14059 * Primary command inlet from frontend ports.  All SCSI and task I/O
14060 * requests must go through this function.
14061 */
14062int
14063ctl_queue(union ctl_io *io)
14064{
14065	struct ctl_softc *ctl_softc;
14066
14067	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
14068
14069	ctl_softc = control_softc;
14070
14071#ifdef CTL_TIME_IO
14072	io->io_hdr.start_time = time_uptime;
14073	getbintime(&io->io_hdr.start_bt);
14074#endif /* CTL_TIME_IO */
14075
14076	/* Map FE-specific LUN ID into global one. */
14077	io->io_hdr.nexus.targ_mapped_lun =
14078	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
14079
14080	switch (io->io_hdr.io_type) {
14081	case CTL_IO_SCSI:
14082	case CTL_IO_TASK:
14083		ctl_enqueue_incoming(io);
14084		break;
14085	default:
14086		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14087		return (EINVAL);
14088	}
14089
14090	return (CTL_RETVAL_COMPLETE);
14091}
14092
14093#ifdef CTL_IO_DELAY
14094static void
14095ctl_done_timer_wakeup(void *arg)
14096{
14097	union ctl_io *io;
14098
14099	io = (union ctl_io *)arg;
14100	ctl_done(io);
14101}
14102#endif /* CTL_IO_DELAY */
14103
14104void
14105ctl_done(union ctl_io *io)
14106{
14107	struct ctl_softc *ctl_softc;
14108
14109	ctl_softc = control_softc;
14110
14111	/*
14112	 * Enable this to catch duplicate completion issues.
14113	 */
14114#if 0
14115	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14116		printf("%s: type %d msg %d cdb %x iptl: "
14117		       "%d:%d:%d:%d tag 0x%04x "
14118		       "flag %#x status %x\n",
14119			__func__,
14120			io->io_hdr.io_type,
14121			io->io_hdr.msg_type,
14122			io->scsiio.cdb[0],
14123			io->io_hdr.nexus.initid.id,
14124			io->io_hdr.nexus.targ_port,
14125			io->io_hdr.nexus.targ_target.id,
14126			io->io_hdr.nexus.targ_lun,
14127			(io->io_hdr.io_type ==
14128			CTL_IO_TASK) ?
14129			io->taskio.tag_num :
14130			io->scsiio.tag_num,
14131		        io->io_hdr.flags,
14132			io->io_hdr.status);
14133	} else
14134		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14135#endif
14136
14137	/*
14138	 * This is an internal copy of an I/O, and should not go through
14139	 * the normal done processing logic.
14140	 */
14141	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14142		return;
14143
14144	/*
14145	 * We need to send a msg to the serializing shelf to finish the IO
14146	 * as well.  We don't send a finish message to the other shelf if
14147	 * this is a task management command.  Task management commands
14148	 * aren't serialized in the OOA queue, but rather just executed on
14149	 * both shelf controllers for commands that originated on that
14150	 * controller.
14151	 */
14152	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14153	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14154		union ctl_ha_msg msg_io;
14155
14156		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14157		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14158		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14159		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14160		}
14161		/* continue on to finish IO */
14162	}
14163#ifdef CTL_IO_DELAY
14164	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14165		struct ctl_lun *lun;
14166
14167		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14168
14169		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14170	} else {
14171		struct ctl_lun *lun;
14172
14173		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14174
14175		if ((lun != NULL)
14176		 && (lun->delay_info.done_delay > 0)) {
14177			struct callout *callout;
14178
14179			callout = (struct callout *)&io->io_hdr.timer_bytes;
14180			callout_init(callout, /*mpsafe*/ 1);
14181			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14182			callout_reset(callout,
14183				      lun->delay_info.done_delay * hz,
14184				      ctl_done_timer_wakeup, io);
14185			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14186				lun->delay_info.done_delay = 0;
14187			return;
14188		}
14189	}
14190#endif /* CTL_IO_DELAY */
14191
14192	ctl_enqueue_done(io);
14193}
14194
14195int
14196ctl_isc(struct ctl_scsiio *ctsio)
14197{
14198	struct ctl_lun *lun;
14199	int retval;
14200
14201	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14202
14203	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14204
14205	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14206
14207	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14208
14209	return (retval);
14210}
14211
14212
14213static void
14214ctl_work_thread(void *arg)
14215{
14216	struct ctl_thread *thr = (struct ctl_thread *)arg;
14217	struct ctl_softc *softc = thr->ctl_softc;
14218	union ctl_io *io;
14219	int retval;
14220
14221	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14222
14223	for (;;) {
14224		retval = 0;
14225
14226		/*
14227		 * We handle the queues in this order:
14228		 * - ISC
14229		 * - done queue (to free up resources, unblock other commands)
14230		 * - RtR queue
14231		 * - incoming queue
14232		 *
14233		 * If those queues are empty, we break out of the loop and
14234		 * go to sleep.
14235		 */
14236		mtx_lock(&thr->queue_lock);
14237		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14238		if (io != NULL) {
14239			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14240			mtx_unlock(&thr->queue_lock);
14241			ctl_handle_isc(io);
14242			continue;
14243		}
14244		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14245		if (io != NULL) {
14246			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14247			/* clear any blocked commands, call fe_done */
14248			mtx_unlock(&thr->queue_lock);
14249			retval = ctl_process_done(io);
14250			continue;
14251		}
14252		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14253		if (io != NULL) {
14254			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14255			mtx_unlock(&thr->queue_lock);
14256			if (io->io_hdr.io_type == CTL_IO_TASK)
14257				ctl_run_task(io);
14258			else
14259				ctl_scsiio_precheck(softc, &io->scsiio);
14260			continue;
14261		}
14262		if (!ctl_pause_rtr) {
14263			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14264			if (io != NULL) {
14265				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14266				mtx_unlock(&thr->queue_lock);
14267				retval = ctl_scsiio(&io->scsiio);
14268				if (retval != CTL_RETVAL_COMPLETE)
14269					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14270				continue;
14271			}
14272		}
14273
14274		/* Sleep until we have something to do. */
14275		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14276	}
14277}
14278
14279static void
14280ctl_lun_thread(void *arg)
14281{
14282	struct ctl_softc *softc = (struct ctl_softc *)arg;
14283	struct ctl_be_lun *be_lun;
14284	int retval;
14285
14286	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14287
14288	for (;;) {
14289		retval = 0;
14290		mtx_lock(&softc->ctl_lock);
14291		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14292		if (be_lun != NULL) {
14293			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14294			mtx_unlock(&softc->ctl_lock);
14295			ctl_create_lun(be_lun);
14296			continue;
14297		}
14298
14299		/* Sleep until we have something to do. */
14300		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14301		    PDROP | PRIBIO, "-", 0);
14302	}
14303}
14304
14305static void
14306ctl_enqueue_incoming(union ctl_io *io)
14307{
14308	struct ctl_softc *softc = control_softc;
14309	struct ctl_thread *thr;
14310	u_int idx;
14311
14312	idx = (io->io_hdr.nexus.targ_port * 127 +
14313	       io->io_hdr.nexus.initid.id) % worker_threads;
14314	thr = &softc->threads[idx];
14315	mtx_lock(&thr->queue_lock);
14316	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14317	mtx_unlock(&thr->queue_lock);
14318	wakeup(thr);
14319}
14320
14321static void
14322ctl_enqueue_rtr(union ctl_io *io)
14323{
14324	struct ctl_softc *softc = control_softc;
14325	struct ctl_thread *thr;
14326
14327	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14328	mtx_lock(&thr->queue_lock);
14329	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14330	mtx_unlock(&thr->queue_lock);
14331	wakeup(thr);
14332}
14333
14334static void
14335ctl_enqueue_done(union ctl_io *io)
14336{
14337	struct ctl_softc *softc = control_softc;
14338	struct ctl_thread *thr;
14339
14340	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14341	mtx_lock(&thr->queue_lock);
14342	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14343	mtx_unlock(&thr->queue_lock);
14344	wakeup(thr);
14345}
14346
14347static void
14348ctl_enqueue_isc(union ctl_io *io)
14349{
14350	struct ctl_softc *softc = control_softc;
14351	struct ctl_thread *thr;
14352
14353	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14354	mtx_lock(&thr->queue_lock);
14355	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14356	mtx_unlock(&thr->queue_lock);
14357	wakeup(thr);
14358}
14359
14360/* Initialization and failover */
14361
14362void
14363ctl_init_isc_msg(void)
14364{
14365	printf("CTL: Still calling this thing\n");
14366}
14367
14368/*
14369 * Init component
14370 * 	Initializes component into configuration defined by bootMode
14371 *	(see hasc-sv.c)
14372 *  	returns hasc_Status:
14373 * 		OK
14374 *		ERROR - fatal error
14375 */
14376static ctl_ha_comp_status
14377ctl_isc_init(struct ctl_ha_component *c)
14378{
14379	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14380
14381	c->status = ret;
14382	return ret;
14383}
14384
14385/* Start component
14386 * 	Starts component in state requested. If component starts successfully,
14387 *	it must set its own state to the requestrd state
14388 *	When requested state is HASC_STATE_HA, the component may refine it
14389 * 	by adding _SLAVE or _MASTER flags.
14390 *	Currently allowed state transitions are:
14391 *	UNKNOWN->HA		- initial startup
14392 *	UNKNOWN->SINGLE - initial startup when no parter detected
14393 *	HA->SINGLE		- failover
14394 * returns ctl_ha_comp_status:
14395 * 		OK	- component successfully started in requested state
14396 *		FAILED  - could not start the requested state, failover may
14397 * 			  be possible
14398 *		ERROR	- fatal error detected, no future startup possible
14399 */
14400static ctl_ha_comp_status
14401ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14402{
14403	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14404
14405	printf("%s: go\n", __func__);
14406
14407	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14408	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14409		ctl_is_single = 0;
14410		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14411		    != CTL_HA_STATUS_SUCCESS) {
14412			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14413			ret = CTL_HA_COMP_STATUS_ERROR;
14414		}
14415	} else if (CTL_HA_STATE_IS_HA(c->state)
14416		&& CTL_HA_STATE_IS_SINGLE(state)){
14417		// HA->SINGLE transition
14418	        ctl_failover();
14419		ctl_is_single = 1;
14420	} else {
14421		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14422		       c->state, state);
14423		ret = CTL_HA_COMP_STATUS_ERROR;
14424	}
14425	if (CTL_HA_STATE_IS_SINGLE(state))
14426		ctl_is_single = 1;
14427
14428	c->state = state;
14429	c->status = ret;
14430	return ret;
14431}
14432
14433/*
14434 * Quiesce component
14435 * The component must clear any error conditions (set status to OK) and
14436 * prepare itself to another Start call
14437 * returns ctl_ha_comp_status:
14438 * 	OK
14439 *	ERROR
14440 */
14441static ctl_ha_comp_status
14442ctl_isc_quiesce(struct ctl_ha_component *c)
14443{
14444	int ret = CTL_HA_COMP_STATUS_OK;
14445
14446	ctl_pause_rtr = 1;
14447	c->status = ret;
14448	return ret;
14449}
14450
14451struct ctl_ha_component ctl_ha_component_ctlisc =
14452{
14453	.name = "CTL ISC",
14454	.state = CTL_HA_STATE_UNKNOWN,
14455	.init = ctl_isc_init,
14456	.start = ctl_isc_start,
14457	.quiesce = ctl_isc_quiesce
14458};
14459
14460/*
14461 *  vim: ts=8
14462 */
14463