ctl.c revision 272893
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 272893 2014-10-10 12:38:53Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/types.h>
51#include <sys/kthread.h>
52#include <sys/bio.h>
53#include <sys/fcntl.h>
54#include <sys/lock.h>
55#include <sys/module.h>
56#include <sys/mutex.h>
57#include <sys/condvar.h>
58#include <sys/malloc.h>
59#include <sys/conf.h>
60#include <sys/ioccom.h>
61#include <sys/queue.h>
62#include <sys/sbuf.h>
63#include <sys/smp.h>
64#include <sys/endian.h>
65#include <sys/sysctl.h>
66
67#include <cam/cam.h>
68#include <cam/scsi/scsi_all.h>
69#include <cam/scsi/scsi_da.h>
70#include <cam/ctl/ctl_io.h>
71#include <cam/ctl/ctl.h>
72#include <cam/ctl/ctl_frontend.h>
73#include <cam/ctl/ctl_frontend_internal.h>
74#include <cam/ctl/ctl_util.h>
75#include <cam/ctl/ctl_backend.h>
76#include <cam/ctl/ctl_ioctl.h>
77#include <cam/ctl/ctl_ha.h>
78#include <cam/ctl/ctl_private.h>
79#include <cam/ctl/ctl_debug.h>
80#include <cam/ctl/ctl_scsi_all.h>
81#include <cam/ctl/ctl_error.h>
82
83struct ctl_softc *control_softc = NULL;
84
85/*
86 * Size and alignment macros needed for Copan-specific HA hardware.  These
87 * can go away when the HA code is re-written, and uses busdma for any
88 * hardware.
89 */
90#define	CTL_ALIGN_8B(target, source, type)				\
91	if (((uint32_t)source & 0x7) != 0)				\
92		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93	else								\
94		target = (type)source;
95
96#define	CTL_SIZE_8B(target, size)					\
97	if ((size & 0x7) != 0)						\
98		target = size + (0x8 - (size & 0x7));			\
99	else								\
100		target = size;
101
102#define CTL_ALIGN_8B_MARGIN	16
103
104/*
105 * Template mode pages.
106 */
107
108/*
109 * Note that these are default values only.  The actual values will be
110 * filled in when the user does a mode sense.
111 */
112static struct copan_power_subpage power_page_default = {
113	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114	/*subpage*/ PWR_SUBPAGE_CODE,
115	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117	/*page_version*/ PWR_VERSION,
118	/* total_luns */ 26,
119	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122		      0, 0, 0, 0, 0, 0}
123};
124
125static struct copan_power_subpage power_page_changeable = {
126	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127	/*subpage*/ PWR_SUBPAGE_CODE,
128	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130	/*page_version*/ 0,
131	/* total_luns */ 0,
132	/* max_active_luns*/ 0,
133	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135		      0, 0, 0, 0, 0, 0}
136};
137
138static struct copan_aps_subpage aps_page_default = {
139	APS_PAGE_CODE | SMPH_SPF, //page_code
140	APS_SUBPAGE_CODE, //subpage
141	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143	APS_VERSION, //page_version
144	0, //lock_active
145	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147	0, 0, 0, 0, 0} //reserved
148};
149
150static struct copan_aps_subpage aps_page_changeable = {
151	APS_PAGE_CODE | SMPH_SPF, //page_code
152	APS_SUBPAGE_CODE, //subpage
153	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155	0, //page_version
156	0, //lock_active
157	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159	0, 0, 0, 0, 0} //reserved
160};
161
162static struct copan_debugconf_subpage debugconf_page_default = {
163	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
164	DBGCNF_SUBPAGE_CODE,		/* subpage */
165	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167	DBGCNF_VERSION,			/* page_version */
168	{CTL_TIME_IO_DEFAULT_SECS>>8,
169	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
170};
171
172static struct copan_debugconf_subpage debugconf_page_changeable = {
173	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
174	DBGCNF_SUBPAGE_CODE,		/* subpage */
175	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177	0,				/* page_version */
178	{0xff,0xff},			/* ctl_time_io_secs */
179};
180
181static struct scsi_format_page format_page_default = {
182	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
183	/*page_length*/sizeof(struct scsi_format_page) - 2,
184	/*tracks_per_zone*/ {0, 0},
185	/*alt_sectors_per_zone*/ {0, 0},
186	/*alt_tracks_per_zone*/ {0, 0},
187	/*alt_tracks_per_lun*/ {0, 0},
188	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190	/*bytes_per_sector*/ {0, 0},
191	/*interleave*/ {0, 0},
192	/*track_skew*/ {0, 0},
193	/*cylinder_skew*/ {0, 0},
194	/*flags*/ SFP_HSEC,
195	/*reserved*/ {0, 0, 0}
196};
197
198static struct scsi_format_page format_page_changeable = {
199	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
200	/*page_length*/sizeof(struct scsi_format_page) - 2,
201	/*tracks_per_zone*/ {0, 0},
202	/*alt_sectors_per_zone*/ {0, 0},
203	/*alt_tracks_per_zone*/ {0, 0},
204	/*alt_tracks_per_lun*/ {0, 0},
205	/*sectors_per_track*/ {0, 0},
206	/*bytes_per_sector*/ {0, 0},
207	/*interleave*/ {0, 0},
208	/*track_skew*/ {0, 0},
209	/*cylinder_skew*/ {0, 0},
210	/*flags*/ 0,
211	/*reserved*/ {0, 0, 0}
212};
213
214static struct scsi_rigid_disk_page rigid_disk_page_default = {
215	/*page_code*/SMS_RIGID_DISK_PAGE,
216	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217	/*cylinders*/ {0, 0, 0},
218	/*heads*/ CTL_DEFAULT_HEADS,
219	/*start_write_precomp*/ {0, 0, 0},
220	/*start_reduced_current*/ {0, 0, 0},
221	/*step_rate*/ {0, 0},
222	/*landing_zone_cylinder*/ {0, 0, 0},
223	/*rpl*/ SRDP_RPL_DISABLED,
224	/*rotational_offset*/ 0,
225	/*reserved1*/ 0,
226	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227			   CTL_DEFAULT_ROTATION_RATE & 0xff},
228	/*reserved2*/ {0, 0}
229};
230
231static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232	/*page_code*/SMS_RIGID_DISK_PAGE,
233	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234	/*cylinders*/ {0, 0, 0},
235	/*heads*/ 0,
236	/*start_write_precomp*/ {0, 0, 0},
237	/*start_reduced_current*/ {0, 0, 0},
238	/*step_rate*/ {0, 0},
239	/*landing_zone_cylinder*/ {0, 0, 0},
240	/*rpl*/ 0,
241	/*rotational_offset*/ 0,
242	/*reserved1*/ 0,
243	/*rotation_rate*/ {0, 0},
244	/*reserved2*/ {0, 0}
245};
246
247static struct scsi_caching_page caching_page_default = {
248	/*page_code*/SMS_CACHING_PAGE,
249	/*page_length*/sizeof(struct scsi_caching_page) - 2,
250	/*flags1*/ SCP_DISC | SCP_WCE,
251	/*ret_priority*/ 0,
252	/*disable_pf_transfer_len*/ {0xff, 0xff},
253	/*min_prefetch*/ {0, 0},
254	/*max_prefetch*/ {0xff, 0xff},
255	/*max_pf_ceiling*/ {0xff, 0xff},
256	/*flags2*/ 0,
257	/*cache_segments*/ 0,
258	/*cache_seg_size*/ {0, 0},
259	/*reserved*/ 0,
260	/*non_cache_seg_size*/ {0, 0, 0}
261};
262
263static struct scsi_caching_page caching_page_changeable = {
264	/*page_code*/SMS_CACHING_PAGE,
265	/*page_length*/sizeof(struct scsi_caching_page) - 2,
266	/*flags1*/ SCP_WCE | SCP_RCD,
267	/*ret_priority*/ 0,
268	/*disable_pf_transfer_len*/ {0, 0},
269	/*min_prefetch*/ {0, 0},
270	/*max_prefetch*/ {0, 0},
271	/*max_pf_ceiling*/ {0, 0},
272	/*flags2*/ 0,
273	/*cache_segments*/ 0,
274	/*cache_seg_size*/ {0, 0},
275	/*reserved*/ 0,
276	/*non_cache_seg_size*/ {0, 0, 0}
277};
278
279static struct scsi_control_page control_page_default = {
280	/*page_code*/SMS_CONTROL_MODE_PAGE,
281	/*page_length*/sizeof(struct scsi_control_page) - 2,
282	/*rlec*/0,
283	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
284	/*eca_and_aen*/0,
285	/*flags4*/SCP_TAS,
286	/*aen_holdoff_period*/{0, 0},
287	/*busy_timeout_period*/{0, 0},
288	/*extended_selftest_completion_time*/{0, 0}
289};
290
291static struct scsi_control_page control_page_changeable = {
292	/*page_code*/SMS_CONTROL_MODE_PAGE,
293	/*page_length*/sizeof(struct scsi_control_page) - 2,
294	/*rlec*/SCP_DSENSE,
295	/*queue_flags*/SCP_QUEUE_ALG_MASK,
296	/*eca_and_aen*/SCP_SWP,
297	/*flags4*/0,
298	/*aen_holdoff_period*/{0, 0},
299	/*busy_timeout_period*/{0, 0},
300	/*extended_selftest_completion_time*/{0, 0}
301};
302
303
304/*
305 * XXX KDM move these into the softc.
306 */
307static int rcv_sync_msg;
308static int persis_offset;
309static uint8_t ctl_pause_rtr;
310static int     ctl_is_single = 1;
311static int     index_to_aps_page;
312
313SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314static int worker_threads = -1;
315SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316    &worker_threads, 1, "Number of worker threads");
317static int verbose = 0;
318SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319    &verbose, 0, "Show SCSI errors returned to initiator");
320
321/*
322 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
324 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
325 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
326 */
327#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
328
329static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
330				  int param);
331static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
332static int ctl_init(void);
333void ctl_shutdown(void);
334static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
335static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
336static void ctl_ioctl_online(void *arg);
337static void ctl_ioctl_offline(void *arg);
338static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
339static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
340static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
341static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
342static int ctl_ioctl_submit_wait(union ctl_io *io);
343static void ctl_ioctl_datamove(union ctl_io *io);
344static void ctl_ioctl_done(union ctl_io *io);
345static void ctl_ioctl_hard_startstop_callback(void *arg,
346					      struct cfi_metatask *metatask);
347static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
348static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
349			      struct ctl_ooa *ooa_hdr,
350			      struct ctl_ooa_entry *kern_entries);
351static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
352		     struct thread *td);
353static uint32_t ctl_map_lun(int port_num, uint32_t lun);
354static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
355#ifdef unused
356static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
357				   uint32_t targ_target, uint32_t targ_lun,
358				   int can_wait);
359static void ctl_kfree_io(union ctl_io *io);
360#endif /* unused */
361static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
362			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
363static int ctl_free_lun(struct ctl_lun *lun);
364static void ctl_create_lun(struct ctl_be_lun *be_lun);
365/**
366static void ctl_failover_change_pages(struct ctl_softc *softc,
367				      struct ctl_scsiio *ctsio, int master);
368**/
369
370static int ctl_do_mode_select(union ctl_io *io);
371static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
372			   uint64_t res_key, uint64_t sa_res_key,
373			   uint8_t type, uint32_t residx,
374			   struct ctl_scsiio *ctsio,
375			   struct scsi_per_res_out *cdb,
376			   struct scsi_per_res_out_parms* param);
377static void ctl_pro_preempt_other(struct ctl_lun *lun,
378				  union ctl_ha_msg *msg);
379static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
380static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
381static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
382static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
383static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
385static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
386					 int alloc_len);
387static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
388					 int alloc_len);
389static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
390static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
391static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
392static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
393static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
394static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
395static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
396    union ctl_io *pending_io, union ctl_io *ooa_io);
397static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
398				union ctl_io *starting_io);
399static int ctl_check_blocked(struct ctl_lun *lun);
400static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
401				struct ctl_lun *lun,
402				const struct ctl_cmd_entry *entry,
403				struct ctl_scsiio *ctsio);
404//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
405static void ctl_failover(void);
406static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
407			       struct ctl_scsiio *ctsio);
408static int ctl_scsiio(struct ctl_scsiio *ctsio);
409
410static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
411static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
412			    ctl_ua_type ua_type);
413static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
414			 ctl_ua_type ua_type);
415static int ctl_abort_task(union ctl_io *io);
416static int ctl_abort_task_set(union ctl_io *io);
417static int ctl_i_t_nexus_reset(union ctl_io *io);
418static void ctl_run_task(union ctl_io *io);
419#ifdef CTL_IO_DELAY
420static void ctl_datamove_timer_wakeup(void *arg);
421static void ctl_done_timer_wakeup(void *arg);
422#endif /* CTL_IO_DELAY */
423
424static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
425static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
426static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
427static void ctl_datamove_remote_write(union ctl_io *io);
428static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
429static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
430static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
431static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
432				    ctl_ha_dt_cb callback);
433static void ctl_datamove_remote_read(union ctl_io *io);
434static void ctl_datamove_remote(union ctl_io *io);
435static int ctl_process_done(union ctl_io *io);
436static void ctl_lun_thread(void *arg);
437static void ctl_work_thread(void *arg);
438static void ctl_enqueue_incoming(union ctl_io *io);
439static void ctl_enqueue_rtr(union ctl_io *io);
440static void ctl_enqueue_done(union ctl_io *io);
441static void ctl_enqueue_isc(union ctl_io *io);
442static const struct ctl_cmd_entry *
443    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
444static const struct ctl_cmd_entry *
445    ctl_validate_command(struct ctl_scsiio *ctsio);
446static int ctl_cmd_applicable(uint8_t lun_type,
447    const struct ctl_cmd_entry *entry);
448
449/*
450 * Load the serialization table.  This isn't very pretty, but is probably
451 * the easiest way to do it.
452 */
453#include "ctl_ser_table.c"
454
455/*
456 * We only need to define open, close and ioctl routines for this driver.
457 */
458static struct cdevsw ctl_cdevsw = {
459	.d_version =	D_VERSION,
460	.d_flags =	0,
461	.d_open =	ctl_open,
462	.d_close =	ctl_close,
463	.d_ioctl =	ctl_ioctl,
464	.d_name =	"ctl",
465};
466
467
468MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
469MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
470
471static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
472
473static moduledata_t ctl_moduledata = {
474	"ctl",
475	ctl_module_event_handler,
476	NULL
477};
478
479DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
480MODULE_VERSION(ctl, 1);
481
482static struct ctl_frontend ioctl_frontend =
483{
484	.name = "ioctl",
485};
486
487static void
488ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
489			    union ctl_ha_msg *msg_info)
490{
491	struct ctl_scsiio *ctsio;
492
493	if (msg_info->hdr.original_sc == NULL) {
494		printf("%s: original_sc == NULL!\n", __func__);
495		/* XXX KDM now what? */
496		return;
497	}
498
499	ctsio = &msg_info->hdr.original_sc->scsiio;
500	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
501	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
502	ctsio->io_hdr.status = msg_info->hdr.status;
503	ctsio->scsi_status = msg_info->scsi.scsi_status;
504	ctsio->sense_len = msg_info->scsi.sense_len;
505	ctsio->sense_residual = msg_info->scsi.sense_residual;
506	ctsio->residual = msg_info->scsi.residual;
507	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
508	       sizeof(ctsio->sense_data));
509	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
510	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
511	ctl_enqueue_isc((union ctl_io *)ctsio);
512}
513
514static void
515ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
516				union ctl_ha_msg *msg_info)
517{
518	struct ctl_scsiio *ctsio;
519
520	if (msg_info->hdr.serializing_sc == NULL) {
521		printf("%s: serializing_sc == NULL!\n", __func__);
522		/* XXX KDM now what? */
523		return;
524	}
525
526	ctsio = &msg_info->hdr.serializing_sc->scsiio;
527#if 0
528	/*
529	 * Attempt to catch the situation where an I/O has
530	 * been freed, and we're using it again.
531	 */
532	if (ctsio->io_hdr.io_type == 0xff) {
533		union ctl_io *tmp_io;
534		tmp_io = (union ctl_io *)ctsio;
535		printf("%s: %p use after free!\n", __func__,
536		       ctsio);
537		printf("%s: type %d msg %d cdb %x iptl: "
538		       "%d:%d:%d:%d tag 0x%04x "
539		       "flag %#x status %x\n",
540			__func__,
541			tmp_io->io_hdr.io_type,
542			tmp_io->io_hdr.msg_type,
543			tmp_io->scsiio.cdb[0],
544			tmp_io->io_hdr.nexus.initid.id,
545			tmp_io->io_hdr.nexus.targ_port,
546			tmp_io->io_hdr.nexus.targ_target.id,
547			tmp_io->io_hdr.nexus.targ_lun,
548			(tmp_io->io_hdr.io_type ==
549			CTL_IO_TASK) ?
550			tmp_io->taskio.tag_num :
551			tmp_io->scsiio.tag_num,
552		        tmp_io->io_hdr.flags,
553			tmp_io->io_hdr.status);
554	}
555#endif
556	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
557	ctl_enqueue_isc((union ctl_io *)ctsio);
558}
559
560/*
561 * ISC (Inter Shelf Communication) event handler.  Events from the HA
562 * subsystem come in here.
563 */
564static void
565ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
566{
567	struct ctl_softc *ctl_softc;
568	union ctl_io *io;
569	struct ctl_prio *presio;
570	ctl_ha_status isc_status;
571
572	ctl_softc = control_softc;
573	io = NULL;
574
575
576#if 0
577	printf("CTL: Isc Msg event %d\n", event);
578#endif
579	if (event == CTL_HA_EVT_MSG_RECV) {
580		union ctl_ha_msg msg_info;
581
582		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
583					     sizeof(msg_info), /*wait*/ 0);
584#if 0
585		printf("CTL: msg_type %d\n", msg_info.msg_type);
586#endif
587		if (isc_status != 0) {
588			printf("Error receiving message, status = %d\n",
589			       isc_status);
590			return;
591		}
592
593		switch (msg_info.hdr.msg_type) {
594		case CTL_MSG_SERIALIZE:
595#if 0
596			printf("Serialize\n");
597#endif
598			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
599			if (io == NULL) {
600				printf("ctl_isc_event_handler: can't allocate "
601				       "ctl_io!\n");
602				/* Bad Juju */
603				/* Need to set busy and send msg back */
604				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
605				msg_info.hdr.status = CTL_SCSI_ERROR;
606				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
607				msg_info.scsi.sense_len = 0;
608			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
609				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
610				}
611				goto bailout;
612			}
613			ctl_zero_io(io);
614			// populate ctsio from msg_info
615			io->io_hdr.io_type = CTL_IO_SCSI;
616			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
617			io->io_hdr.original_sc = msg_info.hdr.original_sc;
618#if 0
619			printf("pOrig %x\n", (int)msg_info.original_sc);
620#endif
621			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
622					    CTL_FLAG_IO_ACTIVE;
623			/*
624			 * If we're in serialization-only mode, we don't
625			 * want to go through full done processing.  Thus
626			 * the COPY flag.
627			 *
628			 * XXX KDM add another flag that is more specific.
629			 */
630			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
631				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
632			io->io_hdr.nexus = msg_info.hdr.nexus;
633#if 0
634			printf("targ %d, port %d, iid %d, lun %d\n",
635			       io->io_hdr.nexus.targ_target.id,
636			       io->io_hdr.nexus.targ_port,
637			       io->io_hdr.nexus.initid.id,
638			       io->io_hdr.nexus.targ_lun);
639#endif
640			io->scsiio.tag_num = msg_info.scsi.tag_num;
641			io->scsiio.tag_type = msg_info.scsi.tag_type;
642			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
643			       CTL_MAX_CDBLEN);
644			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
645				const struct ctl_cmd_entry *entry;
646
647				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
648				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
649				io->io_hdr.flags |=
650					entry->flags & CTL_FLAG_DATA_MASK;
651			}
652			ctl_enqueue_isc(io);
653			break;
654
655		/* Performed on the Originating SC, XFER mode only */
656		case CTL_MSG_DATAMOVE: {
657			struct ctl_sg_entry *sgl;
658			int i, j;
659
660			io = msg_info.hdr.original_sc;
661			if (io == NULL) {
662				printf("%s: original_sc == NULL!\n", __func__);
663				/* XXX KDM do something here */
664				break;
665			}
666			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
667			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
668			/*
669			 * Keep track of this, we need to send it back over
670			 * when the datamove is complete.
671			 */
672			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
673
674			if (msg_info.dt.sg_sequence == 0) {
675				/*
676				 * XXX KDM we use the preallocated S/G list
677				 * here, but we'll need to change this to
678				 * dynamic allocation if we need larger S/G
679				 * lists.
680				 */
681				if (msg_info.dt.kern_sg_entries >
682				    sizeof(io->io_hdr.remote_sglist) /
683				    sizeof(io->io_hdr.remote_sglist[0])) {
684					printf("%s: number of S/G entries "
685					    "needed %u > allocated num %zd\n",
686					    __func__,
687					    msg_info.dt.kern_sg_entries,
688					    sizeof(io->io_hdr.remote_sglist)/
689					    sizeof(io->io_hdr.remote_sglist[0]));
690
691					/*
692					 * XXX KDM send a message back to
693					 * the other side to shut down the
694					 * DMA.  The error will come back
695					 * through via the normal channel.
696					 */
697					break;
698				}
699				sgl = io->io_hdr.remote_sglist;
700				memset(sgl, 0,
701				       sizeof(io->io_hdr.remote_sglist));
702
703				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
704
705				io->scsiio.kern_sg_entries =
706					msg_info.dt.kern_sg_entries;
707				io->scsiio.rem_sg_entries =
708					msg_info.dt.kern_sg_entries;
709				io->scsiio.kern_data_len =
710					msg_info.dt.kern_data_len;
711				io->scsiio.kern_total_len =
712					msg_info.dt.kern_total_len;
713				io->scsiio.kern_data_resid =
714					msg_info.dt.kern_data_resid;
715				io->scsiio.kern_rel_offset =
716					msg_info.dt.kern_rel_offset;
717				/*
718				 * Clear out per-DMA flags.
719				 */
720				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
721				/*
722				 * Add per-DMA flags that are set for this
723				 * particular DMA request.
724				 */
725				io->io_hdr.flags |= msg_info.dt.flags &
726						    CTL_FLAG_RDMA_MASK;
727			} else
728				sgl = (struct ctl_sg_entry *)
729					io->scsiio.kern_data_ptr;
730
731			for (i = msg_info.dt.sent_sg_entries, j = 0;
732			     i < (msg_info.dt.sent_sg_entries +
733			     msg_info.dt.cur_sg_entries); i++, j++) {
734				sgl[i].addr = msg_info.dt.sg_list[j].addr;
735				sgl[i].len = msg_info.dt.sg_list[j].len;
736
737#if 0
738				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
739				       __func__,
740				       msg_info.dt.sg_list[j].addr,
741				       msg_info.dt.sg_list[j].len,
742				       sgl[i].addr, sgl[i].len, j, i);
743#endif
744			}
745#if 0
746			memcpy(&sgl[msg_info.dt.sent_sg_entries],
747			       msg_info.dt.sg_list,
748			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
749#endif
750
751			/*
752			 * If this is the last piece of the I/O, we've got
753			 * the full S/G list.  Queue processing in the thread.
754			 * Otherwise wait for the next piece.
755			 */
756			if (msg_info.dt.sg_last != 0)
757				ctl_enqueue_isc(io);
758			break;
759		}
760		/* Performed on the Serializing (primary) SC, XFER mode only */
761		case CTL_MSG_DATAMOVE_DONE: {
762			if (msg_info.hdr.serializing_sc == NULL) {
763				printf("%s: serializing_sc == NULL!\n",
764				       __func__);
765				/* XXX KDM now what? */
766				break;
767			}
768			/*
769			 * We grab the sense information here in case
770			 * there was a failure, so we can return status
771			 * back to the initiator.
772			 */
773			io = msg_info.hdr.serializing_sc;
774			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
775			io->io_hdr.status = msg_info.hdr.status;
776			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
777			io->scsiio.sense_len = msg_info.scsi.sense_len;
778			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
779			io->io_hdr.port_status = msg_info.scsi.fetd_status;
780			io->scsiio.residual = msg_info.scsi.residual;
781			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
782			       sizeof(io->scsiio.sense_data));
783			ctl_enqueue_isc(io);
784			break;
785		}
786
787		/* Preformed on Originating SC, SER_ONLY mode */
788		case CTL_MSG_R2R:
789			io = msg_info.hdr.original_sc;
790			if (io == NULL) {
791				printf("%s: Major Bummer\n", __func__);
792				return;
793			} else {
794#if 0
795				printf("pOrig %x\n",(int) ctsio);
796#endif
797			}
798			io->io_hdr.msg_type = CTL_MSG_R2R;
799			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
800			ctl_enqueue_isc(io);
801			break;
802
803		/*
804		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
805		 * mode.
806		 * Performed on the Originating (i.e. secondary) SC in XFER
807		 * mode
808		 */
809		case CTL_MSG_FINISH_IO:
810			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
811				ctl_isc_handler_finish_xfer(ctl_softc,
812							    &msg_info);
813			else
814				ctl_isc_handler_finish_ser_only(ctl_softc,
815								&msg_info);
816			break;
817
818		/* Preformed on Originating SC */
819		case CTL_MSG_BAD_JUJU:
820			io = msg_info.hdr.original_sc;
821			if (io == NULL) {
822				printf("%s: Bad JUJU!, original_sc is NULL!\n",
823				       __func__);
824				break;
825			}
826			ctl_copy_sense_data(&msg_info, io);
827			/*
828			 * IO should have already been cleaned up on other
829			 * SC so clear this flag so we won't send a message
830			 * back to finish the IO there.
831			 */
832			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
833			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
834
835			/* io = msg_info.hdr.serializing_sc; */
836			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
837			ctl_enqueue_isc(io);
838			break;
839
840		/* Handle resets sent from the other side */
841		case CTL_MSG_MANAGE_TASKS: {
842			struct ctl_taskio *taskio;
843			taskio = (struct ctl_taskio *)ctl_alloc_io(
844				(void *)ctl_softc->othersc_pool);
845			if (taskio == NULL) {
846				printf("ctl_isc_event_handler: can't allocate "
847				       "ctl_io!\n");
848				/* Bad Juju */
849				/* should I just call the proper reset func
850				   here??? */
851				goto bailout;
852			}
853			ctl_zero_io((union ctl_io *)taskio);
854			taskio->io_hdr.io_type = CTL_IO_TASK;
855			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
856			taskio->io_hdr.nexus = msg_info.hdr.nexus;
857			taskio->task_action = msg_info.task.task_action;
858			taskio->tag_num = msg_info.task.tag_num;
859			taskio->tag_type = msg_info.task.tag_type;
860#ifdef CTL_TIME_IO
861			taskio->io_hdr.start_time = time_uptime;
862			getbintime(&taskio->io_hdr.start_bt);
863#if 0
864			cs_prof_gettime(&taskio->io_hdr.start_ticks);
865#endif
866#endif /* CTL_TIME_IO */
867			ctl_run_task((union ctl_io *)taskio);
868			break;
869		}
870		/* Persistent Reserve action which needs attention */
871		case CTL_MSG_PERS_ACTION:
872			presio = (struct ctl_prio *)ctl_alloc_io(
873				(void *)ctl_softc->othersc_pool);
874			if (presio == NULL) {
875				printf("ctl_isc_event_handler: can't allocate "
876				       "ctl_io!\n");
877				/* Bad Juju */
878				/* Need to set busy and send msg back */
879				goto bailout;
880			}
881			ctl_zero_io((union ctl_io *)presio);
882			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883			presio->pr_msg = msg_info.pr;
884			ctl_enqueue_isc((union ctl_io *)presio);
885			break;
886		case CTL_MSG_SYNC_FE:
887			rcv_sync_msg = 1;
888			break;
889		case CTL_MSG_APS_LOCK: {
890			// It's quicker to execute this then to
891			// queue it.
892			struct ctl_lun *lun;
893			struct ctl_page_index *page_index;
894			struct copan_aps_subpage *current_sp;
895			uint32_t targ_lun;
896
897			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
898			lun = ctl_softc->ctl_luns[targ_lun];
899			mtx_lock(&lun->lun_lock);
900			page_index = &lun->mode_pages.index[index_to_aps_page];
901			current_sp = (struct copan_aps_subpage *)
902				     (page_index->page_data +
903				     (page_index->page_len * CTL_PAGE_CURRENT));
904
905			current_sp->lock_active = msg_info.aps.lock_flag;
906			mtx_unlock(&lun->lun_lock);
907		        break;
908		}
909		default:
910		        printf("How did I get here?\n");
911		}
912	} else if (event == CTL_HA_EVT_MSG_SENT) {
913		if (param != CTL_HA_STATUS_SUCCESS) {
914			printf("Bad status from ctl_ha_msg_send status %d\n",
915			       param);
916		}
917		return;
918	} else if (event == CTL_HA_EVT_DISCONNECT) {
919		printf("CTL: Got a disconnect from Isc\n");
920		return;
921	} else {
922		printf("ctl_isc_event_handler: Unknown event %d\n", event);
923		return;
924	}
925
926bailout:
927	return;
928}
929
930static void
931ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
932{
933	struct scsi_sense_data *sense;
934
935	sense = &dest->scsiio.sense_data;
936	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
937	dest->scsiio.scsi_status = src->scsi.scsi_status;
938	dest->scsiio.sense_len = src->scsi.sense_len;
939	dest->io_hdr.status = src->hdr.status;
940}
941
942static int
943ctl_init(void)
944{
945	struct ctl_softc *softc;
946	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
947	struct ctl_port *port;
948        uint8_t sc_id =0;
949	int i, error, retval;
950	//int isc_retval;
951
952	retval = 0;
953	ctl_pause_rtr = 0;
954        rcv_sync_msg = 0;
955
956	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
957			       M_WAITOK | M_ZERO);
958	softc = control_softc;
959
960	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
961			      "cam/ctl");
962
963	softc->dev->si_drv1 = softc;
964
965	/*
966	 * By default, return a "bad LUN" peripheral qualifier for unknown
967	 * LUNs.  The user can override this default using the tunable or
968	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
969	 */
970	softc->inquiry_pq_no_lun = 1;
971	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
972			  &softc->inquiry_pq_no_lun);
973	sysctl_ctx_init(&softc->sysctl_ctx);
974	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
975		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
976		CTLFLAG_RD, 0, "CAM Target Layer");
977
978	if (softc->sysctl_tree == NULL) {
979		printf("%s: unable to allocate sysctl tree\n", __func__);
980		destroy_dev(softc->dev);
981		free(control_softc, M_DEVBUF);
982		control_softc = NULL;
983		return (ENOMEM);
984	}
985
986	SYSCTL_ADD_INT(&softc->sysctl_ctx,
987		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
988		       "inquiry_pq_no_lun", CTLFLAG_RW,
989		       &softc->inquiry_pq_no_lun, 0,
990		       "Report no lun possible for invalid LUNs");
991
992	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
993	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
994	softc->open_count = 0;
995
996	/*
997	 * Default to actually sending a SYNCHRONIZE CACHE command down to
998	 * the drive.
999	 */
1000	softc->flags = CTL_FLAG_REAL_SYNC;
1001
1002	/*
1003	 * In Copan's HA scheme, the "master" and "slave" roles are
1004	 * figured out through the slot the controller is in.  Although it
1005	 * is an active/active system, someone has to be in charge.
1006 	 */
1007#ifdef NEEDTOPORT
1008        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1009#endif
1010
1011        if (sc_id == 0) {
1012		softc->flags |= CTL_FLAG_MASTER_SHELF;
1013		persis_offset = 0;
1014	} else
1015		persis_offset = CTL_MAX_INITIATORS;
1016
1017	/*
1018	 * XXX KDM need to figure out where we want to get our target ID
1019	 * and WWID.  Is it different on each port?
1020	 */
1021	softc->target.id = 0;
1022	softc->target.wwid[0] = 0x12345678;
1023	softc->target.wwid[1] = 0x87654321;
1024	STAILQ_INIT(&softc->lun_list);
1025	STAILQ_INIT(&softc->pending_lun_queue);
1026	STAILQ_INIT(&softc->fe_list);
1027	STAILQ_INIT(&softc->port_list);
1028	STAILQ_INIT(&softc->be_list);
1029	STAILQ_INIT(&softc->io_pools);
1030	ctl_tpc_init(softc);
1031
1032	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1033			    &internal_pool)!= 0){
1034		printf("ctl: can't allocate %d entry internal pool, "
1035		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1036		return (ENOMEM);
1037	}
1038
1039	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1040			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1041		printf("ctl: can't allocate %d entry emergency pool, "
1042		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1043		ctl_pool_free(internal_pool);
1044		return (ENOMEM);
1045	}
1046
1047	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1048	                    &other_pool) != 0)
1049	{
1050		printf("ctl: can't allocate %d entry other SC pool, "
1051		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1052		ctl_pool_free(internal_pool);
1053		ctl_pool_free(emergency_pool);
1054		return (ENOMEM);
1055	}
1056
1057	softc->internal_pool = internal_pool;
1058	softc->emergency_pool = emergency_pool;
1059	softc->othersc_pool = other_pool;
1060
1061	if (worker_threads <= 0)
1062		worker_threads = max(1, mp_ncpus / 4);
1063	if (worker_threads > CTL_MAX_THREADS)
1064		worker_threads = CTL_MAX_THREADS;
1065
1066	for (i = 0; i < worker_threads; i++) {
1067		struct ctl_thread *thr = &softc->threads[i];
1068
1069		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1070		thr->ctl_softc = softc;
1071		STAILQ_INIT(&thr->incoming_queue);
1072		STAILQ_INIT(&thr->rtr_queue);
1073		STAILQ_INIT(&thr->done_queue);
1074		STAILQ_INIT(&thr->isc_queue);
1075
1076		error = kproc_kthread_add(ctl_work_thread, thr,
1077		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1078		if (error != 0) {
1079			printf("error creating CTL work thread!\n");
1080			ctl_pool_free(internal_pool);
1081			ctl_pool_free(emergency_pool);
1082			ctl_pool_free(other_pool);
1083			return (error);
1084		}
1085	}
1086	error = kproc_kthread_add(ctl_lun_thread, softc,
1087	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1088	if (error != 0) {
1089		printf("error creating CTL lun thread!\n");
1090		ctl_pool_free(internal_pool);
1091		ctl_pool_free(emergency_pool);
1092		ctl_pool_free(other_pool);
1093		return (error);
1094	}
1095	if (bootverbose)
1096		printf("ctl: CAM Target Layer loaded\n");
1097
1098	/*
1099	 * Initialize the ioctl front end.
1100	 */
1101	ctl_frontend_register(&ioctl_frontend);
1102	port = &softc->ioctl_info.port;
1103	port->frontend = &ioctl_frontend;
1104	sprintf(softc->ioctl_info.port_name, "ioctl");
1105	port->port_type = CTL_PORT_IOCTL;
1106	port->num_requested_ctl_io = 100;
1107	port->port_name = softc->ioctl_info.port_name;
1108	port->port_online = ctl_ioctl_online;
1109	port->port_offline = ctl_ioctl_offline;
1110	port->onoff_arg = &softc->ioctl_info;
1111	port->lun_enable = ctl_ioctl_lun_enable;
1112	port->lun_disable = ctl_ioctl_lun_disable;
1113	port->targ_lun_arg = &softc->ioctl_info;
1114	port->fe_datamove = ctl_ioctl_datamove;
1115	port->fe_done = ctl_ioctl_done;
1116	port->max_targets = 15;
1117	port->max_target_id = 15;
1118
1119	if (ctl_port_register(&softc->ioctl_info.port,
1120	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1121		printf("ctl: ioctl front end registration failed, will "
1122		       "continue anyway\n");
1123	}
1124
1125#ifdef CTL_IO_DELAY
1126	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1127		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1128		       sizeof(struct callout), CTL_TIMER_BYTES);
1129		return (EINVAL);
1130	}
1131#endif /* CTL_IO_DELAY */
1132
1133	return (0);
1134}
1135
1136void
1137ctl_shutdown(void)
1138{
1139	struct ctl_softc *softc;
1140	struct ctl_lun *lun, *next_lun;
1141	struct ctl_io_pool *pool;
1142
1143	softc = (struct ctl_softc *)control_softc;
1144
1145	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1146		printf("ctl: ioctl front end deregistration failed\n");
1147
1148	mtx_lock(&softc->ctl_lock);
1149
1150	/*
1151	 * Free up each LUN.
1152	 */
1153	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1154		next_lun = STAILQ_NEXT(lun, links);
1155		ctl_free_lun(lun);
1156	}
1157
1158	mtx_unlock(&softc->ctl_lock);
1159
1160	ctl_frontend_deregister(&ioctl_frontend);
1161
1162	/*
1163	 * This will rip the rug out from under any FETDs or anyone else
1164	 * that has a pool allocated.  Since we increment our module
1165	 * refcount any time someone outside the main CTL module allocates
1166	 * a pool, we shouldn't have any problems here.  The user won't be
1167	 * able to unload the CTL module until client modules have
1168	 * successfully unloaded.
1169	 */
1170	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1171		ctl_pool_free(pool);
1172
1173#if 0
1174	ctl_shutdown_thread(softc->work_thread);
1175	mtx_destroy(&softc->queue_lock);
1176#endif
1177
1178	ctl_tpc_shutdown(softc);
1179	mtx_destroy(&softc->pool_lock);
1180	mtx_destroy(&softc->ctl_lock);
1181
1182	destroy_dev(softc->dev);
1183
1184	sysctl_ctx_free(&softc->sysctl_ctx);
1185
1186	free(control_softc, M_DEVBUF);
1187	control_softc = NULL;
1188
1189	if (bootverbose)
1190		printf("ctl: CAM Target Layer unloaded\n");
1191}
1192
1193static int
1194ctl_module_event_handler(module_t mod, int what, void *arg)
1195{
1196
1197	switch (what) {
1198	case MOD_LOAD:
1199		return (ctl_init());
1200	case MOD_UNLOAD:
1201		return (EBUSY);
1202	default:
1203		return (EOPNOTSUPP);
1204	}
1205}
1206
1207/*
1208 * XXX KDM should we do some access checks here?  Bump a reference count to
1209 * prevent a CTL module from being unloaded while someone has it open?
1210 */
1211static int
1212ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1213{
1214	return (0);
1215}
1216
1217static int
1218ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1219{
1220	return (0);
1221}
1222
1223int
1224ctl_port_enable(ctl_port_type port_type)
1225{
1226	struct ctl_softc *softc;
1227	struct ctl_port *port;
1228
1229	if (ctl_is_single == 0) {
1230		union ctl_ha_msg msg_info;
1231		int isc_retval;
1232
1233#if 0
1234		printf("%s: HA mode, synchronizing frontend enable\n",
1235		        __func__);
1236#endif
1237		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1238	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1239		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1240			printf("Sync msg send error retval %d\n", isc_retval);
1241		}
1242		if (!rcv_sync_msg) {
1243			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1244			        sizeof(msg_info), 1);
1245		}
1246#if 0
1247        	printf("CTL:Frontend Enable\n");
1248	} else {
1249		printf("%s: single mode, skipping frontend synchronization\n",
1250		        __func__);
1251#endif
1252	}
1253
1254	softc = control_softc;
1255
1256	STAILQ_FOREACH(port, &softc->port_list, links) {
1257		if (port_type & port->port_type)
1258		{
1259#if 0
1260			printf("port %d\n", port->targ_port);
1261#endif
1262			ctl_port_online(port);
1263		}
1264	}
1265
1266	return (0);
1267}
1268
1269int
1270ctl_port_disable(ctl_port_type port_type)
1271{
1272	struct ctl_softc *softc;
1273	struct ctl_port *port;
1274
1275	softc = control_softc;
1276
1277	STAILQ_FOREACH(port, &softc->port_list, links) {
1278		if (port_type & port->port_type)
1279			ctl_port_offline(port);
1280	}
1281
1282	return (0);
1283}
1284
1285/*
1286 * Returns 0 for success, 1 for failure.
1287 * Currently the only failure mode is if there aren't enough entries
1288 * allocated.  So, in case of a failure, look at num_entries_dropped,
1289 * reallocate and try again.
1290 */
1291int
1292ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1293	      int *num_entries_filled, int *num_entries_dropped,
1294	      ctl_port_type port_type, int no_virtual)
1295{
1296	struct ctl_softc *softc;
1297	struct ctl_port *port;
1298	int entries_dropped, entries_filled;
1299	int retval;
1300	int i;
1301
1302	softc = control_softc;
1303
1304	retval = 0;
1305	entries_filled = 0;
1306	entries_dropped = 0;
1307
1308	i = 0;
1309	mtx_lock(&softc->ctl_lock);
1310	STAILQ_FOREACH(port, &softc->port_list, links) {
1311		struct ctl_port_entry *entry;
1312
1313		if ((port->port_type & port_type) == 0)
1314			continue;
1315
1316		if ((no_virtual != 0)
1317		 && (port->virtual_port != 0))
1318			continue;
1319
1320		if (entries_filled >= num_entries_alloced) {
1321			entries_dropped++;
1322			continue;
1323		}
1324		entry = &entries[i];
1325
1326		entry->port_type = port->port_type;
1327		strlcpy(entry->port_name, port->port_name,
1328			sizeof(entry->port_name));
1329		entry->physical_port = port->physical_port;
1330		entry->virtual_port = port->virtual_port;
1331		entry->wwnn = port->wwnn;
1332		entry->wwpn = port->wwpn;
1333
1334		i++;
1335		entries_filled++;
1336	}
1337
1338	mtx_unlock(&softc->ctl_lock);
1339
1340	if (entries_dropped > 0)
1341		retval = 1;
1342
1343	*num_entries_dropped = entries_dropped;
1344	*num_entries_filled = entries_filled;
1345
1346	return (retval);
1347}
1348
1349static void
1350ctl_ioctl_online(void *arg)
1351{
1352	struct ctl_ioctl_info *ioctl_info;
1353
1354	ioctl_info = (struct ctl_ioctl_info *)arg;
1355
1356	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1357}
1358
1359static void
1360ctl_ioctl_offline(void *arg)
1361{
1362	struct ctl_ioctl_info *ioctl_info;
1363
1364	ioctl_info = (struct ctl_ioctl_info *)arg;
1365
1366	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1367}
1368
1369/*
1370 * Remove an initiator by port number and initiator ID.
1371 * Returns 0 for success, -1 for failure.
1372 */
1373int
1374ctl_remove_initiator(struct ctl_port *port, int iid)
1375{
1376	struct ctl_softc *softc = control_softc;
1377
1378	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1379
1380	if (iid > CTL_MAX_INIT_PER_PORT) {
1381		printf("%s: initiator ID %u > maximun %u!\n",
1382		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1383		return (-1);
1384	}
1385
1386	mtx_lock(&softc->ctl_lock);
1387	port->wwpn_iid[iid].in_use--;
1388	port->wwpn_iid[iid].last_use = time_uptime;
1389	mtx_unlock(&softc->ctl_lock);
1390
1391	return (0);
1392}
1393
1394/*
1395 * Add an initiator to the initiator map.
1396 * Returns iid for success, < 0 for failure.
1397 */
1398int
1399ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1400{
1401	struct ctl_softc *softc = control_softc;
1402	time_t best_time;
1403	int i, best;
1404
1405	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1406
1407	if (iid >= CTL_MAX_INIT_PER_PORT) {
1408		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1409		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1410		free(name, M_CTL);
1411		return (-1);
1412	}
1413
1414	mtx_lock(&softc->ctl_lock);
1415
1416	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1417		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1418			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1419				iid = i;
1420				break;
1421			}
1422			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1423			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1424				iid = i;
1425				break;
1426			}
1427		}
1428	}
1429
1430	if (iid < 0) {
1431		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1432			if (port->wwpn_iid[i].in_use == 0 &&
1433			    port->wwpn_iid[i].wwpn == 0 &&
1434			    port->wwpn_iid[i].name == NULL) {
1435				iid = i;
1436				break;
1437			}
1438		}
1439	}
1440
1441	if (iid < 0) {
1442		best = -1;
1443		best_time = INT32_MAX;
1444		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1445			if (port->wwpn_iid[i].in_use == 0) {
1446				if (port->wwpn_iid[i].last_use < best_time) {
1447					best = i;
1448					best_time = port->wwpn_iid[i].last_use;
1449				}
1450			}
1451		}
1452		iid = best;
1453	}
1454
1455	if (iid < 0) {
1456		mtx_unlock(&softc->ctl_lock);
1457		free(name, M_CTL);
1458		return (-2);
1459	}
1460
1461	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1462		/*
1463		 * This is not an error yet.
1464		 */
1465		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1466#if 0
1467			printf("%s: port %d iid %u WWPN %#jx arrived"
1468			    " again\n", __func__, port->targ_port,
1469			    iid, (uintmax_t)wwpn);
1470#endif
1471			goto take;
1472		}
1473		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1474		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1475#if 0
1476			printf("%s: port %d iid %u name '%s' arrived"
1477			    " again\n", __func__, port->targ_port,
1478			    iid, name);
1479#endif
1480			goto take;
1481		}
1482
1483		/*
1484		 * This is an error, but what do we do about it?  The
1485		 * driver is telling us we have a new WWPN for this
1486		 * initiator ID, so we pretty much need to use it.
1487		 */
1488		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1489		    " but WWPN %#jx '%s' is still at that address\n",
1490		    __func__, port->targ_port, iid, wwpn, name,
1491		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1492		    port->wwpn_iid[iid].name);
1493
1494		/*
1495		 * XXX KDM clear have_ca and ua_pending on each LUN for
1496		 * this initiator.
1497		 */
1498	}
1499take:
1500	free(port->wwpn_iid[iid].name, M_CTL);
1501	port->wwpn_iid[iid].name = name;
1502	port->wwpn_iid[iid].wwpn = wwpn;
1503	port->wwpn_iid[iid].in_use++;
1504	mtx_unlock(&softc->ctl_lock);
1505
1506	return (iid);
1507}
1508
1509static int
1510ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1511{
1512	int len;
1513
1514	switch (port->port_type) {
1515	case CTL_PORT_FC:
1516	{
1517		struct scsi_transportid_fcp *id =
1518		    (struct scsi_transportid_fcp *)buf;
1519		if (port->wwpn_iid[iid].wwpn == 0)
1520			return (0);
1521		memset(id, 0, sizeof(*id));
1522		id->format_protocol = SCSI_PROTO_FC;
1523		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1524		return (sizeof(*id));
1525	}
1526	case CTL_PORT_ISCSI:
1527	{
1528		struct scsi_transportid_iscsi_port *id =
1529		    (struct scsi_transportid_iscsi_port *)buf;
1530		if (port->wwpn_iid[iid].name == NULL)
1531			return (0);
1532		memset(id, 0, 256);
1533		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1534		    SCSI_PROTO_ISCSI;
1535		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1536		len = roundup2(min(len, 252), 4);
1537		scsi_ulto2b(len, id->additional_length);
1538		return (sizeof(*id) + len);
1539	}
1540	case CTL_PORT_SAS:
1541	{
1542		struct scsi_transportid_sas *id =
1543		    (struct scsi_transportid_sas *)buf;
1544		if (port->wwpn_iid[iid].wwpn == 0)
1545			return (0);
1546		memset(id, 0, sizeof(*id));
1547		id->format_protocol = SCSI_PROTO_SAS;
1548		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1549		return (sizeof(*id));
1550	}
1551	default:
1552	{
1553		struct scsi_transportid_spi *id =
1554		    (struct scsi_transportid_spi *)buf;
1555		memset(id, 0, sizeof(*id));
1556		id->format_protocol = SCSI_PROTO_SPI;
1557		scsi_ulto2b(iid, id->scsi_addr);
1558		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1559		return (sizeof(*id));
1560	}
1561	}
1562}
1563
1564static int
1565ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1566{
1567	return (0);
1568}
1569
1570static int
1571ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1572{
1573	return (0);
1574}
1575
1576/*
1577 * Data movement routine for the CTL ioctl frontend port.
1578 */
1579static int
1580ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1581{
1582	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1583	struct ctl_sg_entry ext_entry, kern_entry;
1584	int ext_sglen, ext_sg_entries, kern_sg_entries;
1585	int ext_sg_start, ext_offset;
1586	int len_to_copy, len_copied;
1587	int kern_watermark, ext_watermark;
1588	int ext_sglist_malloced;
1589	int i, j;
1590
1591	ext_sglist_malloced = 0;
1592	ext_sg_start = 0;
1593	ext_offset = 0;
1594
1595	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1596
1597	/*
1598	 * If this flag is set, fake the data transfer.
1599	 */
1600	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1601		ctsio->ext_data_filled = ctsio->ext_data_len;
1602		goto bailout;
1603	}
1604
1605	/*
1606	 * To simplify things here, if we have a single buffer, stick it in
1607	 * a S/G entry and just make it a single entry S/G list.
1608	 */
1609	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1610		int len_seen;
1611
1612		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1613
1614		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1615							   M_WAITOK);
1616		ext_sglist_malloced = 1;
1617		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1618				   ext_sglen) != 0) {
1619			ctl_set_internal_failure(ctsio,
1620						 /*sks_valid*/ 0,
1621						 /*retry_count*/ 0);
1622			goto bailout;
1623		}
1624		ext_sg_entries = ctsio->ext_sg_entries;
1625		len_seen = 0;
1626		for (i = 0; i < ext_sg_entries; i++) {
1627			if ((len_seen + ext_sglist[i].len) >=
1628			     ctsio->ext_data_filled) {
1629				ext_sg_start = i;
1630				ext_offset = ctsio->ext_data_filled - len_seen;
1631				break;
1632			}
1633			len_seen += ext_sglist[i].len;
1634		}
1635	} else {
1636		ext_sglist = &ext_entry;
1637		ext_sglist->addr = ctsio->ext_data_ptr;
1638		ext_sglist->len = ctsio->ext_data_len;
1639		ext_sg_entries = 1;
1640		ext_sg_start = 0;
1641		ext_offset = ctsio->ext_data_filled;
1642	}
1643
1644	if (ctsio->kern_sg_entries > 0) {
1645		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1646		kern_sg_entries = ctsio->kern_sg_entries;
1647	} else {
1648		kern_sglist = &kern_entry;
1649		kern_sglist->addr = ctsio->kern_data_ptr;
1650		kern_sglist->len = ctsio->kern_data_len;
1651		kern_sg_entries = 1;
1652	}
1653
1654
1655	kern_watermark = 0;
1656	ext_watermark = ext_offset;
1657	len_copied = 0;
1658	for (i = ext_sg_start, j = 0;
1659	     i < ext_sg_entries && j < kern_sg_entries;) {
1660		uint8_t *ext_ptr, *kern_ptr;
1661
1662		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1663				      kern_sglist[j].len - kern_watermark);
1664
1665		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1666		ext_ptr = ext_ptr + ext_watermark;
1667		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1668			/*
1669			 * XXX KDM fix this!
1670			 */
1671			panic("need to implement bus address support");
1672#if 0
1673			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1674#endif
1675		} else
1676			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1677		kern_ptr = kern_ptr + kern_watermark;
1678
1679		kern_watermark += len_to_copy;
1680		ext_watermark += len_to_copy;
1681
1682		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1683		     CTL_FLAG_DATA_IN) {
1684			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1685					 "bytes to user\n", len_to_copy));
1686			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1687					 "to %p\n", kern_ptr, ext_ptr));
1688			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1689				ctl_set_internal_failure(ctsio,
1690							 /*sks_valid*/ 0,
1691							 /*retry_count*/ 0);
1692				goto bailout;
1693			}
1694		} else {
1695			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1696					 "bytes from user\n", len_to_copy));
1697			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1698					 "to %p\n", ext_ptr, kern_ptr));
1699			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1700				ctl_set_internal_failure(ctsio,
1701							 /*sks_valid*/ 0,
1702							 /*retry_count*/0);
1703				goto bailout;
1704			}
1705		}
1706
1707		len_copied += len_to_copy;
1708
1709		if (ext_sglist[i].len == ext_watermark) {
1710			i++;
1711			ext_watermark = 0;
1712		}
1713
1714		if (kern_sglist[j].len == kern_watermark) {
1715			j++;
1716			kern_watermark = 0;
1717		}
1718	}
1719
1720	ctsio->ext_data_filled += len_copied;
1721
1722	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1723			 "kern_sg_entries: %d\n", ext_sg_entries,
1724			 kern_sg_entries));
1725	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1726			 "kern_data_len = %d\n", ctsio->ext_data_len,
1727			 ctsio->kern_data_len));
1728
1729
1730	/* XXX KDM set residual?? */
1731bailout:
1732
1733	if (ext_sglist_malloced != 0)
1734		free(ext_sglist, M_CTL);
1735
1736	return (CTL_RETVAL_COMPLETE);
1737}
1738
1739/*
1740 * Serialize a command that went down the "wrong" side, and so was sent to
1741 * this controller for execution.  The logic is a little different than the
1742 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1743 * sent back to the other side, but in the success case, we execute the
1744 * command on this side (XFER mode) or tell the other side to execute it
1745 * (SER_ONLY mode).
1746 */
1747static int
1748ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1749{
1750	struct ctl_softc *ctl_softc;
1751	union ctl_ha_msg msg_info;
1752	struct ctl_lun *lun;
1753	int retval = 0;
1754	uint32_t targ_lun;
1755
1756	ctl_softc = control_softc;
1757
1758	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1759	lun = ctl_softc->ctl_luns[targ_lun];
1760	if (lun==NULL)
1761	{
1762		/*
1763		 * Why isn't LUN defined? The other side wouldn't
1764		 * send a cmd if the LUN is undefined.
1765		 */
1766		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1767
1768		/* "Logical unit not supported" */
1769		ctl_set_sense_data(&msg_info.scsi.sense_data,
1770				   lun,
1771				   /*sense_format*/SSD_TYPE_NONE,
1772				   /*current_error*/ 1,
1773				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1774				   /*asc*/ 0x25,
1775				   /*ascq*/ 0x00,
1776				   SSD_ELEM_NONE);
1777
1778		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1779		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1780		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1781		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1782		msg_info.hdr.serializing_sc = NULL;
1783		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1784	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1785				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1786		}
1787		return(1);
1788
1789	}
1790
1791	mtx_lock(&lun->lun_lock);
1792    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1793
1794	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1795		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1796		 ooa_links))) {
1797	case CTL_ACTION_BLOCK:
1798		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1799		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1800				  blocked_links);
1801		break;
1802	case CTL_ACTION_PASS:
1803	case CTL_ACTION_SKIP:
1804		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1805			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1806			ctl_enqueue_rtr((union ctl_io *)ctsio);
1807		} else {
1808
1809			/* send msg back to other side */
1810			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1811			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1812			msg_info.hdr.msg_type = CTL_MSG_R2R;
1813#if 0
1814			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1815#endif
1816		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1817			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1818			}
1819		}
1820		break;
1821	case CTL_ACTION_OVERLAP:
1822		/* OVERLAPPED COMMANDS ATTEMPTED */
1823		ctl_set_sense_data(&msg_info.scsi.sense_data,
1824				   lun,
1825				   /*sense_format*/SSD_TYPE_NONE,
1826				   /*current_error*/ 1,
1827				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1828				   /*asc*/ 0x4E,
1829				   /*ascq*/ 0x00,
1830				   SSD_ELEM_NONE);
1831
1832		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1833		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1834		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1835		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1836		msg_info.hdr.serializing_sc = NULL;
1837		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1838#if 0
1839		printf("BAD JUJU:Major Bummer Overlap\n");
1840#endif
1841		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1842		retval = 1;
1843		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1844		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1845		}
1846		break;
1847	case CTL_ACTION_OVERLAP_TAG:
1848		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1849		ctl_set_sense_data(&msg_info.scsi.sense_data,
1850				   lun,
1851				   /*sense_format*/SSD_TYPE_NONE,
1852				   /*current_error*/ 1,
1853				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854				   /*asc*/ 0x4D,
1855				   /*ascq*/ ctsio->tag_num & 0xff,
1856				   SSD_ELEM_NONE);
1857
1858		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862		msg_info.hdr.serializing_sc = NULL;
1863		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864#if 0
1865		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1866#endif
1867		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868		retval = 1;
1869		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871		}
1872		break;
1873	case CTL_ACTION_ERROR:
1874	default:
1875		/* "Internal target failure" */
1876		ctl_set_sense_data(&msg_info.scsi.sense_data,
1877				   lun,
1878				   /*sense_format*/SSD_TYPE_NONE,
1879				   /*current_error*/ 1,
1880				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1881				   /*asc*/ 0x44,
1882				   /*ascq*/ 0x00,
1883				   SSD_ELEM_NONE);
1884
1885		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1886		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1887		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1888		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1889		msg_info.hdr.serializing_sc = NULL;
1890		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1891#if 0
1892		printf("BAD JUJU:Major Bummer HW Error\n");
1893#endif
1894		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1895		retval = 1;
1896		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1897		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1898		}
1899		break;
1900	}
1901	mtx_unlock(&lun->lun_lock);
1902	return (retval);
1903}
1904
1905static int
1906ctl_ioctl_submit_wait(union ctl_io *io)
1907{
1908	struct ctl_fe_ioctl_params params;
1909	ctl_fe_ioctl_state last_state;
1910	int done, retval;
1911
1912	retval = 0;
1913
1914	bzero(&params, sizeof(params));
1915
1916	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1917	cv_init(&params.sem, "ctlioccv");
1918	params.state = CTL_IOCTL_INPROG;
1919	last_state = params.state;
1920
1921	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1922
1923	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1924
1925	/* This shouldn't happen */
1926	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1927		return (retval);
1928
1929	done = 0;
1930
1931	do {
1932		mtx_lock(&params.ioctl_mtx);
1933		/*
1934		 * Check the state here, and don't sleep if the state has
1935		 * already changed (i.e. wakeup has already occured, but we
1936		 * weren't waiting yet).
1937		 */
1938		if (params.state == last_state) {
1939			/* XXX KDM cv_wait_sig instead? */
1940			cv_wait(&params.sem, &params.ioctl_mtx);
1941		}
1942		last_state = params.state;
1943
1944		switch (params.state) {
1945		case CTL_IOCTL_INPROG:
1946			/* Why did we wake up? */
1947			/* XXX KDM error here? */
1948			mtx_unlock(&params.ioctl_mtx);
1949			break;
1950		case CTL_IOCTL_DATAMOVE:
1951			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1952
1953			/*
1954			 * change last_state back to INPROG to avoid
1955			 * deadlock on subsequent data moves.
1956			 */
1957			params.state = last_state = CTL_IOCTL_INPROG;
1958
1959			mtx_unlock(&params.ioctl_mtx);
1960			ctl_ioctl_do_datamove(&io->scsiio);
1961			/*
1962			 * Note that in some cases, most notably writes,
1963			 * this will queue the I/O and call us back later.
1964			 * In other cases, generally reads, this routine
1965			 * will immediately call back and wake us up,
1966			 * probably using our own context.
1967			 */
1968			io->scsiio.be_move_done(io);
1969			break;
1970		case CTL_IOCTL_DONE:
1971			mtx_unlock(&params.ioctl_mtx);
1972			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1973			done = 1;
1974			break;
1975		default:
1976			mtx_unlock(&params.ioctl_mtx);
1977			/* XXX KDM error here? */
1978			break;
1979		}
1980	} while (done == 0);
1981
1982	mtx_destroy(&params.ioctl_mtx);
1983	cv_destroy(&params.sem);
1984
1985	return (CTL_RETVAL_COMPLETE);
1986}
1987
1988static void
1989ctl_ioctl_datamove(union ctl_io *io)
1990{
1991	struct ctl_fe_ioctl_params *params;
1992
1993	params = (struct ctl_fe_ioctl_params *)
1994		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1995
1996	mtx_lock(&params->ioctl_mtx);
1997	params->state = CTL_IOCTL_DATAMOVE;
1998	cv_broadcast(&params->sem);
1999	mtx_unlock(&params->ioctl_mtx);
2000}
2001
2002static void
2003ctl_ioctl_done(union ctl_io *io)
2004{
2005	struct ctl_fe_ioctl_params *params;
2006
2007	params = (struct ctl_fe_ioctl_params *)
2008		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2009
2010	mtx_lock(&params->ioctl_mtx);
2011	params->state = CTL_IOCTL_DONE;
2012	cv_broadcast(&params->sem);
2013	mtx_unlock(&params->ioctl_mtx);
2014}
2015
2016static void
2017ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2018{
2019	struct ctl_fe_ioctl_startstop_info *sd_info;
2020
2021	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2022
2023	sd_info->hs_info.status = metatask->status;
2024	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2025	sd_info->hs_info.luns_complete =
2026		metatask->taskinfo.startstop.luns_complete;
2027	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2028
2029	cv_broadcast(&sd_info->sem);
2030}
2031
2032static void
2033ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2034{
2035	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2036
2037	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2038
2039	mtx_lock(fe_bbr_info->lock);
2040	fe_bbr_info->bbr_info->status = metatask->status;
2041	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2042	fe_bbr_info->wakeup_done = 1;
2043	mtx_unlock(fe_bbr_info->lock);
2044
2045	cv_broadcast(&fe_bbr_info->sem);
2046}
2047
2048/*
2049 * Returns 0 for success, errno for failure.
2050 */
2051static int
2052ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2053		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2054{
2055	union ctl_io *io;
2056	int retval;
2057
2058	retval = 0;
2059
2060	mtx_lock(&lun->lun_lock);
2061	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2062	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2063	     ooa_links)) {
2064		struct ctl_ooa_entry *entry;
2065
2066		/*
2067		 * If we've got more than we can fit, just count the
2068		 * remaining entries.
2069		 */
2070		if (*cur_fill_num >= ooa_hdr->alloc_num)
2071			continue;
2072
2073		entry = &kern_entries[*cur_fill_num];
2074
2075		entry->tag_num = io->scsiio.tag_num;
2076		entry->lun_num = lun->lun;
2077#ifdef CTL_TIME_IO
2078		entry->start_bt = io->io_hdr.start_bt;
2079#endif
2080		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2081		entry->cdb_len = io->scsiio.cdb_len;
2082		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2083			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2084
2085		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2086			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2087
2088		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2089			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2090
2091		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2092			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2093
2094		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2095			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2096	}
2097	mtx_unlock(&lun->lun_lock);
2098
2099	return (retval);
2100}
2101
2102static void *
2103ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2104		 size_t error_str_len)
2105{
2106	void *kptr;
2107
2108	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2109
2110	if (copyin(user_addr, kptr, len) != 0) {
2111		snprintf(error_str, error_str_len, "Error copying %d bytes "
2112			 "from user address %p to kernel address %p", len,
2113			 user_addr, kptr);
2114		free(kptr, M_CTL);
2115		return (NULL);
2116	}
2117
2118	return (kptr);
2119}
2120
2121static void
2122ctl_free_args(int num_args, struct ctl_be_arg *args)
2123{
2124	int i;
2125
2126	if (args == NULL)
2127		return;
2128
2129	for (i = 0; i < num_args; i++) {
2130		free(args[i].kname, M_CTL);
2131		free(args[i].kvalue, M_CTL);
2132	}
2133
2134	free(args, M_CTL);
2135}
2136
2137static struct ctl_be_arg *
2138ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2139		char *error_str, size_t error_str_len)
2140{
2141	struct ctl_be_arg *args;
2142	int i;
2143
2144	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2145				error_str, error_str_len);
2146
2147	if (args == NULL)
2148		goto bailout;
2149
2150	for (i = 0; i < num_args; i++) {
2151		args[i].kname = NULL;
2152		args[i].kvalue = NULL;
2153	}
2154
2155	for (i = 0; i < num_args; i++) {
2156		uint8_t *tmpptr;
2157
2158		args[i].kname = ctl_copyin_alloc(args[i].name,
2159			args[i].namelen, error_str, error_str_len);
2160		if (args[i].kname == NULL)
2161			goto bailout;
2162
2163		if (args[i].kname[args[i].namelen - 1] != '\0') {
2164			snprintf(error_str, error_str_len, "Argument %d "
2165				 "name is not NUL-terminated", i);
2166			goto bailout;
2167		}
2168
2169		if (args[i].flags & CTL_BEARG_RD) {
2170			tmpptr = ctl_copyin_alloc(args[i].value,
2171				args[i].vallen, error_str, error_str_len);
2172			if (tmpptr == NULL)
2173				goto bailout;
2174			if ((args[i].flags & CTL_BEARG_ASCII)
2175			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2176				snprintf(error_str, error_str_len, "Argument "
2177				    "%d value is not NUL-terminated", i);
2178				goto bailout;
2179			}
2180			args[i].kvalue = tmpptr;
2181		} else {
2182			args[i].kvalue = malloc(args[i].vallen,
2183			    M_CTL, M_WAITOK | M_ZERO);
2184		}
2185	}
2186
2187	return (args);
2188bailout:
2189
2190	ctl_free_args(num_args, args);
2191
2192	return (NULL);
2193}
2194
2195static void
2196ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2197{
2198	int i;
2199
2200	for (i = 0; i < num_args; i++) {
2201		if (args[i].flags & CTL_BEARG_WR)
2202			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2203	}
2204}
2205
2206/*
2207 * Escape characters that are illegal or not recommended in XML.
2208 */
2209int
2210ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2211{
2212	int retval;
2213
2214	retval = 0;
2215
2216	for (; *str; str++) {
2217		switch (*str) {
2218		case '&':
2219			retval = sbuf_printf(sb, "&amp;");
2220			break;
2221		case '>':
2222			retval = sbuf_printf(sb, "&gt;");
2223			break;
2224		case '<':
2225			retval = sbuf_printf(sb, "&lt;");
2226			break;
2227		default:
2228			retval = sbuf_putc(sb, *str);
2229			break;
2230		}
2231
2232		if (retval != 0)
2233			break;
2234
2235	}
2236
2237	return (retval);
2238}
2239
2240static int
2241ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2242	  struct thread *td)
2243{
2244	struct ctl_softc *softc;
2245	int retval;
2246
2247	softc = control_softc;
2248
2249	retval = 0;
2250
2251	switch (cmd) {
2252	case CTL_IO: {
2253		union ctl_io *io;
2254		void *pool_tmp;
2255
2256		/*
2257		 * If we haven't been "enabled", don't allow any SCSI I/O
2258		 * to this FETD.
2259		 */
2260		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2261			retval = EPERM;
2262			break;
2263		}
2264
2265		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2266		if (io == NULL) {
2267			printf("ctl_ioctl: can't allocate ctl_io!\n");
2268			retval = ENOSPC;
2269			break;
2270		}
2271
2272		/*
2273		 * Need to save the pool reference so it doesn't get
2274		 * spammed by the user's ctl_io.
2275		 */
2276		pool_tmp = io->io_hdr.pool;
2277
2278		memcpy(io, (void *)addr, sizeof(*io));
2279
2280		io->io_hdr.pool = pool_tmp;
2281		/*
2282		 * No status yet, so make sure the status is set properly.
2283		 */
2284		io->io_hdr.status = CTL_STATUS_NONE;
2285
2286		/*
2287		 * The user sets the initiator ID, target and LUN IDs.
2288		 */
2289		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2290		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2291		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2292		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2293			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2294
2295		retval = ctl_ioctl_submit_wait(io);
2296
2297		if (retval != 0) {
2298			ctl_free_io(io);
2299			break;
2300		}
2301
2302		memcpy((void *)addr, io, sizeof(*io));
2303
2304		/* return this to our pool */
2305		ctl_free_io(io);
2306
2307		break;
2308	}
2309	case CTL_ENABLE_PORT:
2310	case CTL_DISABLE_PORT:
2311	case CTL_SET_PORT_WWNS: {
2312		struct ctl_port *port;
2313		struct ctl_port_entry *entry;
2314
2315		entry = (struct ctl_port_entry *)addr;
2316
2317		mtx_lock(&softc->ctl_lock);
2318		STAILQ_FOREACH(port, &softc->port_list, links) {
2319			int action, done;
2320
2321			action = 0;
2322			done = 0;
2323
2324			if ((entry->port_type == CTL_PORT_NONE)
2325			 && (entry->targ_port == port->targ_port)) {
2326				/*
2327				 * If the user only wants to enable or
2328				 * disable or set WWNs on a specific port,
2329				 * do the operation and we're done.
2330				 */
2331				action = 1;
2332				done = 1;
2333			} else if (entry->port_type & port->port_type) {
2334				/*
2335				 * Compare the user's type mask with the
2336				 * particular frontend type to see if we
2337				 * have a match.
2338				 */
2339				action = 1;
2340				done = 0;
2341
2342				/*
2343				 * Make sure the user isn't trying to set
2344				 * WWNs on multiple ports at the same time.
2345				 */
2346				if (cmd == CTL_SET_PORT_WWNS) {
2347					printf("%s: Can't set WWNs on "
2348					       "multiple ports\n", __func__);
2349					retval = EINVAL;
2350					break;
2351				}
2352			}
2353			if (action != 0) {
2354				/*
2355				 * XXX KDM we have to drop the lock here,
2356				 * because the online/offline operations
2357				 * can potentially block.  We need to
2358				 * reference count the frontends so they
2359				 * can't go away,
2360				 */
2361				mtx_unlock(&softc->ctl_lock);
2362
2363				if (cmd == CTL_ENABLE_PORT) {
2364					struct ctl_lun *lun;
2365
2366					STAILQ_FOREACH(lun, &softc->lun_list,
2367						       links) {
2368						port->lun_enable(port->targ_lun_arg,
2369						    lun->target,
2370						    lun->lun);
2371					}
2372
2373					ctl_port_online(port);
2374				} else if (cmd == CTL_DISABLE_PORT) {
2375					struct ctl_lun *lun;
2376
2377					ctl_port_offline(port);
2378
2379					STAILQ_FOREACH(lun, &softc->lun_list,
2380						       links) {
2381						port->lun_disable(
2382						    port->targ_lun_arg,
2383						    lun->target,
2384						    lun->lun);
2385					}
2386				}
2387
2388				mtx_lock(&softc->ctl_lock);
2389
2390				if (cmd == CTL_SET_PORT_WWNS)
2391					ctl_port_set_wwns(port,
2392					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2393					    1 : 0, entry->wwnn,
2394					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2395					    1 : 0, entry->wwpn);
2396			}
2397			if (done != 0)
2398				break;
2399		}
2400		mtx_unlock(&softc->ctl_lock);
2401		break;
2402	}
2403	case CTL_GET_PORT_LIST: {
2404		struct ctl_port *port;
2405		struct ctl_port_list *list;
2406		int i;
2407
2408		list = (struct ctl_port_list *)addr;
2409
2410		if (list->alloc_len != (list->alloc_num *
2411		    sizeof(struct ctl_port_entry))) {
2412			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2413			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2414			       "%zu\n", __func__, list->alloc_len,
2415			       list->alloc_num, sizeof(struct ctl_port_entry));
2416			retval = EINVAL;
2417			break;
2418		}
2419		list->fill_len = 0;
2420		list->fill_num = 0;
2421		list->dropped_num = 0;
2422		i = 0;
2423		mtx_lock(&softc->ctl_lock);
2424		STAILQ_FOREACH(port, &softc->port_list, links) {
2425			struct ctl_port_entry entry, *list_entry;
2426
2427			if (list->fill_num >= list->alloc_num) {
2428				list->dropped_num++;
2429				continue;
2430			}
2431
2432			entry.port_type = port->port_type;
2433			strlcpy(entry.port_name, port->port_name,
2434				sizeof(entry.port_name));
2435			entry.targ_port = port->targ_port;
2436			entry.physical_port = port->physical_port;
2437			entry.virtual_port = port->virtual_port;
2438			entry.wwnn = port->wwnn;
2439			entry.wwpn = port->wwpn;
2440			if (port->status & CTL_PORT_STATUS_ONLINE)
2441				entry.online = 1;
2442			else
2443				entry.online = 0;
2444
2445			list_entry = &list->entries[i];
2446
2447			retval = copyout(&entry, list_entry, sizeof(entry));
2448			if (retval != 0) {
2449				printf("%s: CTL_GET_PORT_LIST: copyout "
2450				       "returned %d\n", __func__, retval);
2451				break;
2452			}
2453			i++;
2454			list->fill_num++;
2455			list->fill_len += sizeof(entry);
2456		}
2457		mtx_unlock(&softc->ctl_lock);
2458
2459		/*
2460		 * If this is non-zero, we had a copyout fault, so there's
2461		 * probably no point in attempting to set the status inside
2462		 * the structure.
2463		 */
2464		if (retval != 0)
2465			break;
2466
2467		if (list->dropped_num > 0)
2468			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2469		else
2470			list->status = CTL_PORT_LIST_OK;
2471		break;
2472	}
2473	case CTL_DUMP_OOA: {
2474		struct ctl_lun *lun;
2475		union ctl_io *io;
2476		char printbuf[128];
2477		struct sbuf sb;
2478
2479		mtx_lock(&softc->ctl_lock);
2480		printf("Dumping OOA queues:\n");
2481		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2482			mtx_lock(&lun->lun_lock);
2483			for (io = (union ctl_io *)TAILQ_FIRST(
2484			     &lun->ooa_queue); io != NULL;
2485			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2486			     ooa_links)) {
2487				sbuf_new(&sb, printbuf, sizeof(printbuf),
2488					 SBUF_FIXEDLEN);
2489				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2490					    (intmax_t)lun->lun,
2491					    io->scsiio.tag_num,
2492					    (io->io_hdr.flags &
2493					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2494					    (io->io_hdr.flags &
2495					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2496					    (io->io_hdr.flags &
2497					    CTL_FLAG_ABORT) ? " ABORT" : "",
2498			                    (io->io_hdr.flags &
2499		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2500				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2501				sbuf_finish(&sb);
2502				printf("%s\n", sbuf_data(&sb));
2503			}
2504			mtx_unlock(&lun->lun_lock);
2505		}
2506		printf("OOA queues dump done\n");
2507		mtx_unlock(&softc->ctl_lock);
2508		break;
2509	}
2510	case CTL_GET_OOA: {
2511		struct ctl_lun *lun;
2512		struct ctl_ooa *ooa_hdr;
2513		struct ctl_ooa_entry *entries;
2514		uint32_t cur_fill_num;
2515
2516		ooa_hdr = (struct ctl_ooa *)addr;
2517
2518		if ((ooa_hdr->alloc_len == 0)
2519		 || (ooa_hdr->alloc_num == 0)) {
2520			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2521			       "must be non-zero\n", __func__,
2522			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2523			retval = EINVAL;
2524			break;
2525		}
2526
2527		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2528		    sizeof(struct ctl_ooa_entry))) {
2529			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2530			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2531			       __func__, ooa_hdr->alloc_len,
2532			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2533			retval = EINVAL;
2534			break;
2535		}
2536
2537		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2538		if (entries == NULL) {
2539			printf("%s: could not allocate %d bytes for OOA "
2540			       "dump\n", __func__, ooa_hdr->alloc_len);
2541			retval = ENOMEM;
2542			break;
2543		}
2544
2545		mtx_lock(&softc->ctl_lock);
2546		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2547		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2548		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2549			mtx_unlock(&softc->ctl_lock);
2550			free(entries, M_CTL);
2551			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2552			       __func__, (uintmax_t)ooa_hdr->lun_num);
2553			retval = EINVAL;
2554			break;
2555		}
2556
2557		cur_fill_num = 0;
2558
2559		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2560			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2561				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2562					ooa_hdr, entries);
2563				if (retval != 0)
2564					break;
2565			}
2566			if (retval != 0) {
2567				mtx_unlock(&softc->ctl_lock);
2568				free(entries, M_CTL);
2569				break;
2570			}
2571		} else {
2572			lun = softc->ctl_luns[ooa_hdr->lun_num];
2573
2574			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2575						    entries);
2576		}
2577		mtx_unlock(&softc->ctl_lock);
2578
2579		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2580		ooa_hdr->fill_len = ooa_hdr->fill_num *
2581			sizeof(struct ctl_ooa_entry);
2582		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2583		if (retval != 0) {
2584			printf("%s: error copying out %d bytes for OOA dump\n",
2585			       __func__, ooa_hdr->fill_len);
2586		}
2587
2588		getbintime(&ooa_hdr->cur_bt);
2589
2590		if (cur_fill_num > ooa_hdr->alloc_num) {
2591			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2592			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2593		} else {
2594			ooa_hdr->dropped_num = 0;
2595			ooa_hdr->status = CTL_OOA_OK;
2596		}
2597
2598		free(entries, M_CTL);
2599		break;
2600	}
2601	case CTL_CHECK_OOA: {
2602		union ctl_io *io;
2603		struct ctl_lun *lun;
2604		struct ctl_ooa_info *ooa_info;
2605
2606
2607		ooa_info = (struct ctl_ooa_info *)addr;
2608
2609		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2610			ooa_info->status = CTL_OOA_INVALID_LUN;
2611			break;
2612		}
2613		mtx_lock(&softc->ctl_lock);
2614		lun = softc->ctl_luns[ooa_info->lun_id];
2615		if (lun == NULL) {
2616			mtx_unlock(&softc->ctl_lock);
2617			ooa_info->status = CTL_OOA_INVALID_LUN;
2618			break;
2619		}
2620		mtx_lock(&lun->lun_lock);
2621		mtx_unlock(&softc->ctl_lock);
2622		ooa_info->num_entries = 0;
2623		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2624		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2625		     &io->io_hdr, ooa_links)) {
2626			ooa_info->num_entries++;
2627		}
2628		mtx_unlock(&lun->lun_lock);
2629
2630		ooa_info->status = CTL_OOA_SUCCESS;
2631
2632		break;
2633	}
2634	case CTL_HARD_START:
2635	case CTL_HARD_STOP: {
2636		struct ctl_fe_ioctl_startstop_info ss_info;
2637		struct cfi_metatask *metatask;
2638		struct mtx hs_mtx;
2639
2640		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2641
2642		cv_init(&ss_info.sem, "hard start/stop cv" );
2643
2644		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2645		if (metatask == NULL) {
2646			retval = ENOMEM;
2647			mtx_destroy(&hs_mtx);
2648			break;
2649		}
2650
2651		if (cmd == CTL_HARD_START)
2652			metatask->tasktype = CFI_TASK_STARTUP;
2653		else
2654			metatask->tasktype = CFI_TASK_SHUTDOWN;
2655
2656		metatask->callback = ctl_ioctl_hard_startstop_callback;
2657		metatask->callback_arg = &ss_info;
2658
2659		cfi_action(metatask);
2660
2661		/* Wait for the callback */
2662		mtx_lock(&hs_mtx);
2663		cv_wait_sig(&ss_info.sem, &hs_mtx);
2664		mtx_unlock(&hs_mtx);
2665
2666		/*
2667		 * All information has been copied from the metatask by the
2668		 * time cv_broadcast() is called, so we free the metatask here.
2669		 */
2670		cfi_free_metatask(metatask);
2671
2672		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2673
2674		mtx_destroy(&hs_mtx);
2675		break;
2676	}
2677	case CTL_BBRREAD: {
2678		struct ctl_bbrread_info *bbr_info;
2679		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2680		struct mtx bbr_mtx;
2681		struct cfi_metatask *metatask;
2682
2683		bbr_info = (struct ctl_bbrread_info *)addr;
2684
2685		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2686
2687		bzero(&bbr_mtx, sizeof(bbr_mtx));
2688		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2689
2690		fe_bbr_info.bbr_info = bbr_info;
2691		fe_bbr_info.lock = &bbr_mtx;
2692
2693		cv_init(&fe_bbr_info.sem, "BBR read cv");
2694		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2695
2696		if (metatask == NULL) {
2697			mtx_destroy(&bbr_mtx);
2698			cv_destroy(&fe_bbr_info.sem);
2699			retval = ENOMEM;
2700			break;
2701		}
2702		metatask->tasktype = CFI_TASK_BBRREAD;
2703		metatask->callback = ctl_ioctl_bbrread_callback;
2704		metatask->callback_arg = &fe_bbr_info;
2705		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2706		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2707		metatask->taskinfo.bbrread.len = bbr_info->len;
2708
2709		cfi_action(metatask);
2710
2711		mtx_lock(&bbr_mtx);
2712		while (fe_bbr_info.wakeup_done == 0)
2713			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2714		mtx_unlock(&bbr_mtx);
2715
2716		bbr_info->status = metatask->status;
2717		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2718		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2719		memcpy(&bbr_info->sense_data,
2720		       &metatask->taskinfo.bbrread.sense_data,
2721		       ctl_min(sizeof(bbr_info->sense_data),
2722			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2723
2724		cfi_free_metatask(metatask);
2725
2726		mtx_destroy(&bbr_mtx);
2727		cv_destroy(&fe_bbr_info.sem);
2728
2729		break;
2730	}
2731	case CTL_DELAY_IO: {
2732		struct ctl_io_delay_info *delay_info;
2733#ifdef CTL_IO_DELAY
2734		struct ctl_lun *lun;
2735#endif /* CTL_IO_DELAY */
2736
2737		delay_info = (struct ctl_io_delay_info *)addr;
2738
2739#ifdef CTL_IO_DELAY
2740		mtx_lock(&softc->ctl_lock);
2741
2742		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2743		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2744			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2745		} else {
2746			lun = softc->ctl_luns[delay_info->lun_id];
2747			mtx_lock(&lun->lun_lock);
2748
2749			delay_info->status = CTL_DELAY_STATUS_OK;
2750
2751			switch (delay_info->delay_type) {
2752			case CTL_DELAY_TYPE_CONT:
2753				break;
2754			case CTL_DELAY_TYPE_ONESHOT:
2755				break;
2756			default:
2757				delay_info->status =
2758					CTL_DELAY_STATUS_INVALID_TYPE;
2759				break;
2760			}
2761
2762			switch (delay_info->delay_loc) {
2763			case CTL_DELAY_LOC_DATAMOVE:
2764				lun->delay_info.datamove_type =
2765					delay_info->delay_type;
2766				lun->delay_info.datamove_delay =
2767					delay_info->delay_secs;
2768				break;
2769			case CTL_DELAY_LOC_DONE:
2770				lun->delay_info.done_type =
2771					delay_info->delay_type;
2772				lun->delay_info.done_delay =
2773					delay_info->delay_secs;
2774				break;
2775			default:
2776				delay_info->status =
2777					CTL_DELAY_STATUS_INVALID_LOC;
2778				break;
2779			}
2780			mtx_unlock(&lun->lun_lock);
2781		}
2782
2783		mtx_unlock(&softc->ctl_lock);
2784#else
2785		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2786#endif /* CTL_IO_DELAY */
2787		break;
2788	}
2789	case CTL_REALSYNC_SET: {
2790		int *syncstate;
2791
2792		syncstate = (int *)addr;
2793
2794		mtx_lock(&softc->ctl_lock);
2795		switch (*syncstate) {
2796		case 0:
2797			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2798			break;
2799		case 1:
2800			softc->flags |= CTL_FLAG_REAL_SYNC;
2801			break;
2802		default:
2803			retval = EINVAL;
2804			break;
2805		}
2806		mtx_unlock(&softc->ctl_lock);
2807		break;
2808	}
2809	case CTL_REALSYNC_GET: {
2810		int *syncstate;
2811
2812		syncstate = (int*)addr;
2813
2814		mtx_lock(&softc->ctl_lock);
2815		if (softc->flags & CTL_FLAG_REAL_SYNC)
2816			*syncstate = 1;
2817		else
2818			*syncstate = 0;
2819		mtx_unlock(&softc->ctl_lock);
2820
2821		break;
2822	}
2823	case CTL_SETSYNC:
2824	case CTL_GETSYNC: {
2825		struct ctl_sync_info *sync_info;
2826		struct ctl_lun *lun;
2827
2828		sync_info = (struct ctl_sync_info *)addr;
2829
2830		mtx_lock(&softc->ctl_lock);
2831		lun = softc->ctl_luns[sync_info->lun_id];
2832		if (lun == NULL) {
2833			mtx_unlock(&softc->ctl_lock);
2834			sync_info->status = CTL_GS_SYNC_NO_LUN;
2835		}
2836		/*
2837		 * Get or set the sync interval.  We're not bounds checking
2838		 * in the set case, hopefully the user won't do something
2839		 * silly.
2840		 */
2841		mtx_lock(&lun->lun_lock);
2842		mtx_unlock(&softc->ctl_lock);
2843		if (cmd == CTL_GETSYNC)
2844			sync_info->sync_interval = lun->sync_interval;
2845		else
2846			lun->sync_interval = sync_info->sync_interval;
2847		mtx_unlock(&lun->lun_lock);
2848
2849		sync_info->status = CTL_GS_SYNC_OK;
2850
2851		break;
2852	}
2853	case CTL_GETSTATS: {
2854		struct ctl_stats *stats;
2855		struct ctl_lun *lun;
2856		int i;
2857
2858		stats = (struct ctl_stats *)addr;
2859
2860		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2861		     stats->alloc_len) {
2862			stats->status = CTL_SS_NEED_MORE_SPACE;
2863			stats->num_luns = softc->num_luns;
2864			break;
2865		}
2866		/*
2867		 * XXX KDM no locking here.  If the LUN list changes,
2868		 * things can blow up.
2869		 */
2870		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2871		     i++, lun = STAILQ_NEXT(lun, links)) {
2872			retval = copyout(&lun->stats, &stats->lun_stats[i],
2873					 sizeof(lun->stats));
2874			if (retval != 0)
2875				break;
2876		}
2877		stats->num_luns = softc->num_luns;
2878		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2879				 softc->num_luns;
2880		stats->status = CTL_SS_OK;
2881#ifdef CTL_TIME_IO
2882		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2883#else
2884		stats->flags = CTL_STATS_FLAG_NONE;
2885#endif
2886		getnanouptime(&stats->timestamp);
2887		break;
2888	}
2889	case CTL_ERROR_INJECT: {
2890		struct ctl_error_desc *err_desc, *new_err_desc;
2891		struct ctl_lun *lun;
2892
2893		err_desc = (struct ctl_error_desc *)addr;
2894
2895		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2896				      M_WAITOK | M_ZERO);
2897		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2898
2899		mtx_lock(&softc->ctl_lock);
2900		lun = softc->ctl_luns[err_desc->lun_id];
2901		if (lun == NULL) {
2902			mtx_unlock(&softc->ctl_lock);
2903			free(new_err_desc, M_CTL);
2904			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2905			       __func__, (uintmax_t)err_desc->lun_id);
2906			retval = EINVAL;
2907			break;
2908		}
2909		mtx_lock(&lun->lun_lock);
2910		mtx_unlock(&softc->ctl_lock);
2911
2912		/*
2913		 * We could do some checking here to verify the validity
2914		 * of the request, but given the complexity of error
2915		 * injection requests, the checking logic would be fairly
2916		 * complex.
2917		 *
2918		 * For now, if the request is invalid, it just won't get
2919		 * executed and might get deleted.
2920		 */
2921		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2922
2923		/*
2924		 * XXX KDM check to make sure the serial number is unique,
2925		 * in case we somehow manage to wrap.  That shouldn't
2926		 * happen for a very long time, but it's the right thing to
2927		 * do.
2928		 */
2929		new_err_desc->serial = lun->error_serial;
2930		err_desc->serial = lun->error_serial;
2931		lun->error_serial++;
2932
2933		mtx_unlock(&lun->lun_lock);
2934		break;
2935	}
2936	case CTL_ERROR_INJECT_DELETE: {
2937		struct ctl_error_desc *delete_desc, *desc, *desc2;
2938		struct ctl_lun *lun;
2939		int delete_done;
2940
2941		delete_desc = (struct ctl_error_desc *)addr;
2942		delete_done = 0;
2943
2944		mtx_lock(&softc->ctl_lock);
2945		lun = softc->ctl_luns[delete_desc->lun_id];
2946		if (lun == NULL) {
2947			mtx_unlock(&softc->ctl_lock);
2948			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2949			       __func__, (uintmax_t)delete_desc->lun_id);
2950			retval = EINVAL;
2951			break;
2952		}
2953		mtx_lock(&lun->lun_lock);
2954		mtx_unlock(&softc->ctl_lock);
2955		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2956			if (desc->serial != delete_desc->serial)
2957				continue;
2958
2959			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2960				      links);
2961			free(desc, M_CTL);
2962			delete_done = 1;
2963		}
2964		mtx_unlock(&lun->lun_lock);
2965		if (delete_done == 0) {
2966			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2967			       "error serial %ju on LUN %u\n", __func__,
2968			       delete_desc->serial, delete_desc->lun_id);
2969			retval = EINVAL;
2970			break;
2971		}
2972		break;
2973	}
2974	case CTL_DUMP_STRUCTS: {
2975		int i, j, k, idx;
2976		struct ctl_port *port;
2977		struct ctl_frontend *fe;
2978
2979		mtx_lock(&softc->ctl_lock);
2980		printf("CTL Persistent Reservation information start:\n");
2981		for (i = 0; i < CTL_MAX_LUNS; i++) {
2982			struct ctl_lun *lun;
2983
2984			lun = softc->ctl_luns[i];
2985
2986			if ((lun == NULL)
2987			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2988				continue;
2989
2990			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2991				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2992					idx = j * CTL_MAX_INIT_PER_PORT + k;
2993					if (lun->pr_keys[idx] == 0)
2994						continue;
2995					printf("  LUN %d port %d iid %d key "
2996					       "%#jx\n", i, j, k,
2997					       (uintmax_t)lun->pr_keys[idx]);
2998				}
2999			}
3000		}
3001		printf("CTL Persistent Reservation information end\n");
3002		printf("CTL Ports:\n");
3003		STAILQ_FOREACH(port, &softc->port_list, links) {
3004			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3005			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3006			       port->frontend->name, port->port_type,
3007			       port->physical_port, port->virtual_port,
3008			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3009			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3010				if (port->wwpn_iid[j].in_use == 0 &&
3011				    port->wwpn_iid[j].wwpn == 0 &&
3012				    port->wwpn_iid[j].name == NULL)
3013					continue;
3014
3015				printf("    iid %u use %d WWPN %#jx '%s'\n",
3016				    j, port->wwpn_iid[j].in_use,
3017				    (uintmax_t)port->wwpn_iid[j].wwpn,
3018				    port->wwpn_iid[j].name);
3019			}
3020		}
3021		printf("CTL Port information end\n");
3022		mtx_unlock(&softc->ctl_lock);
3023		/*
3024		 * XXX KDM calling this without a lock.  We'd likely want
3025		 * to drop the lock before calling the frontend's dump
3026		 * routine anyway.
3027		 */
3028		printf("CTL Frontends:\n");
3029		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3030			printf("  Frontend '%s'\n", fe->name);
3031			if (fe->fe_dump != NULL)
3032				fe->fe_dump();
3033		}
3034		printf("CTL Frontend information end\n");
3035		break;
3036	}
3037	case CTL_LUN_REQ: {
3038		struct ctl_lun_req *lun_req;
3039		struct ctl_backend_driver *backend;
3040
3041		lun_req = (struct ctl_lun_req *)addr;
3042
3043		backend = ctl_backend_find(lun_req->backend);
3044		if (backend == NULL) {
3045			lun_req->status = CTL_LUN_ERROR;
3046			snprintf(lun_req->error_str,
3047				 sizeof(lun_req->error_str),
3048				 "Backend \"%s\" not found.",
3049				 lun_req->backend);
3050			break;
3051		}
3052		if (lun_req->num_be_args > 0) {
3053			lun_req->kern_be_args = ctl_copyin_args(
3054				lun_req->num_be_args,
3055				lun_req->be_args,
3056				lun_req->error_str,
3057				sizeof(lun_req->error_str));
3058			if (lun_req->kern_be_args == NULL) {
3059				lun_req->status = CTL_LUN_ERROR;
3060				break;
3061			}
3062		}
3063
3064		retval = backend->ioctl(dev, cmd, addr, flag, td);
3065
3066		if (lun_req->num_be_args > 0) {
3067			ctl_copyout_args(lun_req->num_be_args,
3068				      lun_req->kern_be_args);
3069			ctl_free_args(lun_req->num_be_args,
3070				      lun_req->kern_be_args);
3071		}
3072		break;
3073	}
3074	case CTL_LUN_LIST: {
3075		struct sbuf *sb;
3076		struct ctl_lun *lun;
3077		struct ctl_lun_list *list;
3078		struct ctl_option *opt;
3079
3080		list = (struct ctl_lun_list *)addr;
3081
3082		/*
3083		 * Allocate a fixed length sbuf here, based on the length
3084		 * of the user's buffer.  We could allocate an auto-extending
3085		 * buffer, and then tell the user how much larger our
3086		 * amount of data is than his buffer, but that presents
3087		 * some problems:
3088		 *
3089		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3090		 *     we can't hold a lock while calling them with an
3091		 *     auto-extending buffer.
3092 		 *
3093		 * 2.  There is not currently a LUN reference counting
3094		 *     mechanism, outside of outstanding transactions on
3095		 *     the LUN's OOA queue.  So a LUN could go away on us
3096		 *     while we're getting the LUN number, backend-specific
3097		 *     information, etc.  Thus, given the way things
3098		 *     currently work, we need to hold the CTL lock while
3099		 *     grabbing LUN information.
3100		 *
3101		 * So, from the user's standpoint, the best thing to do is
3102		 * allocate what he thinks is a reasonable buffer length,
3103		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3104		 * double the buffer length and try again.  (And repeat
3105		 * that until he succeeds.)
3106		 */
3107		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3108		if (sb == NULL) {
3109			list->status = CTL_LUN_LIST_ERROR;
3110			snprintf(list->error_str, sizeof(list->error_str),
3111				 "Unable to allocate %d bytes for LUN list",
3112				 list->alloc_len);
3113			break;
3114		}
3115
3116		sbuf_printf(sb, "<ctllunlist>\n");
3117
3118		mtx_lock(&softc->ctl_lock);
3119		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3120			mtx_lock(&lun->lun_lock);
3121			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3122					     (uintmax_t)lun->lun);
3123
3124			/*
3125			 * Bail out as soon as we see that we've overfilled
3126			 * the buffer.
3127			 */
3128			if (retval != 0)
3129				break;
3130
3131			retval = sbuf_printf(sb, "\t<backend_type>%s"
3132					     "</backend_type>\n",
3133					     (lun->backend == NULL) ?  "none" :
3134					     lun->backend->name);
3135
3136			if (retval != 0)
3137				break;
3138
3139			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3140					     lun->be_lun->lun_type);
3141
3142			if (retval != 0)
3143				break;
3144
3145			if (lun->backend == NULL) {
3146				retval = sbuf_printf(sb, "</lun>\n");
3147				if (retval != 0)
3148					break;
3149				continue;
3150			}
3151
3152			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3153					     (lun->be_lun->maxlba > 0) ?
3154					     lun->be_lun->maxlba + 1 : 0);
3155
3156			if (retval != 0)
3157				break;
3158
3159			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3160					     lun->be_lun->blocksize);
3161
3162			if (retval != 0)
3163				break;
3164
3165			retval = sbuf_printf(sb, "\t<serial_number>");
3166
3167			if (retval != 0)
3168				break;
3169
3170			retval = ctl_sbuf_printf_esc(sb,
3171						     lun->be_lun->serial_num);
3172
3173			if (retval != 0)
3174				break;
3175
3176			retval = sbuf_printf(sb, "</serial_number>\n");
3177
3178			if (retval != 0)
3179				break;
3180
3181			retval = sbuf_printf(sb, "\t<device_id>");
3182
3183			if (retval != 0)
3184				break;
3185
3186			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3187
3188			if (retval != 0)
3189				break;
3190
3191			retval = sbuf_printf(sb, "</device_id>\n");
3192
3193			if (retval != 0)
3194				break;
3195
3196			if (lun->backend->lun_info != NULL) {
3197				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3198				if (retval != 0)
3199					break;
3200			}
3201			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3202				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3203				    opt->name, opt->value, opt->name);
3204				if (retval != 0)
3205					break;
3206			}
3207
3208			retval = sbuf_printf(sb, "</lun>\n");
3209
3210			if (retval != 0)
3211				break;
3212			mtx_unlock(&lun->lun_lock);
3213		}
3214		if (lun != NULL)
3215			mtx_unlock(&lun->lun_lock);
3216		mtx_unlock(&softc->ctl_lock);
3217
3218		if ((retval != 0)
3219		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3220			retval = 0;
3221			sbuf_delete(sb);
3222			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3223			snprintf(list->error_str, sizeof(list->error_str),
3224				 "Out of space, %d bytes is too small",
3225				 list->alloc_len);
3226			break;
3227		}
3228
3229		sbuf_finish(sb);
3230
3231		retval = copyout(sbuf_data(sb), list->lun_xml,
3232				 sbuf_len(sb) + 1);
3233
3234		list->fill_len = sbuf_len(sb) + 1;
3235		list->status = CTL_LUN_LIST_OK;
3236		sbuf_delete(sb);
3237		break;
3238	}
3239	case CTL_ISCSI: {
3240		struct ctl_iscsi *ci;
3241		struct ctl_frontend *fe;
3242
3243		ci = (struct ctl_iscsi *)addr;
3244
3245		fe = ctl_frontend_find("iscsi");
3246		if (fe == NULL) {
3247			ci->status = CTL_ISCSI_ERROR;
3248			snprintf(ci->error_str, sizeof(ci->error_str),
3249			    "Frontend \"iscsi\" not found.");
3250			break;
3251		}
3252
3253		retval = fe->ioctl(dev, cmd, addr, flag, td);
3254		break;
3255	}
3256	case CTL_PORT_REQ: {
3257		struct ctl_req *req;
3258		struct ctl_frontend *fe;
3259
3260		req = (struct ctl_req *)addr;
3261
3262		fe = ctl_frontend_find(req->driver);
3263		if (fe == NULL) {
3264			req->status = CTL_LUN_ERROR;
3265			snprintf(req->error_str, sizeof(req->error_str),
3266			    "Frontend \"%s\" not found.", req->driver);
3267			break;
3268		}
3269		if (req->num_args > 0) {
3270			req->kern_args = ctl_copyin_args(req->num_args,
3271			    req->args, req->error_str, sizeof(req->error_str));
3272			if (req->kern_args == NULL) {
3273				req->status = CTL_LUN_ERROR;
3274				break;
3275			}
3276		}
3277
3278		retval = fe->ioctl(dev, cmd, addr, flag, td);
3279
3280		if (req->num_args > 0) {
3281			ctl_copyout_args(req->num_args, req->kern_args);
3282			ctl_free_args(req->num_args, req->kern_args);
3283		}
3284		break;
3285	}
3286	case CTL_PORT_LIST: {
3287		struct sbuf *sb;
3288		struct ctl_port *port;
3289		struct ctl_lun_list *list;
3290		struct ctl_option *opt;
3291
3292		list = (struct ctl_lun_list *)addr;
3293
3294		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3295		if (sb == NULL) {
3296			list->status = CTL_LUN_LIST_ERROR;
3297			snprintf(list->error_str, sizeof(list->error_str),
3298				 "Unable to allocate %d bytes for LUN list",
3299				 list->alloc_len);
3300			break;
3301		}
3302
3303		sbuf_printf(sb, "<ctlportlist>\n");
3304
3305		mtx_lock(&softc->ctl_lock);
3306		STAILQ_FOREACH(port, &softc->port_list, links) {
3307			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3308					     (uintmax_t)port->targ_port);
3309
3310			/*
3311			 * Bail out as soon as we see that we've overfilled
3312			 * the buffer.
3313			 */
3314			if (retval != 0)
3315				break;
3316
3317			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3318			    "</frontend_type>\n", port->frontend->name);
3319			if (retval != 0)
3320				break;
3321
3322			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3323					     port->port_type);
3324			if (retval != 0)
3325				break;
3326
3327			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3328			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3329			if (retval != 0)
3330				break;
3331
3332			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3333			    port->port_name);
3334			if (retval != 0)
3335				break;
3336
3337			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3338			    port->physical_port);
3339			if (retval != 0)
3340				break;
3341
3342			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3343			    port->virtual_port);
3344			if (retval != 0)
3345				break;
3346
3347			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3348			    (uintmax_t)port->wwnn);
3349			if (retval != 0)
3350				break;
3351
3352			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3353			    (uintmax_t)port->wwpn);
3354			if (retval != 0)
3355				break;
3356
3357			if (port->port_info != NULL) {
3358				retval = port->port_info(port->onoff_arg, sb);
3359				if (retval != 0)
3360					break;
3361			}
3362			STAILQ_FOREACH(opt, &port->options, links) {
3363				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3364				    opt->name, opt->value, opt->name);
3365				if (retval != 0)
3366					break;
3367			}
3368
3369			retval = sbuf_printf(sb, "</targ_port>\n");
3370			if (retval != 0)
3371				break;
3372		}
3373		mtx_unlock(&softc->ctl_lock);
3374
3375		if ((retval != 0)
3376		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3377			retval = 0;
3378			sbuf_delete(sb);
3379			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3380			snprintf(list->error_str, sizeof(list->error_str),
3381				 "Out of space, %d bytes is too small",
3382				 list->alloc_len);
3383			break;
3384		}
3385
3386		sbuf_finish(sb);
3387
3388		retval = copyout(sbuf_data(sb), list->lun_xml,
3389				 sbuf_len(sb) + 1);
3390
3391		list->fill_len = sbuf_len(sb) + 1;
3392		list->status = CTL_LUN_LIST_OK;
3393		sbuf_delete(sb);
3394		break;
3395	}
3396	default: {
3397		/* XXX KDM should we fix this? */
3398#if 0
3399		struct ctl_backend_driver *backend;
3400		unsigned int type;
3401		int found;
3402
3403		found = 0;
3404
3405		/*
3406		 * We encode the backend type as the ioctl type for backend
3407		 * ioctls.  So parse it out here, and then search for a
3408		 * backend of this type.
3409		 */
3410		type = _IOC_TYPE(cmd);
3411
3412		STAILQ_FOREACH(backend, &softc->be_list, links) {
3413			if (backend->type == type) {
3414				found = 1;
3415				break;
3416			}
3417		}
3418		if (found == 0) {
3419			printf("ctl: unknown ioctl command %#lx or backend "
3420			       "%d\n", cmd, type);
3421			retval = EINVAL;
3422			break;
3423		}
3424		retval = backend->ioctl(dev, cmd, addr, flag, td);
3425#endif
3426		retval = ENOTTY;
3427		break;
3428	}
3429	}
3430	return (retval);
3431}
3432
3433uint32_t
3434ctl_get_initindex(struct ctl_nexus *nexus)
3435{
3436	if (nexus->targ_port < CTL_MAX_PORTS)
3437		return (nexus->initid.id +
3438			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3439	else
3440		return (nexus->initid.id +
3441		       ((nexus->targ_port - CTL_MAX_PORTS) *
3442			CTL_MAX_INIT_PER_PORT));
3443}
3444
3445uint32_t
3446ctl_get_resindex(struct ctl_nexus *nexus)
3447{
3448	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3449}
3450
3451uint32_t
3452ctl_port_idx(int port_num)
3453{
3454	if (port_num < CTL_MAX_PORTS)
3455		return(port_num);
3456	else
3457		return(port_num - CTL_MAX_PORTS);
3458}
3459
3460static uint32_t
3461ctl_map_lun(int port_num, uint32_t lun_id)
3462{
3463	struct ctl_port *port;
3464
3465	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3466	if (port == NULL)
3467		return (UINT32_MAX);
3468	if (port->lun_map == NULL)
3469		return (lun_id);
3470	return (port->lun_map(port->targ_lun_arg, lun_id));
3471}
3472
3473static uint32_t
3474ctl_map_lun_back(int port_num, uint32_t lun_id)
3475{
3476	struct ctl_port *port;
3477	uint32_t i;
3478
3479	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3480	if (port->lun_map == NULL)
3481		return (lun_id);
3482	for (i = 0; i < CTL_MAX_LUNS; i++) {
3483		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3484			return (i);
3485	}
3486	return (UINT32_MAX);
3487}
3488
3489/*
3490 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3491 * that are a power of 2.
3492 */
3493int
3494ctl_ffz(uint32_t *mask, uint32_t size)
3495{
3496	uint32_t num_chunks, num_pieces;
3497	int i, j;
3498
3499	num_chunks = (size >> 5);
3500	if (num_chunks == 0)
3501		num_chunks++;
3502	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3503
3504	for (i = 0; i < num_chunks; i++) {
3505		for (j = 0; j < num_pieces; j++) {
3506			if ((mask[i] & (1 << j)) == 0)
3507				return ((i << 5) + j);
3508		}
3509	}
3510
3511	return (-1);
3512}
3513
3514int
3515ctl_set_mask(uint32_t *mask, uint32_t bit)
3516{
3517	uint32_t chunk, piece;
3518
3519	chunk = bit >> 5;
3520	piece = bit % (sizeof(uint32_t) * 8);
3521
3522	if ((mask[chunk] & (1 << piece)) != 0)
3523		return (-1);
3524	else
3525		mask[chunk] |= (1 << piece);
3526
3527	return (0);
3528}
3529
3530int
3531ctl_clear_mask(uint32_t *mask, uint32_t bit)
3532{
3533	uint32_t chunk, piece;
3534
3535	chunk = bit >> 5;
3536	piece = bit % (sizeof(uint32_t) * 8);
3537
3538	if ((mask[chunk] & (1 << piece)) == 0)
3539		return (-1);
3540	else
3541		mask[chunk] &= ~(1 << piece);
3542
3543	return (0);
3544}
3545
3546int
3547ctl_is_set(uint32_t *mask, uint32_t bit)
3548{
3549	uint32_t chunk, piece;
3550
3551	chunk = bit >> 5;
3552	piece = bit % (sizeof(uint32_t) * 8);
3553
3554	if ((mask[chunk] & (1 << piece)) == 0)
3555		return (0);
3556	else
3557		return (1);
3558}
3559
3560#ifdef unused
3561/*
3562 * The bus, target and lun are optional, they can be filled in later.
3563 * can_wait is used to determine whether we can wait on the malloc or not.
3564 */
3565union ctl_io*
3566ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3567	      uint32_t targ_lun, int can_wait)
3568{
3569	union ctl_io *io;
3570
3571	if (can_wait)
3572		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3573	else
3574		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3575
3576	if (io != NULL) {
3577		io->io_hdr.io_type = io_type;
3578		io->io_hdr.targ_port = targ_port;
3579		/*
3580		 * XXX KDM this needs to change/go away.  We need to move
3581		 * to a preallocated pool of ctl_scsiio structures.
3582		 */
3583		io->io_hdr.nexus.targ_target.id = targ_target;
3584		io->io_hdr.nexus.targ_lun = targ_lun;
3585	}
3586
3587	return (io);
3588}
3589
3590void
3591ctl_kfree_io(union ctl_io *io)
3592{
3593	free(io, M_CTL);
3594}
3595#endif /* unused */
3596
3597/*
3598 * ctl_softc, pool_type, total_ctl_io are passed in.
3599 * npool is passed out.
3600 */
3601int
3602ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3603		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3604{
3605	uint32_t i;
3606	union ctl_io *cur_io, *next_io;
3607	struct ctl_io_pool *pool;
3608	int retval;
3609
3610	retval = 0;
3611
3612	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3613					    M_NOWAIT | M_ZERO);
3614	if (pool == NULL) {
3615		retval = ENOMEM;
3616		goto bailout;
3617	}
3618
3619	pool->type = pool_type;
3620	pool->ctl_softc = ctl_softc;
3621
3622	mtx_lock(&ctl_softc->pool_lock);
3623	pool->id = ctl_softc->cur_pool_id++;
3624	mtx_unlock(&ctl_softc->pool_lock);
3625
3626	pool->flags = CTL_POOL_FLAG_NONE;
3627	pool->refcount = 1;		/* Reference for validity. */
3628	STAILQ_INIT(&pool->free_queue);
3629
3630	/*
3631	 * XXX KDM other options here:
3632	 * - allocate a page at a time
3633	 * - allocate one big chunk of memory.
3634	 * Page allocation might work well, but would take a little more
3635	 * tracking.
3636	 */
3637	for (i = 0; i < total_ctl_io; i++) {
3638		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3639						M_NOWAIT);
3640		if (cur_io == NULL) {
3641			retval = ENOMEM;
3642			break;
3643		}
3644		cur_io->io_hdr.pool = pool;
3645		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3646		pool->total_ctl_io++;
3647		pool->free_ctl_io++;
3648	}
3649
3650	if (retval != 0) {
3651		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3652		     cur_io != NULL; cur_io = next_io) {
3653			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3654							      links);
3655			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3656				      ctl_io_hdr, links);
3657			free(cur_io, M_CTLIO);
3658		}
3659
3660		free(pool, M_CTL);
3661		goto bailout;
3662	}
3663	mtx_lock(&ctl_softc->pool_lock);
3664	ctl_softc->num_pools++;
3665	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3666	/*
3667	 * Increment our usage count if this is an external consumer, so we
3668	 * can't get unloaded until the external consumer (most likely a
3669	 * FETD) unloads and frees his pool.
3670	 *
3671	 * XXX KDM will this increment the caller's module use count, or
3672	 * mine?
3673	 */
3674#if 0
3675	if ((pool_type != CTL_POOL_EMERGENCY)
3676	 && (pool_type != CTL_POOL_INTERNAL)
3677	 && (pool_type != CTL_POOL_4OTHERSC))
3678		MOD_INC_USE_COUNT;
3679#endif
3680
3681	mtx_unlock(&ctl_softc->pool_lock);
3682
3683	*npool = pool;
3684
3685bailout:
3686
3687	return (retval);
3688}
3689
3690static int
3691ctl_pool_acquire(struct ctl_io_pool *pool)
3692{
3693
3694	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3695
3696	if (pool->flags & CTL_POOL_FLAG_INVALID)
3697		return (EINVAL);
3698
3699	pool->refcount++;
3700
3701	return (0);
3702}
3703
3704static void
3705ctl_pool_release(struct ctl_io_pool *pool)
3706{
3707	struct ctl_softc *ctl_softc = pool->ctl_softc;
3708	union ctl_io *io;
3709
3710	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3711
3712	if (--pool->refcount != 0)
3713		return;
3714
3715	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3716		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3717			      links);
3718		free(io, M_CTLIO);
3719	}
3720
3721	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3722	ctl_softc->num_pools--;
3723
3724	/*
3725	 * XXX KDM will this decrement the caller's usage count or mine?
3726	 */
3727#if 0
3728	if ((pool->type != CTL_POOL_EMERGENCY)
3729	 && (pool->type != CTL_POOL_INTERNAL)
3730	 && (pool->type != CTL_POOL_4OTHERSC))
3731		MOD_DEC_USE_COUNT;
3732#endif
3733
3734	free(pool, M_CTL);
3735}
3736
3737void
3738ctl_pool_free(struct ctl_io_pool *pool)
3739{
3740	struct ctl_softc *ctl_softc;
3741
3742	if (pool == NULL)
3743		return;
3744
3745	ctl_softc = pool->ctl_softc;
3746	mtx_lock(&ctl_softc->pool_lock);
3747	pool->flags |= CTL_POOL_FLAG_INVALID;
3748	ctl_pool_release(pool);
3749	mtx_unlock(&ctl_softc->pool_lock);
3750}
3751
3752/*
3753 * This routine does not block (except for spinlocks of course).
3754 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3755 * possible.
3756 */
3757union ctl_io *
3758ctl_alloc_io(void *pool_ref)
3759{
3760	union ctl_io *io;
3761	struct ctl_softc *ctl_softc;
3762	struct ctl_io_pool *pool, *npool;
3763	struct ctl_io_pool *emergency_pool;
3764
3765	pool = (struct ctl_io_pool *)pool_ref;
3766
3767	if (pool == NULL) {
3768		printf("%s: pool is NULL\n", __func__);
3769		return (NULL);
3770	}
3771
3772	emergency_pool = NULL;
3773
3774	ctl_softc = pool->ctl_softc;
3775
3776	mtx_lock(&ctl_softc->pool_lock);
3777	/*
3778	 * First, try to get the io structure from the user's pool.
3779	 */
3780	if (ctl_pool_acquire(pool) == 0) {
3781		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3782		if (io != NULL) {
3783			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3784			pool->total_allocated++;
3785			pool->free_ctl_io--;
3786			mtx_unlock(&ctl_softc->pool_lock);
3787			return (io);
3788		} else
3789			ctl_pool_release(pool);
3790	}
3791	/*
3792	 * If he doesn't have any io structures left, search for an
3793	 * emergency pool and grab one from there.
3794	 */
3795	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3796		if (npool->type != CTL_POOL_EMERGENCY)
3797			continue;
3798
3799		if (ctl_pool_acquire(npool) != 0)
3800			continue;
3801
3802		emergency_pool = npool;
3803
3804		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3805		if (io != NULL) {
3806			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3807			npool->total_allocated++;
3808			npool->free_ctl_io--;
3809			mtx_unlock(&ctl_softc->pool_lock);
3810			return (io);
3811		} else
3812			ctl_pool_release(npool);
3813	}
3814
3815	/* Drop the spinlock before we malloc */
3816	mtx_unlock(&ctl_softc->pool_lock);
3817
3818	/*
3819	 * The emergency pool (if it exists) didn't have one, so try an
3820	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3821	 */
3822	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3823	if (io != NULL) {
3824		/*
3825		 * If the emergency pool exists but is empty, add this
3826		 * ctl_io to its list when it gets freed.
3827		 */
3828		if (emergency_pool != NULL) {
3829			mtx_lock(&ctl_softc->pool_lock);
3830			if (ctl_pool_acquire(emergency_pool) == 0) {
3831				io->io_hdr.pool = emergency_pool;
3832				emergency_pool->total_ctl_io++;
3833				/*
3834				 * Need to bump this, otherwise
3835				 * total_allocated and total_freed won't
3836				 * match when we no longer have anything
3837				 * outstanding.
3838				 */
3839				emergency_pool->total_allocated++;
3840			}
3841			mtx_unlock(&ctl_softc->pool_lock);
3842		} else
3843			io->io_hdr.pool = NULL;
3844	}
3845
3846	return (io);
3847}
3848
3849void
3850ctl_free_io(union ctl_io *io)
3851{
3852	if (io == NULL)
3853		return;
3854
3855	/*
3856	 * If this ctl_io has a pool, return it to that pool.
3857	 */
3858	if (io->io_hdr.pool != NULL) {
3859		struct ctl_io_pool *pool;
3860
3861		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3862		mtx_lock(&pool->ctl_softc->pool_lock);
3863		io->io_hdr.io_type = 0xff;
3864		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3865		pool->total_freed++;
3866		pool->free_ctl_io++;
3867		ctl_pool_release(pool);
3868		mtx_unlock(&pool->ctl_softc->pool_lock);
3869	} else {
3870		/*
3871		 * Otherwise, just free it.  We probably malloced it and
3872		 * the emergency pool wasn't available.
3873		 */
3874		free(io, M_CTLIO);
3875	}
3876
3877}
3878
3879void
3880ctl_zero_io(union ctl_io *io)
3881{
3882	void *pool_ref;
3883
3884	if (io == NULL)
3885		return;
3886
3887	/*
3888	 * May need to preserve linked list pointers at some point too.
3889	 */
3890	pool_ref = io->io_hdr.pool;
3891
3892	memset(io, 0, sizeof(*io));
3893
3894	io->io_hdr.pool = pool_ref;
3895}
3896
3897/*
3898 * This routine is currently used for internal copies of ctl_ios that need
3899 * to persist for some reason after we've already returned status to the
3900 * FETD.  (Thus the flag set.)
3901 *
3902 * XXX XXX
3903 * Note that this makes a blind copy of all fields in the ctl_io, except
3904 * for the pool reference.  This includes any memory that has been
3905 * allocated!  That memory will no longer be valid after done has been
3906 * called, so this would be VERY DANGEROUS for command that actually does
3907 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3908 * start and stop commands, which don't transfer any data, so this is not a
3909 * problem.  If it is used for anything else, the caller would also need to
3910 * allocate data buffer space and this routine would need to be modified to
3911 * copy the data buffer(s) as well.
3912 */
3913void
3914ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3915{
3916	void *pool_ref;
3917
3918	if ((src == NULL)
3919	 || (dest == NULL))
3920		return;
3921
3922	/*
3923	 * May need to preserve linked list pointers at some point too.
3924	 */
3925	pool_ref = dest->io_hdr.pool;
3926
3927	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3928
3929	dest->io_hdr.pool = pool_ref;
3930	/*
3931	 * We need to know that this is an internal copy, and doesn't need
3932	 * to get passed back to the FETD that allocated it.
3933	 */
3934	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3935}
3936
3937#ifdef NEEDTOPORT
3938static void
3939ctl_update_power_subpage(struct copan_power_subpage *page)
3940{
3941	int num_luns, num_partitions, config_type;
3942	struct ctl_softc *softc;
3943	cs_BOOL_t aor_present, shelf_50pct_power;
3944	cs_raidset_personality_t rs_type;
3945	int max_active_luns;
3946
3947	softc = control_softc;
3948
3949	/* subtract out the processor LUN */
3950	num_luns = softc->num_luns - 1;
3951	/*
3952	 * Default to 7 LUNs active, which was the only number we allowed
3953	 * in the past.
3954	 */
3955	max_active_luns = 7;
3956
3957	num_partitions = config_GetRsPartitionInfo();
3958	config_type = config_GetConfigType();
3959	shelf_50pct_power = config_GetShelfPowerMode();
3960	aor_present = config_IsAorRsPresent();
3961
3962	rs_type = ddb_GetRsRaidType(1);
3963	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3964	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3965		EPRINT(0, "Unsupported RS type %d!", rs_type);
3966	}
3967
3968
3969	page->total_luns = num_luns;
3970
3971	switch (config_type) {
3972	case 40:
3973		/*
3974		 * In a 40 drive configuration, it doesn't matter what DC
3975		 * cards we have, whether we have AOR enabled or not,
3976		 * partitioning or not, or what type of RAIDset we have.
3977		 * In that scenario, we can power up every LUN we present
3978		 * to the user.
3979		 */
3980		max_active_luns = num_luns;
3981
3982		break;
3983	case 64:
3984		if (shelf_50pct_power == CS_FALSE) {
3985			/* 25% power */
3986			if (aor_present == CS_TRUE) {
3987				if (rs_type ==
3988				     CS_RAIDSET_PERSONALITY_RAID5) {
3989					max_active_luns = 7;
3990				} else if (rs_type ==
3991					 CS_RAIDSET_PERSONALITY_RAID1){
3992					max_active_luns = 14;
3993				} else {
3994					/* XXX KDM now what?? */
3995				}
3996			} else {
3997				if (rs_type ==
3998				     CS_RAIDSET_PERSONALITY_RAID5) {
3999					max_active_luns = 8;
4000				} else if (rs_type ==
4001					 CS_RAIDSET_PERSONALITY_RAID1){
4002					max_active_luns = 16;
4003				} else {
4004					/* XXX KDM now what?? */
4005				}
4006			}
4007		} else {
4008			/* 50% power */
4009			/*
4010			 * With 50% power in a 64 drive configuration, we
4011			 * can power all LUNs we present.
4012			 */
4013			max_active_luns = num_luns;
4014		}
4015		break;
4016	case 112:
4017		if (shelf_50pct_power == CS_FALSE) {
4018			/* 25% power */
4019			if (aor_present == CS_TRUE) {
4020				if (rs_type ==
4021				     CS_RAIDSET_PERSONALITY_RAID5) {
4022					max_active_luns = 7;
4023				} else if (rs_type ==
4024					 CS_RAIDSET_PERSONALITY_RAID1){
4025					max_active_luns = 14;
4026				} else {
4027					/* XXX KDM now what?? */
4028				}
4029			} else {
4030				if (rs_type ==
4031				     CS_RAIDSET_PERSONALITY_RAID5) {
4032					max_active_luns = 8;
4033				} else if (rs_type ==
4034					 CS_RAIDSET_PERSONALITY_RAID1){
4035					max_active_luns = 16;
4036				} else {
4037					/* XXX KDM now what?? */
4038				}
4039			}
4040		} else {
4041			/* 50% power */
4042			if (aor_present == CS_TRUE) {
4043				if (rs_type ==
4044				     CS_RAIDSET_PERSONALITY_RAID5) {
4045					max_active_luns = 14;
4046				} else if (rs_type ==
4047					 CS_RAIDSET_PERSONALITY_RAID1){
4048					/*
4049					 * We're assuming here that disk
4050					 * caching is enabled, and so we're
4051					 * able to power up half of each
4052					 * LUN, and cache all writes.
4053					 */
4054					max_active_luns = num_luns;
4055				} else {
4056					/* XXX KDM now what?? */
4057				}
4058			} else {
4059				if (rs_type ==
4060				     CS_RAIDSET_PERSONALITY_RAID5) {
4061					max_active_luns = 15;
4062				} else if (rs_type ==
4063					 CS_RAIDSET_PERSONALITY_RAID1){
4064					max_active_luns = 30;
4065				} else {
4066					/* XXX KDM now what?? */
4067				}
4068			}
4069		}
4070		break;
4071	default:
4072		/*
4073		 * In this case, we have an unknown configuration, so we
4074		 * just use the default from above.
4075		 */
4076		break;
4077	}
4078
4079	page->max_active_luns = max_active_luns;
4080#if 0
4081	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4082	       page->total_luns, page->max_active_luns);
4083#endif
4084}
4085#endif /* NEEDTOPORT */
4086
4087/*
4088 * This routine could be used in the future to load default and/or saved
4089 * mode page parameters for a particuar lun.
4090 */
4091static int
4092ctl_init_page_index(struct ctl_lun *lun)
4093{
4094	int i;
4095	struct ctl_page_index *page_index;
4096	struct ctl_softc *softc;
4097	const char *value;
4098
4099	memcpy(&lun->mode_pages.index, page_index_template,
4100	       sizeof(page_index_template));
4101
4102	softc = lun->ctl_softc;
4103
4104	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4105
4106		page_index = &lun->mode_pages.index[i];
4107		/*
4108		 * If this is a disk-only mode page, there's no point in
4109		 * setting it up.  For some pages, we have to have some
4110		 * basic information about the disk in order to calculate the
4111		 * mode page data.
4112		 */
4113		if ((lun->be_lun->lun_type != T_DIRECT)
4114		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4115			continue;
4116
4117		switch (page_index->page_code & SMPH_PC_MASK) {
4118		case SMS_FORMAT_DEVICE_PAGE: {
4119			struct scsi_format_page *format_page;
4120
4121			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4122				panic("subpage is incorrect!");
4123
4124			/*
4125			 * Sectors per track are set above.  Bytes per
4126			 * sector need to be set here on a per-LUN basis.
4127			 */
4128			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4129			       &format_page_default,
4130			       sizeof(format_page_default));
4131			memcpy(&lun->mode_pages.format_page[
4132			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4133			       sizeof(format_page_changeable));
4134			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4135			       &format_page_default,
4136			       sizeof(format_page_default));
4137			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4138			       &format_page_default,
4139			       sizeof(format_page_default));
4140
4141			format_page = &lun->mode_pages.format_page[
4142				CTL_PAGE_CURRENT];
4143			scsi_ulto2b(lun->be_lun->blocksize,
4144				    format_page->bytes_per_sector);
4145
4146			format_page = &lun->mode_pages.format_page[
4147				CTL_PAGE_DEFAULT];
4148			scsi_ulto2b(lun->be_lun->blocksize,
4149				    format_page->bytes_per_sector);
4150
4151			format_page = &lun->mode_pages.format_page[
4152				CTL_PAGE_SAVED];
4153			scsi_ulto2b(lun->be_lun->blocksize,
4154				    format_page->bytes_per_sector);
4155
4156			page_index->page_data =
4157				(uint8_t *)lun->mode_pages.format_page;
4158			break;
4159		}
4160		case SMS_RIGID_DISK_PAGE: {
4161			struct scsi_rigid_disk_page *rigid_disk_page;
4162			uint32_t sectors_per_cylinder;
4163			uint64_t cylinders;
4164#ifndef	__XSCALE__
4165			int shift;
4166#endif /* !__XSCALE__ */
4167
4168			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4169				panic("invalid subpage value %d",
4170				      page_index->subpage);
4171
4172			/*
4173			 * Rotation rate and sectors per track are set
4174			 * above.  We calculate the cylinders here based on
4175			 * capacity.  Due to the number of heads and
4176			 * sectors per track we're using, smaller arrays
4177			 * may turn out to have 0 cylinders.  Linux and
4178			 * FreeBSD don't pay attention to these mode pages
4179			 * to figure out capacity, but Solaris does.  It
4180			 * seems to deal with 0 cylinders just fine, and
4181			 * works out a fake geometry based on the capacity.
4182			 */
4183			memcpy(&lun->mode_pages.rigid_disk_page[
4184			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4185			       sizeof(rigid_disk_page_default));
4186			memcpy(&lun->mode_pages.rigid_disk_page[
4187			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4188			       sizeof(rigid_disk_page_changeable));
4189			memcpy(&lun->mode_pages.rigid_disk_page[
4190			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4191			       sizeof(rigid_disk_page_default));
4192			memcpy(&lun->mode_pages.rigid_disk_page[
4193			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4194			       sizeof(rigid_disk_page_default));
4195
4196			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4197				CTL_DEFAULT_HEADS;
4198
4199			/*
4200			 * The divide method here will be more accurate,
4201			 * probably, but results in floating point being
4202			 * used in the kernel on i386 (__udivdi3()).  On the
4203			 * XScale, though, __udivdi3() is implemented in
4204			 * software.
4205			 *
4206			 * The shift method for cylinder calculation is
4207			 * accurate if sectors_per_cylinder is a power of
4208			 * 2.  Otherwise it might be slightly off -- you
4209			 * might have a bit of a truncation problem.
4210			 */
4211#ifdef	__XSCALE__
4212			cylinders = (lun->be_lun->maxlba + 1) /
4213				sectors_per_cylinder;
4214#else
4215			for (shift = 31; shift > 0; shift--) {
4216				if (sectors_per_cylinder & (1 << shift))
4217					break;
4218			}
4219			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4220#endif
4221
4222			/*
4223			 * We've basically got 3 bytes, or 24 bits for the
4224			 * cylinder size in the mode page.  If we're over,
4225			 * just round down to 2^24.
4226			 */
4227			if (cylinders > 0xffffff)
4228				cylinders = 0xffffff;
4229
4230			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4231				CTL_PAGE_CURRENT];
4232			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4233
4234			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4235				CTL_PAGE_DEFAULT];
4236			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4237
4238			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4239				CTL_PAGE_SAVED];
4240			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4241
4242			page_index->page_data =
4243				(uint8_t *)lun->mode_pages.rigid_disk_page;
4244			break;
4245		}
4246		case SMS_CACHING_PAGE: {
4247			struct scsi_caching_page *caching_page;
4248
4249			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4250				panic("invalid subpage value %d",
4251				      page_index->subpage);
4252			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4253			       &caching_page_default,
4254			       sizeof(caching_page_default));
4255			memcpy(&lun->mode_pages.caching_page[
4256			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4257			       sizeof(caching_page_changeable));
4258			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4259			       &caching_page_default,
4260			       sizeof(caching_page_default));
4261			caching_page = &lun->mode_pages.caching_page[
4262			    CTL_PAGE_SAVED];
4263			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4264			if (value != NULL && strcmp(value, "off") == 0)
4265				caching_page->flags1 &= ~SCP_WCE;
4266			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4267			if (value != NULL && strcmp(value, "off") == 0)
4268				caching_page->flags1 |= SCP_RCD;
4269			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4270			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4271			       sizeof(caching_page_default));
4272			page_index->page_data =
4273				(uint8_t *)lun->mode_pages.caching_page;
4274			break;
4275		}
4276		case SMS_CONTROL_MODE_PAGE: {
4277			struct scsi_control_page *control_page;
4278
4279			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4280				panic("invalid subpage value %d",
4281				      page_index->subpage);
4282
4283			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4284			       &control_page_default,
4285			       sizeof(control_page_default));
4286			memcpy(&lun->mode_pages.control_page[
4287			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4288			       sizeof(control_page_changeable));
4289			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4290			       &control_page_default,
4291			       sizeof(control_page_default));
4292			control_page = &lun->mode_pages.control_page[
4293			    CTL_PAGE_SAVED];
4294			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4295			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4296				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4297				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4298			}
4299			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4300			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4301			       sizeof(control_page_default));
4302			page_index->page_data =
4303				(uint8_t *)lun->mode_pages.control_page;
4304			break;
4305
4306		}
4307		case SMS_VENDOR_SPECIFIC_PAGE:{
4308			switch (page_index->subpage) {
4309			case PWR_SUBPAGE_CODE: {
4310				struct copan_power_subpage *current_page,
4311							   *saved_page;
4312
4313				memcpy(&lun->mode_pages.power_subpage[
4314				       CTL_PAGE_CURRENT],
4315				       &power_page_default,
4316				       sizeof(power_page_default));
4317				memcpy(&lun->mode_pages.power_subpage[
4318				       CTL_PAGE_CHANGEABLE],
4319				       &power_page_changeable,
4320				       sizeof(power_page_changeable));
4321				memcpy(&lun->mode_pages.power_subpage[
4322				       CTL_PAGE_DEFAULT],
4323				       &power_page_default,
4324				       sizeof(power_page_default));
4325				memcpy(&lun->mode_pages.power_subpage[
4326				       CTL_PAGE_SAVED],
4327				       &power_page_default,
4328				       sizeof(power_page_default));
4329				page_index->page_data =
4330				    (uint8_t *)lun->mode_pages.power_subpage;
4331
4332				current_page = (struct copan_power_subpage *)
4333					(page_index->page_data +
4334					 (page_index->page_len *
4335					  CTL_PAGE_CURRENT));
4336			        saved_page = (struct copan_power_subpage *)
4337				        (page_index->page_data +
4338					 (page_index->page_len *
4339					  CTL_PAGE_SAVED));
4340				break;
4341			}
4342			case APS_SUBPAGE_CODE: {
4343				struct copan_aps_subpage *current_page,
4344							 *saved_page;
4345
4346				// This gets set multiple times but
4347				// it should always be the same. It's
4348				// only done during init so who cares.
4349				index_to_aps_page = i;
4350
4351				memcpy(&lun->mode_pages.aps_subpage[
4352				       CTL_PAGE_CURRENT],
4353				       &aps_page_default,
4354				       sizeof(aps_page_default));
4355				memcpy(&lun->mode_pages.aps_subpage[
4356				       CTL_PAGE_CHANGEABLE],
4357				       &aps_page_changeable,
4358				       sizeof(aps_page_changeable));
4359				memcpy(&lun->mode_pages.aps_subpage[
4360				       CTL_PAGE_DEFAULT],
4361				       &aps_page_default,
4362				       sizeof(aps_page_default));
4363				memcpy(&lun->mode_pages.aps_subpage[
4364				       CTL_PAGE_SAVED],
4365				       &aps_page_default,
4366				       sizeof(aps_page_default));
4367				page_index->page_data =
4368					(uint8_t *)lun->mode_pages.aps_subpage;
4369
4370				current_page = (struct copan_aps_subpage *)
4371					(page_index->page_data +
4372					 (page_index->page_len *
4373					  CTL_PAGE_CURRENT));
4374				saved_page = (struct copan_aps_subpage *)
4375					(page_index->page_data +
4376					 (page_index->page_len *
4377					  CTL_PAGE_SAVED));
4378				break;
4379			}
4380			case DBGCNF_SUBPAGE_CODE: {
4381				struct copan_debugconf_subpage *current_page,
4382							       *saved_page;
4383
4384				memcpy(&lun->mode_pages.debugconf_subpage[
4385				       CTL_PAGE_CURRENT],
4386				       &debugconf_page_default,
4387				       sizeof(debugconf_page_default));
4388				memcpy(&lun->mode_pages.debugconf_subpage[
4389				       CTL_PAGE_CHANGEABLE],
4390				       &debugconf_page_changeable,
4391				       sizeof(debugconf_page_changeable));
4392				memcpy(&lun->mode_pages.debugconf_subpage[
4393				       CTL_PAGE_DEFAULT],
4394				       &debugconf_page_default,
4395				       sizeof(debugconf_page_default));
4396				memcpy(&lun->mode_pages.debugconf_subpage[
4397				       CTL_PAGE_SAVED],
4398				       &debugconf_page_default,
4399				       sizeof(debugconf_page_default));
4400				page_index->page_data =
4401					(uint8_t *)lun->mode_pages.debugconf_subpage;
4402
4403				current_page = (struct copan_debugconf_subpage *)
4404					(page_index->page_data +
4405					 (page_index->page_len *
4406					  CTL_PAGE_CURRENT));
4407				saved_page = (struct copan_debugconf_subpage *)
4408					(page_index->page_data +
4409					 (page_index->page_len *
4410					  CTL_PAGE_SAVED));
4411				break;
4412			}
4413			default:
4414				panic("invalid subpage value %d",
4415				      page_index->subpage);
4416				break;
4417			}
4418   			break;
4419		}
4420		default:
4421			panic("invalid page value %d",
4422			      page_index->page_code & SMPH_PC_MASK);
4423			break;
4424    	}
4425	}
4426
4427	return (CTL_RETVAL_COMPLETE);
4428}
4429
4430/*
4431 * LUN allocation.
4432 *
4433 * Requirements:
4434 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4435 *   wants us to allocate the LUN and he can block.
4436 * - ctl_softc is always set
4437 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4438 *
4439 * Returns 0 for success, non-zero (errno) for failure.
4440 */
4441static int
4442ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4443	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4444{
4445	struct ctl_lun *nlun, *lun;
4446	struct ctl_port *port;
4447	struct scsi_vpd_id_descriptor *desc;
4448	struct scsi_vpd_id_t10 *t10id;
4449	const char *eui, *naa, *scsiname, *vendor, *value;
4450	int lun_number, i, lun_malloced;
4451	int devidlen, idlen1, idlen2 = 0, len;
4452
4453	if (be_lun == NULL)
4454		return (EINVAL);
4455
4456	/*
4457	 * We currently only support Direct Access or Processor LUN types.
4458	 */
4459	switch (be_lun->lun_type) {
4460	case T_DIRECT:
4461		break;
4462	case T_PROCESSOR:
4463		break;
4464	case T_SEQUENTIAL:
4465	case T_CHANGER:
4466	default:
4467		be_lun->lun_config_status(be_lun->be_lun,
4468					  CTL_LUN_CONFIG_FAILURE);
4469		break;
4470	}
4471	if (ctl_lun == NULL) {
4472		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4473		lun_malloced = 1;
4474	} else {
4475		lun_malloced = 0;
4476		lun = ctl_lun;
4477	}
4478
4479	memset(lun, 0, sizeof(*lun));
4480	if (lun_malloced)
4481		lun->flags = CTL_LUN_MALLOCED;
4482
4483	/* Generate LUN ID. */
4484	devidlen = max(CTL_DEVID_MIN_LEN,
4485	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4486	idlen1 = sizeof(*t10id) + devidlen;
4487	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4488	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4489	if (scsiname != NULL) {
4490		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4491		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4492	}
4493	eui = ctl_get_opt(&be_lun->options, "eui");
4494	if (eui != NULL) {
4495		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4496	}
4497	naa = ctl_get_opt(&be_lun->options, "naa");
4498	if (naa != NULL) {
4499		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4500	}
4501	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4502	    M_CTL, M_WAITOK | M_ZERO);
4503	lun->lun_devid->len = len;
4504	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4505	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4506	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4507	desc->length = idlen1;
4508	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4509	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4510	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4511		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4512	} else {
4513		strncpy(t10id->vendor, vendor,
4514		    min(sizeof(t10id->vendor), strlen(vendor)));
4515	}
4516	strncpy((char *)t10id->vendor_spec_id,
4517	    (char *)be_lun->device_id, devidlen);
4518	if (scsiname != NULL) {
4519		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4520		    desc->length);
4521		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4522		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4523		    SVPD_ID_TYPE_SCSI_NAME;
4524		desc->length = idlen2;
4525		strlcpy(desc->identifier, scsiname, idlen2);
4526	}
4527	if (eui != NULL) {
4528		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4529		    desc->length);
4530		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4531		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4532		    SVPD_ID_TYPE_EUI64;
4533		desc->length = 8;
4534		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4535	}
4536	if (naa != NULL) {
4537		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4538		    desc->length);
4539		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4540		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4541		    SVPD_ID_TYPE_NAA;
4542		desc->length = 8;
4543		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4544	}
4545
4546	mtx_lock(&ctl_softc->ctl_lock);
4547	/*
4548	 * See if the caller requested a particular LUN number.  If so, see
4549	 * if it is available.  Otherwise, allocate the first available LUN.
4550	 */
4551	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4552		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4553		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4554			mtx_unlock(&ctl_softc->ctl_lock);
4555			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4556				printf("ctl: requested LUN ID %d is higher "
4557				       "than CTL_MAX_LUNS - 1 (%d)\n",
4558				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4559			} else {
4560				/*
4561				 * XXX KDM return an error, or just assign
4562				 * another LUN ID in this case??
4563				 */
4564				printf("ctl: requested LUN ID %d is already "
4565				       "in use\n", be_lun->req_lun_id);
4566			}
4567			if (lun->flags & CTL_LUN_MALLOCED)
4568				free(lun, M_CTL);
4569			be_lun->lun_config_status(be_lun->be_lun,
4570						  CTL_LUN_CONFIG_FAILURE);
4571			return (ENOSPC);
4572		}
4573		lun_number = be_lun->req_lun_id;
4574	} else {
4575		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4576		if (lun_number == -1) {
4577			mtx_unlock(&ctl_softc->ctl_lock);
4578			printf("ctl: can't allocate LUN on target %ju, out of "
4579			       "LUNs\n", (uintmax_t)target_id.id);
4580			if (lun->flags & CTL_LUN_MALLOCED)
4581				free(lun, M_CTL);
4582			be_lun->lun_config_status(be_lun->be_lun,
4583						  CTL_LUN_CONFIG_FAILURE);
4584			return (ENOSPC);
4585		}
4586	}
4587	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4588
4589	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4590	lun->target = target_id;
4591	lun->lun = lun_number;
4592	lun->be_lun = be_lun;
4593	/*
4594	 * The processor LUN is always enabled.  Disk LUNs come on line
4595	 * disabled, and must be enabled by the backend.
4596	 */
4597	lun->flags |= CTL_LUN_DISABLED;
4598	lun->backend = be_lun->be;
4599	be_lun->ctl_lun = lun;
4600	be_lun->lun_id = lun_number;
4601	atomic_add_int(&be_lun->be->num_luns, 1);
4602	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4603		lun->flags |= CTL_LUN_STOPPED;
4604
4605	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4606		lun->flags |= CTL_LUN_INOPERABLE;
4607
4608	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4609		lun->flags |= CTL_LUN_PRIMARY_SC;
4610
4611	value = ctl_get_opt(&be_lun->options, "readonly");
4612	if (value != NULL && strcmp(value, "on") == 0)
4613		lun->flags |= CTL_LUN_READONLY;
4614
4615	lun->ctl_softc = ctl_softc;
4616	TAILQ_INIT(&lun->ooa_queue);
4617	TAILQ_INIT(&lun->blocked_queue);
4618	STAILQ_INIT(&lun->error_list);
4619	ctl_tpc_lun_init(lun);
4620
4621	/*
4622	 * Initialize the mode page index.
4623	 */
4624	ctl_init_page_index(lun);
4625
4626	/*
4627	 * Set the poweron UA for all initiators on this LUN only.
4628	 */
4629	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4630		lun->pending_ua[i] = CTL_UA_POWERON;
4631
4632	/*
4633	 * Now, before we insert this lun on the lun list, set the lun
4634	 * inventory changed UA for all other luns.
4635	 */
4636	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4637		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4638			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4639		}
4640	}
4641
4642	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4643
4644	ctl_softc->ctl_luns[lun_number] = lun;
4645
4646	ctl_softc->num_luns++;
4647
4648	/* Setup statistics gathering */
4649	lun->stats.device_type = be_lun->lun_type;
4650	lun->stats.lun_number = lun_number;
4651	if (lun->stats.device_type == T_DIRECT)
4652		lun->stats.blocksize = be_lun->blocksize;
4653	else
4654		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4655	for (i = 0;i < CTL_MAX_PORTS;i++)
4656		lun->stats.ports[i].targ_port = i;
4657
4658	mtx_unlock(&ctl_softc->ctl_lock);
4659
4660	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4661
4662	/*
4663	 * Run through each registered FETD and bring it online if it isn't
4664	 * already.  Enable the target ID if it hasn't been enabled, and
4665	 * enable this particular LUN.
4666	 */
4667	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4668		int retval;
4669
4670		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4671		if (retval != 0) {
4672			printf("ctl_alloc_lun: FETD %s port %d returned error "
4673			       "%d for lun_enable on target %ju lun %d\n",
4674			       port->port_name, port->targ_port, retval,
4675			       (uintmax_t)target_id.id, lun_number);
4676		} else
4677			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4678	}
4679	return (0);
4680}
4681
4682/*
4683 * Delete a LUN.
4684 * Assumptions:
4685 * - LUN has already been marked invalid and any pending I/O has been taken
4686 *   care of.
4687 */
4688static int
4689ctl_free_lun(struct ctl_lun *lun)
4690{
4691	struct ctl_softc *softc;
4692#if 0
4693	struct ctl_port *port;
4694#endif
4695	struct ctl_lun *nlun;
4696	int i;
4697
4698	softc = lun->ctl_softc;
4699
4700	mtx_assert(&softc->ctl_lock, MA_OWNED);
4701
4702	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4703
4704	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4705
4706	softc->ctl_luns[lun->lun] = NULL;
4707
4708	if (!TAILQ_EMPTY(&lun->ooa_queue))
4709		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4710
4711	softc->num_luns--;
4712
4713	/*
4714	 * XXX KDM this scheme only works for a single target/multiple LUN
4715	 * setup.  It needs to be revamped for a multiple target scheme.
4716	 *
4717	 * XXX KDM this results in port->lun_disable() getting called twice,
4718	 * once when ctl_disable_lun() is called, and a second time here.
4719	 * We really need to re-think the LUN disable semantics.  There
4720	 * should probably be several steps/levels to LUN removal:
4721	 *  - disable
4722	 *  - invalidate
4723	 *  - free
4724 	 *
4725	 * Right now we only have a disable method when communicating to
4726	 * the front end ports, at least for individual LUNs.
4727	 */
4728#if 0
4729	STAILQ_FOREACH(port, &softc->port_list, links) {
4730		int retval;
4731
4732		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4733					 lun->lun);
4734		if (retval != 0) {
4735			printf("ctl_free_lun: FETD %s port %d returned error "
4736			       "%d for lun_disable on target %ju lun %jd\n",
4737			       port->port_name, port->targ_port, retval,
4738			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4739		}
4740
4741		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4742			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4743
4744			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4745			if (retval != 0) {
4746				printf("ctl_free_lun: FETD %s port %d "
4747				       "returned error %d for targ_disable on "
4748				       "target %ju\n", port->port_name,
4749				       port->targ_port, retval,
4750				       (uintmax_t)lun->target.id);
4751			} else
4752				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4753
4754			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4755				continue;
4756
4757#if 0
4758			port->port_offline(port->onoff_arg);
4759			port->status &= ~CTL_PORT_STATUS_ONLINE;
4760#endif
4761		}
4762	}
4763#endif
4764
4765	/*
4766	 * Tell the backend to free resources, if this LUN has a backend.
4767	 */
4768	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4769	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4770
4771	ctl_tpc_lun_shutdown(lun);
4772	mtx_destroy(&lun->lun_lock);
4773	free(lun->lun_devid, M_CTL);
4774	if (lun->flags & CTL_LUN_MALLOCED)
4775		free(lun, M_CTL);
4776
4777	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4778		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4779			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4780		}
4781	}
4782
4783	return (0);
4784}
4785
4786static void
4787ctl_create_lun(struct ctl_be_lun *be_lun)
4788{
4789	struct ctl_softc *ctl_softc;
4790
4791	ctl_softc = control_softc;
4792
4793	/*
4794	 * ctl_alloc_lun() should handle all potential failure cases.
4795	 */
4796	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4797}
4798
4799int
4800ctl_add_lun(struct ctl_be_lun *be_lun)
4801{
4802	struct ctl_softc *ctl_softc = control_softc;
4803
4804	mtx_lock(&ctl_softc->ctl_lock);
4805	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4806	mtx_unlock(&ctl_softc->ctl_lock);
4807	wakeup(&ctl_softc->pending_lun_queue);
4808
4809	return (0);
4810}
4811
4812int
4813ctl_enable_lun(struct ctl_be_lun *be_lun)
4814{
4815	struct ctl_softc *ctl_softc;
4816	struct ctl_port *port, *nport;
4817	struct ctl_lun *lun;
4818	int retval;
4819
4820	ctl_softc = control_softc;
4821
4822	lun = (struct ctl_lun *)be_lun->ctl_lun;
4823
4824	mtx_lock(&ctl_softc->ctl_lock);
4825	mtx_lock(&lun->lun_lock);
4826	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4827		/*
4828		 * eh?  Why did we get called if the LUN is already
4829		 * enabled?
4830		 */
4831		mtx_unlock(&lun->lun_lock);
4832		mtx_unlock(&ctl_softc->ctl_lock);
4833		return (0);
4834	}
4835	lun->flags &= ~CTL_LUN_DISABLED;
4836	mtx_unlock(&lun->lun_lock);
4837
4838	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4839		nport = STAILQ_NEXT(port, links);
4840
4841		/*
4842		 * Drop the lock while we call the FETD's enable routine.
4843		 * This can lead to a callback into CTL (at least in the
4844		 * case of the internal initiator frontend.
4845		 */
4846		mtx_unlock(&ctl_softc->ctl_lock);
4847		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4848		mtx_lock(&ctl_softc->ctl_lock);
4849		if (retval != 0) {
4850			printf("%s: FETD %s port %d returned error "
4851			       "%d for lun_enable on target %ju lun %jd\n",
4852			       __func__, port->port_name, port->targ_port, retval,
4853			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4854		}
4855#if 0
4856		 else {
4857            /* NOTE:  TODO:  why does lun enable affect port status? */
4858			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4859		}
4860#endif
4861	}
4862
4863	mtx_unlock(&ctl_softc->ctl_lock);
4864
4865	return (0);
4866}
4867
4868int
4869ctl_disable_lun(struct ctl_be_lun *be_lun)
4870{
4871	struct ctl_softc *ctl_softc;
4872	struct ctl_port *port;
4873	struct ctl_lun *lun;
4874	int retval;
4875
4876	ctl_softc = control_softc;
4877
4878	lun = (struct ctl_lun *)be_lun->ctl_lun;
4879
4880	mtx_lock(&ctl_softc->ctl_lock);
4881	mtx_lock(&lun->lun_lock);
4882	if (lun->flags & CTL_LUN_DISABLED) {
4883		mtx_unlock(&lun->lun_lock);
4884		mtx_unlock(&ctl_softc->ctl_lock);
4885		return (0);
4886	}
4887	lun->flags |= CTL_LUN_DISABLED;
4888	mtx_unlock(&lun->lun_lock);
4889
4890	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4891		mtx_unlock(&ctl_softc->ctl_lock);
4892		/*
4893		 * Drop the lock before we call the frontend's disable
4894		 * routine, to avoid lock order reversals.
4895		 *
4896		 * XXX KDM what happens if the frontend list changes while
4897		 * we're traversing it?  It's unlikely, but should be handled.
4898		 */
4899		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4900					 lun->lun);
4901		mtx_lock(&ctl_softc->ctl_lock);
4902		if (retval != 0) {
4903			printf("ctl_alloc_lun: FETD %s port %d returned error "
4904			       "%d for lun_disable on target %ju lun %jd\n",
4905			       port->port_name, port->targ_port, retval,
4906			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4907		}
4908	}
4909
4910	mtx_unlock(&ctl_softc->ctl_lock);
4911
4912	return (0);
4913}
4914
4915int
4916ctl_start_lun(struct ctl_be_lun *be_lun)
4917{
4918	struct ctl_softc *ctl_softc;
4919	struct ctl_lun *lun;
4920
4921	ctl_softc = control_softc;
4922
4923	lun = (struct ctl_lun *)be_lun->ctl_lun;
4924
4925	mtx_lock(&lun->lun_lock);
4926	lun->flags &= ~CTL_LUN_STOPPED;
4927	mtx_unlock(&lun->lun_lock);
4928
4929	return (0);
4930}
4931
4932int
4933ctl_stop_lun(struct ctl_be_lun *be_lun)
4934{
4935	struct ctl_softc *ctl_softc;
4936	struct ctl_lun *lun;
4937
4938	ctl_softc = control_softc;
4939
4940	lun = (struct ctl_lun *)be_lun->ctl_lun;
4941
4942	mtx_lock(&lun->lun_lock);
4943	lun->flags |= CTL_LUN_STOPPED;
4944	mtx_unlock(&lun->lun_lock);
4945
4946	return (0);
4947}
4948
4949int
4950ctl_lun_offline(struct ctl_be_lun *be_lun)
4951{
4952	struct ctl_softc *ctl_softc;
4953	struct ctl_lun *lun;
4954
4955	ctl_softc = control_softc;
4956
4957	lun = (struct ctl_lun *)be_lun->ctl_lun;
4958
4959	mtx_lock(&lun->lun_lock);
4960	lun->flags |= CTL_LUN_OFFLINE;
4961	mtx_unlock(&lun->lun_lock);
4962
4963	return (0);
4964}
4965
4966int
4967ctl_lun_online(struct ctl_be_lun *be_lun)
4968{
4969	struct ctl_softc *ctl_softc;
4970	struct ctl_lun *lun;
4971
4972	ctl_softc = control_softc;
4973
4974	lun = (struct ctl_lun *)be_lun->ctl_lun;
4975
4976	mtx_lock(&lun->lun_lock);
4977	lun->flags &= ~CTL_LUN_OFFLINE;
4978	mtx_unlock(&lun->lun_lock);
4979
4980	return (0);
4981}
4982
4983int
4984ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4985{
4986	struct ctl_softc *ctl_softc;
4987	struct ctl_lun *lun;
4988
4989	ctl_softc = control_softc;
4990
4991	lun = (struct ctl_lun *)be_lun->ctl_lun;
4992
4993	mtx_lock(&lun->lun_lock);
4994
4995	/*
4996	 * The LUN needs to be disabled before it can be marked invalid.
4997	 */
4998	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4999		mtx_unlock(&lun->lun_lock);
5000		return (-1);
5001	}
5002	/*
5003	 * Mark the LUN invalid.
5004	 */
5005	lun->flags |= CTL_LUN_INVALID;
5006
5007	/*
5008	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5009	 * If we have something in the OOA queue, we'll free it when the
5010	 * last I/O completes.
5011	 */
5012	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5013		mtx_unlock(&lun->lun_lock);
5014		mtx_lock(&ctl_softc->ctl_lock);
5015		ctl_free_lun(lun);
5016		mtx_unlock(&ctl_softc->ctl_lock);
5017	} else
5018		mtx_unlock(&lun->lun_lock);
5019
5020	return (0);
5021}
5022
5023int
5024ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5025{
5026	struct ctl_softc *ctl_softc;
5027	struct ctl_lun *lun;
5028
5029	ctl_softc = control_softc;
5030	lun = (struct ctl_lun *)be_lun->ctl_lun;
5031
5032	mtx_lock(&lun->lun_lock);
5033	lun->flags |= CTL_LUN_INOPERABLE;
5034	mtx_unlock(&lun->lun_lock);
5035
5036	return (0);
5037}
5038
5039int
5040ctl_lun_operable(struct ctl_be_lun *be_lun)
5041{
5042	struct ctl_softc *ctl_softc;
5043	struct ctl_lun *lun;
5044
5045	ctl_softc = control_softc;
5046	lun = (struct ctl_lun *)be_lun->ctl_lun;
5047
5048	mtx_lock(&lun->lun_lock);
5049	lun->flags &= ~CTL_LUN_INOPERABLE;
5050	mtx_unlock(&lun->lun_lock);
5051
5052	return (0);
5053}
5054
5055int
5056ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5057		   int lock)
5058{
5059	struct ctl_softc *softc;
5060	struct ctl_lun *lun;
5061	struct copan_aps_subpage *current_sp;
5062	struct ctl_page_index *page_index;
5063	int i;
5064
5065	softc = control_softc;
5066
5067	mtx_lock(&softc->ctl_lock);
5068
5069	lun = (struct ctl_lun *)be_lun->ctl_lun;
5070	mtx_lock(&lun->lun_lock);
5071
5072	page_index = NULL;
5073	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5074		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5075		     APS_PAGE_CODE)
5076			continue;
5077
5078		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5079			continue;
5080		page_index = &lun->mode_pages.index[i];
5081	}
5082
5083	if (page_index == NULL) {
5084		mtx_unlock(&lun->lun_lock);
5085		mtx_unlock(&softc->ctl_lock);
5086		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5087		       (uintmax_t)lun->lun);
5088		return (1);
5089	}
5090#if 0
5091	if ((softc->aps_locked_lun != 0)
5092	 && (softc->aps_locked_lun != lun->lun)) {
5093		printf("%s: attempt to lock LUN %llu when %llu is already "
5094		       "locked\n");
5095		mtx_unlock(&lun->lun_lock);
5096		mtx_unlock(&softc->ctl_lock);
5097		return (1);
5098	}
5099#endif
5100
5101	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5102		(page_index->page_len * CTL_PAGE_CURRENT));
5103
5104	if (lock != 0) {
5105		current_sp->lock_active = APS_LOCK_ACTIVE;
5106		softc->aps_locked_lun = lun->lun;
5107	} else {
5108		current_sp->lock_active = 0;
5109		softc->aps_locked_lun = 0;
5110	}
5111
5112
5113	/*
5114	 * If we're in HA mode, try to send the lock message to the other
5115	 * side.
5116	 */
5117	if (ctl_is_single == 0) {
5118		int isc_retval;
5119		union ctl_ha_msg lock_msg;
5120
5121		lock_msg.hdr.nexus = *nexus;
5122		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5123		if (lock != 0)
5124			lock_msg.aps.lock_flag = 1;
5125		else
5126			lock_msg.aps.lock_flag = 0;
5127		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5128					 sizeof(lock_msg), 0);
5129		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5130			printf("%s: APS (lock=%d) error returned from "
5131			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5132			mtx_unlock(&lun->lun_lock);
5133			mtx_unlock(&softc->ctl_lock);
5134			return (1);
5135		}
5136	}
5137
5138	mtx_unlock(&lun->lun_lock);
5139	mtx_unlock(&softc->ctl_lock);
5140
5141	return (0);
5142}
5143
5144void
5145ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5146{
5147	struct ctl_lun *lun;
5148	struct ctl_softc *softc;
5149	int i;
5150
5151	softc = control_softc;
5152
5153	lun = (struct ctl_lun *)be_lun->ctl_lun;
5154
5155	mtx_lock(&lun->lun_lock);
5156
5157	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5158		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5159
5160	mtx_unlock(&lun->lun_lock);
5161}
5162
5163/*
5164 * Backend "memory move is complete" callback for requests that never
5165 * make it down to say RAIDCore's configuration code.
5166 */
5167int
5168ctl_config_move_done(union ctl_io *io)
5169{
5170	int retval;
5171
5172	retval = CTL_RETVAL_COMPLETE;
5173
5174
5175	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5176	/*
5177	 * XXX KDM this shouldn't happen, but what if it does?
5178	 */
5179	if (io->io_hdr.io_type != CTL_IO_SCSI)
5180		panic("I/O type isn't CTL_IO_SCSI!");
5181
5182	if ((io->io_hdr.port_status == 0)
5183	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5184	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5185		io->io_hdr.status = CTL_SUCCESS;
5186	else if ((io->io_hdr.port_status != 0)
5187	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5188	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5189		/*
5190		 * For hardware error sense keys, the sense key
5191		 * specific value is defined to be a retry count,
5192		 * but we use it to pass back an internal FETD
5193		 * error code.  XXX KDM  Hopefully the FETD is only
5194		 * using 16 bits for an error code, since that's
5195		 * all the space we have in the sks field.
5196		 */
5197		ctl_set_internal_failure(&io->scsiio,
5198					 /*sks_valid*/ 1,
5199					 /*retry_count*/
5200					 io->io_hdr.port_status);
5201		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5202			free(io->scsiio.kern_data_ptr, M_CTL);
5203		ctl_done(io);
5204		goto bailout;
5205	}
5206
5207	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5208	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5209	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5210		/*
5211		 * XXX KDM just assuming a single pointer here, and not a
5212		 * S/G list.  If we start using S/G lists for config data,
5213		 * we'll need to know how to clean them up here as well.
5214		 */
5215		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5216			free(io->scsiio.kern_data_ptr, M_CTL);
5217		/* Hopefully the user has already set the status... */
5218		ctl_done(io);
5219	} else {
5220		/*
5221		 * XXX KDM now we need to continue data movement.  Some
5222		 * options:
5223		 * - call ctl_scsiio() again?  We don't do this for data
5224		 *   writes, because for those at least we know ahead of
5225		 *   time where the write will go and how long it is.  For
5226		 *   config writes, though, that information is largely
5227		 *   contained within the write itself, thus we need to
5228		 *   parse out the data again.
5229		 *
5230		 * - Call some other function once the data is in?
5231		 */
5232
5233		/*
5234		 * XXX KDM call ctl_scsiio() again for now, and check flag
5235		 * bits to see whether we're allocated or not.
5236		 */
5237		retval = ctl_scsiio(&io->scsiio);
5238	}
5239bailout:
5240	return (retval);
5241}
5242
5243/*
5244 * This gets called by a backend driver when it is done with a
5245 * data_submit method.
5246 */
5247void
5248ctl_data_submit_done(union ctl_io *io)
5249{
5250	/*
5251	 * If the IO_CONT flag is set, we need to call the supplied
5252	 * function to continue processing the I/O, instead of completing
5253	 * the I/O just yet.
5254	 *
5255	 * If there is an error, though, we don't want to keep processing.
5256	 * Instead, just send status back to the initiator.
5257	 */
5258	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5259	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5260	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5261	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5262		io->scsiio.io_cont(io);
5263		return;
5264	}
5265	ctl_done(io);
5266}
5267
5268/*
5269 * This gets called by a backend driver when it is done with a
5270 * configuration write.
5271 */
5272void
5273ctl_config_write_done(union ctl_io *io)
5274{
5275	uint8_t *buf;
5276
5277	/*
5278	 * If the IO_CONT flag is set, we need to call the supplied
5279	 * function to continue processing the I/O, instead of completing
5280	 * the I/O just yet.
5281	 *
5282	 * If there is an error, though, we don't want to keep processing.
5283	 * Instead, just send status back to the initiator.
5284	 */
5285	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5286	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5287	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5288	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5289		io->scsiio.io_cont(io);
5290		return;
5291	}
5292	/*
5293	 * Since a configuration write can be done for commands that actually
5294	 * have data allocated, like write buffer, and commands that have
5295	 * no data, like start/stop unit, we need to check here.
5296	 */
5297	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5298		buf = io->scsiio.kern_data_ptr;
5299	else
5300		buf = NULL;
5301	ctl_done(io);
5302	if (buf)
5303		free(buf, M_CTL);
5304}
5305
5306/*
5307 * SCSI release command.
5308 */
5309int
5310ctl_scsi_release(struct ctl_scsiio *ctsio)
5311{
5312	int length, longid, thirdparty_id, resv_id;
5313	struct ctl_softc *ctl_softc;
5314	struct ctl_lun *lun;
5315	uint32_t residx;
5316
5317	length = 0;
5318	resv_id = 0;
5319
5320	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5321
5322	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5323	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5324	ctl_softc = control_softc;
5325
5326	switch (ctsio->cdb[0]) {
5327	case RELEASE_10: {
5328		struct scsi_release_10 *cdb;
5329
5330		cdb = (struct scsi_release_10 *)ctsio->cdb;
5331
5332		if (cdb->byte2 & SR10_LONGID)
5333			longid = 1;
5334		else
5335			thirdparty_id = cdb->thirdparty_id;
5336
5337		resv_id = cdb->resv_id;
5338		length = scsi_2btoul(cdb->length);
5339		break;
5340	}
5341	}
5342
5343
5344	/*
5345	 * XXX KDM right now, we only support LUN reservation.  We don't
5346	 * support 3rd party reservations, or extent reservations, which
5347	 * might actually need the parameter list.  If we've gotten this
5348	 * far, we've got a LUN reservation.  Anything else got kicked out
5349	 * above.  So, according to SPC, ignore the length.
5350	 */
5351	length = 0;
5352
5353	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5354	 && (length > 0)) {
5355		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5356		ctsio->kern_data_len = length;
5357		ctsio->kern_total_len = length;
5358		ctsio->kern_data_resid = 0;
5359		ctsio->kern_rel_offset = 0;
5360		ctsio->kern_sg_entries = 0;
5361		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5362		ctsio->be_move_done = ctl_config_move_done;
5363		ctl_datamove((union ctl_io *)ctsio);
5364
5365		return (CTL_RETVAL_COMPLETE);
5366	}
5367
5368	if (length > 0)
5369		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5370
5371	mtx_lock(&lun->lun_lock);
5372
5373	/*
5374	 * According to SPC, it is not an error for an intiator to attempt
5375	 * to release a reservation on a LUN that isn't reserved, or that
5376	 * is reserved by another initiator.  The reservation can only be
5377	 * released, though, by the initiator who made it or by one of
5378	 * several reset type events.
5379	 */
5380	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5381			lun->flags &= ~CTL_LUN_RESERVED;
5382
5383	mtx_unlock(&lun->lun_lock);
5384
5385	ctsio->scsi_status = SCSI_STATUS_OK;
5386	ctsio->io_hdr.status = CTL_SUCCESS;
5387
5388	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5389		free(ctsio->kern_data_ptr, M_CTL);
5390		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5391	}
5392
5393	ctl_done((union ctl_io *)ctsio);
5394	return (CTL_RETVAL_COMPLETE);
5395}
5396
5397int
5398ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5399{
5400	int extent, thirdparty, longid;
5401	int resv_id, length;
5402	uint64_t thirdparty_id;
5403	struct ctl_softc *ctl_softc;
5404	struct ctl_lun *lun;
5405	uint32_t residx;
5406
5407	extent = 0;
5408	thirdparty = 0;
5409	longid = 0;
5410	resv_id = 0;
5411	length = 0;
5412	thirdparty_id = 0;
5413
5414	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5415
5416	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5417	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5418	ctl_softc = control_softc;
5419
5420	switch (ctsio->cdb[0]) {
5421	case RESERVE_10: {
5422		struct scsi_reserve_10 *cdb;
5423
5424		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5425
5426		if (cdb->byte2 & SR10_LONGID)
5427			longid = 1;
5428		else
5429			thirdparty_id = cdb->thirdparty_id;
5430
5431		resv_id = cdb->resv_id;
5432		length = scsi_2btoul(cdb->length);
5433		break;
5434	}
5435	}
5436
5437	/*
5438	 * XXX KDM right now, we only support LUN reservation.  We don't
5439	 * support 3rd party reservations, or extent reservations, which
5440	 * might actually need the parameter list.  If we've gotten this
5441	 * far, we've got a LUN reservation.  Anything else got kicked out
5442	 * above.  So, according to SPC, ignore the length.
5443	 */
5444	length = 0;
5445
5446	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5447	 && (length > 0)) {
5448		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5449		ctsio->kern_data_len = length;
5450		ctsio->kern_total_len = length;
5451		ctsio->kern_data_resid = 0;
5452		ctsio->kern_rel_offset = 0;
5453		ctsio->kern_sg_entries = 0;
5454		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5455		ctsio->be_move_done = ctl_config_move_done;
5456		ctl_datamove((union ctl_io *)ctsio);
5457
5458		return (CTL_RETVAL_COMPLETE);
5459	}
5460
5461	if (length > 0)
5462		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5463
5464	mtx_lock(&lun->lun_lock);
5465	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5466		ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5467		ctsio->io_hdr.status = CTL_SCSI_ERROR;
5468		goto bailout;
5469	}
5470
5471	lun->flags |= CTL_LUN_RESERVED;
5472	lun->res_idx = residx;
5473
5474	ctsio->scsi_status = SCSI_STATUS_OK;
5475	ctsio->io_hdr.status = CTL_SUCCESS;
5476
5477bailout:
5478	mtx_unlock(&lun->lun_lock);
5479
5480	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5481		free(ctsio->kern_data_ptr, M_CTL);
5482		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5483	}
5484
5485	ctl_done((union ctl_io *)ctsio);
5486	return (CTL_RETVAL_COMPLETE);
5487}
5488
5489int
5490ctl_start_stop(struct ctl_scsiio *ctsio)
5491{
5492	struct scsi_start_stop_unit *cdb;
5493	struct ctl_lun *lun;
5494	struct ctl_softc *ctl_softc;
5495	int retval;
5496
5497	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5498
5499	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5500	ctl_softc = control_softc;
5501	retval = 0;
5502
5503	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5504
5505	/*
5506	 * XXX KDM
5507	 * We don't support the immediate bit on a stop unit.  In order to
5508	 * do that, we would need to code up a way to know that a stop is
5509	 * pending, and hold off any new commands until it completes, one
5510	 * way or another.  Then we could accept or reject those commands
5511	 * depending on its status.  We would almost need to do the reverse
5512	 * of what we do below for an immediate start -- return the copy of
5513	 * the ctl_io to the FETD with status to send to the host (and to
5514	 * free the copy!) and then free the original I/O once the stop
5515	 * actually completes.  That way, the OOA queue mechanism can work
5516	 * to block commands that shouldn't proceed.  Another alternative
5517	 * would be to put the copy in the queue in place of the original,
5518	 * and return the original back to the caller.  That could be
5519	 * slightly safer..
5520	 */
5521	if ((cdb->byte2 & SSS_IMMED)
5522	 && ((cdb->how & SSS_START) == 0)) {
5523		ctl_set_invalid_field(ctsio,
5524				      /*sks_valid*/ 1,
5525				      /*command*/ 1,
5526				      /*field*/ 1,
5527				      /*bit_valid*/ 1,
5528				      /*bit*/ 0);
5529		ctl_done((union ctl_io *)ctsio);
5530		return (CTL_RETVAL_COMPLETE);
5531	}
5532
5533	if ((lun->flags & CTL_LUN_PR_RESERVED)
5534	 && ((cdb->how & SSS_START)==0)) {
5535		uint32_t residx;
5536
5537		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5538		if (lun->pr_keys[residx] == 0
5539		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5540
5541			ctl_set_reservation_conflict(ctsio);
5542			ctl_done((union ctl_io *)ctsio);
5543			return (CTL_RETVAL_COMPLETE);
5544		}
5545	}
5546
5547	/*
5548	 * If there is no backend on this device, we can't start or stop
5549	 * it.  In theory we shouldn't get any start/stop commands in the
5550	 * first place at this level if the LUN doesn't have a backend.
5551	 * That should get stopped by the command decode code.
5552	 */
5553	if (lun->backend == NULL) {
5554		ctl_set_invalid_opcode(ctsio);
5555		ctl_done((union ctl_io *)ctsio);
5556		return (CTL_RETVAL_COMPLETE);
5557	}
5558
5559	/*
5560	 * XXX KDM Copan-specific offline behavior.
5561	 * Figure out a reasonable way to port this?
5562	 */
5563#ifdef NEEDTOPORT
5564	mtx_lock(&lun->lun_lock);
5565
5566	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5567	 && (lun->flags & CTL_LUN_OFFLINE)) {
5568		/*
5569		 * If the LUN is offline, and the on/offline bit isn't set,
5570		 * reject the start or stop.  Otherwise, let it through.
5571		 */
5572		mtx_unlock(&lun->lun_lock);
5573		ctl_set_lun_not_ready(ctsio);
5574		ctl_done((union ctl_io *)ctsio);
5575	} else {
5576		mtx_unlock(&lun->lun_lock);
5577#endif /* NEEDTOPORT */
5578		/*
5579		 * This could be a start or a stop when we're online,
5580		 * or a stop/offline or start/online.  A start or stop when
5581		 * we're offline is covered in the case above.
5582		 */
5583		/*
5584		 * In the non-immediate case, we send the request to
5585		 * the backend and return status to the user when
5586		 * it is done.
5587		 *
5588		 * In the immediate case, we allocate a new ctl_io
5589		 * to hold a copy of the request, and send that to
5590		 * the backend.  We then set good status on the
5591		 * user's request and return it immediately.
5592		 */
5593		if (cdb->byte2 & SSS_IMMED) {
5594			union ctl_io *new_io;
5595
5596			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5597			if (new_io == NULL) {
5598				ctl_set_busy(ctsio);
5599				ctl_done((union ctl_io *)ctsio);
5600			} else {
5601				ctl_copy_io((union ctl_io *)ctsio,
5602					    new_io);
5603				retval = lun->backend->config_write(new_io);
5604				ctl_set_success(ctsio);
5605				ctl_done((union ctl_io *)ctsio);
5606			}
5607		} else {
5608			retval = lun->backend->config_write(
5609				(union ctl_io *)ctsio);
5610		}
5611#ifdef NEEDTOPORT
5612	}
5613#endif
5614	return (retval);
5615}
5616
5617/*
5618 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5619 * we don't really do anything with the LBA and length fields if the user
5620 * passes them in.  Instead we'll just flush out the cache for the entire
5621 * LUN.
5622 */
5623int
5624ctl_sync_cache(struct ctl_scsiio *ctsio)
5625{
5626	struct ctl_lun *lun;
5627	struct ctl_softc *ctl_softc;
5628	uint64_t starting_lba;
5629	uint32_t block_count;
5630	int retval;
5631
5632	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5633
5634	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5635	ctl_softc = control_softc;
5636	retval = 0;
5637
5638	switch (ctsio->cdb[0]) {
5639	case SYNCHRONIZE_CACHE: {
5640		struct scsi_sync_cache *cdb;
5641		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5642
5643		starting_lba = scsi_4btoul(cdb->begin_lba);
5644		block_count = scsi_2btoul(cdb->lb_count);
5645		break;
5646	}
5647	case SYNCHRONIZE_CACHE_16: {
5648		struct scsi_sync_cache_16 *cdb;
5649		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5650
5651		starting_lba = scsi_8btou64(cdb->begin_lba);
5652		block_count = scsi_4btoul(cdb->lb_count);
5653		break;
5654	}
5655	default:
5656		ctl_set_invalid_opcode(ctsio);
5657		ctl_done((union ctl_io *)ctsio);
5658		goto bailout;
5659		break; /* NOTREACHED */
5660	}
5661
5662	/*
5663	 * We check the LBA and length, but don't do anything with them.
5664	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5665	 * get flushed.  This check will just help satisfy anyone who wants
5666	 * to see an error for an out of range LBA.
5667	 */
5668	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5669		ctl_set_lba_out_of_range(ctsio);
5670		ctl_done((union ctl_io *)ctsio);
5671		goto bailout;
5672	}
5673
5674	/*
5675	 * If this LUN has no backend, we can't flush the cache anyway.
5676	 */
5677	if (lun->backend == NULL) {
5678		ctl_set_invalid_opcode(ctsio);
5679		ctl_done((union ctl_io *)ctsio);
5680		goto bailout;
5681	}
5682
5683	/*
5684	 * Check to see whether we're configured to send the SYNCHRONIZE
5685	 * CACHE command directly to the back end.
5686	 */
5687	mtx_lock(&lun->lun_lock);
5688	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5689	 && (++(lun->sync_count) >= lun->sync_interval)) {
5690		lun->sync_count = 0;
5691		mtx_unlock(&lun->lun_lock);
5692		retval = lun->backend->config_write((union ctl_io *)ctsio);
5693	} else {
5694		mtx_unlock(&lun->lun_lock);
5695		ctl_set_success(ctsio);
5696		ctl_done((union ctl_io *)ctsio);
5697	}
5698
5699bailout:
5700
5701	return (retval);
5702}
5703
5704int
5705ctl_format(struct ctl_scsiio *ctsio)
5706{
5707	struct scsi_format *cdb;
5708	struct ctl_lun *lun;
5709	struct ctl_softc *ctl_softc;
5710	int length, defect_list_len;
5711
5712	CTL_DEBUG_PRINT(("ctl_format\n"));
5713
5714	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5715	ctl_softc = control_softc;
5716
5717	cdb = (struct scsi_format *)ctsio->cdb;
5718
5719	length = 0;
5720	if (cdb->byte2 & SF_FMTDATA) {
5721		if (cdb->byte2 & SF_LONGLIST)
5722			length = sizeof(struct scsi_format_header_long);
5723		else
5724			length = sizeof(struct scsi_format_header_short);
5725	}
5726
5727	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5728	 && (length > 0)) {
5729		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5730		ctsio->kern_data_len = length;
5731		ctsio->kern_total_len = length;
5732		ctsio->kern_data_resid = 0;
5733		ctsio->kern_rel_offset = 0;
5734		ctsio->kern_sg_entries = 0;
5735		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5736		ctsio->be_move_done = ctl_config_move_done;
5737		ctl_datamove((union ctl_io *)ctsio);
5738
5739		return (CTL_RETVAL_COMPLETE);
5740	}
5741
5742	defect_list_len = 0;
5743
5744	if (cdb->byte2 & SF_FMTDATA) {
5745		if (cdb->byte2 & SF_LONGLIST) {
5746			struct scsi_format_header_long *header;
5747
5748			header = (struct scsi_format_header_long *)
5749				ctsio->kern_data_ptr;
5750
5751			defect_list_len = scsi_4btoul(header->defect_list_len);
5752			if (defect_list_len != 0) {
5753				ctl_set_invalid_field(ctsio,
5754						      /*sks_valid*/ 1,
5755						      /*command*/ 0,
5756						      /*field*/ 2,
5757						      /*bit_valid*/ 0,
5758						      /*bit*/ 0);
5759				goto bailout;
5760			}
5761		} else {
5762			struct scsi_format_header_short *header;
5763
5764			header = (struct scsi_format_header_short *)
5765				ctsio->kern_data_ptr;
5766
5767			defect_list_len = scsi_2btoul(header->defect_list_len);
5768			if (defect_list_len != 0) {
5769				ctl_set_invalid_field(ctsio,
5770						      /*sks_valid*/ 1,
5771						      /*command*/ 0,
5772						      /*field*/ 2,
5773						      /*bit_valid*/ 0,
5774						      /*bit*/ 0);
5775				goto bailout;
5776			}
5777		}
5778	}
5779
5780	/*
5781	 * The format command will clear out the "Medium format corrupted"
5782	 * status if set by the configuration code.  That status is really
5783	 * just a way to notify the host that we have lost the media, and
5784	 * get them to issue a command that will basically make them think
5785	 * they're blowing away the media.
5786	 */
5787	mtx_lock(&lun->lun_lock);
5788	lun->flags &= ~CTL_LUN_INOPERABLE;
5789	mtx_unlock(&lun->lun_lock);
5790
5791	ctsio->scsi_status = SCSI_STATUS_OK;
5792	ctsio->io_hdr.status = CTL_SUCCESS;
5793bailout:
5794
5795	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5796		free(ctsio->kern_data_ptr, M_CTL);
5797		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5798	}
5799
5800	ctl_done((union ctl_io *)ctsio);
5801	return (CTL_RETVAL_COMPLETE);
5802}
5803
5804int
5805ctl_read_buffer(struct ctl_scsiio *ctsio)
5806{
5807	struct scsi_read_buffer *cdb;
5808	struct ctl_lun *lun;
5809	int buffer_offset, len;
5810	static uint8_t descr[4];
5811	static uint8_t echo_descr[4] = { 0 };
5812
5813	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5814
5815	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5816	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5817
5818	if (lun->flags & CTL_LUN_PR_RESERVED) {
5819		uint32_t residx;
5820
5821		/*
5822		 * XXX KDM need a lock here.
5823		 */
5824		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5825		if ((lun->res_type == SPR_TYPE_EX_AC
5826		  && residx != lun->pr_res_idx)
5827		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5828		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5829		  && lun->pr_keys[residx] == 0)) {
5830			ctl_set_reservation_conflict(ctsio);
5831			ctl_done((union ctl_io *)ctsio);
5832			return (CTL_RETVAL_COMPLETE);
5833	        }
5834	}
5835
5836	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5837	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5838	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5839		ctl_set_invalid_field(ctsio,
5840				      /*sks_valid*/ 1,
5841				      /*command*/ 1,
5842				      /*field*/ 1,
5843				      /*bit_valid*/ 1,
5844				      /*bit*/ 4);
5845		ctl_done((union ctl_io *)ctsio);
5846		return (CTL_RETVAL_COMPLETE);
5847	}
5848
5849	len = scsi_3btoul(cdb->length);
5850	buffer_offset = scsi_3btoul(cdb->offset);
5851
5852	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5853		ctl_set_invalid_field(ctsio,
5854				      /*sks_valid*/ 1,
5855				      /*command*/ 1,
5856				      /*field*/ 6,
5857				      /*bit_valid*/ 0,
5858				      /*bit*/ 0);
5859		ctl_done((union ctl_io *)ctsio);
5860		return (CTL_RETVAL_COMPLETE);
5861	}
5862
5863	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5864		descr[0] = 0;
5865		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5866		ctsio->kern_data_ptr = descr;
5867		len = min(len, sizeof(descr));
5868	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5869		ctsio->kern_data_ptr = echo_descr;
5870		len = min(len, sizeof(echo_descr));
5871	} else
5872		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5873	ctsio->kern_data_len = len;
5874	ctsio->kern_total_len = len;
5875	ctsio->kern_data_resid = 0;
5876	ctsio->kern_rel_offset = 0;
5877	ctsio->kern_sg_entries = 0;
5878	ctsio->be_move_done = ctl_config_move_done;
5879	ctl_datamove((union ctl_io *)ctsio);
5880
5881	return (CTL_RETVAL_COMPLETE);
5882}
5883
5884int
5885ctl_write_buffer(struct ctl_scsiio *ctsio)
5886{
5887	struct scsi_write_buffer *cdb;
5888	struct ctl_lun *lun;
5889	int buffer_offset, len;
5890
5891	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5892
5893	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5894	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5895
5896	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5897		ctl_set_invalid_field(ctsio,
5898				      /*sks_valid*/ 1,
5899				      /*command*/ 1,
5900				      /*field*/ 1,
5901				      /*bit_valid*/ 1,
5902				      /*bit*/ 4);
5903		ctl_done((union ctl_io *)ctsio);
5904		return (CTL_RETVAL_COMPLETE);
5905	}
5906
5907	len = scsi_3btoul(cdb->length);
5908	buffer_offset = scsi_3btoul(cdb->offset);
5909
5910	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5911		ctl_set_invalid_field(ctsio,
5912				      /*sks_valid*/ 1,
5913				      /*command*/ 1,
5914				      /*field*/ 6,
5915				      /*bit_valid*/ 0,
5916				      /*bit*/ 0);
5917		ctl_done((union ctl_io *)ctsio);
5918		return (CTL_RETVAL_COMPLETE);
5919	}
5920
5921	/*
5922	 * If we've got a kernel request that hasn't been malloced yet,
5923	 * malloc it and tell the caller the data buffer is here.
5924	 */
5925	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5926		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5927		ctsio->kern_data_len = len;
5928		ctsio->kern_total_len = len;
5929		ctsio->kern_data_resid = 0;
5930		ctsio->kern_rel_offset = 0;
5931		ctsio->kern_sg_entries = 0;
5932		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5933		ctsio->be_move_done = ctl_config_move_done;
5934		ctl_datamove((union ctl_io *)ctsio);
5935
5936		return (CTL_RETVAL_COMPLETE);
5937	}
5938
5939	ctl_done((union ctl_io *)ctsio);
5940
5941	return (CTL_RETVAL_COMPLETE);
5942}
5943
5944int
5945ctl_write_same(struct ctl_scsiio *ctsio)
5946{
5947	struct ctl_lun *lun;
5948	struct ctl_lba_len_flags *lbalen;
5949	uint64_t lba;
5950	uint32_t num_blocks;
5951	int len, retval;
5952	uint8_t byte2;
5953
5954	retval = CTL_RETVAL_COMPLETE;
5955
5956	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5957
5958	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5959
5960	switch (ctsio->cdb[0]) {
5961	case WRITE_SAME_10: {
5962		struct scsi_write_same_10 *cdb;
5963
5964		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5965
5966		lba = scsi_4btoul(cdb->addr);
5967		num_blocks = scsi_2btoul(cdb->length);
5968		byte2 = cdb->byte2;
5969		break;
5970	}
5971	case WRITE_SAME_16: {
5972		struct scsi_write_same_16 *cdb;
5973
5974		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5975
5976		lba = scsi_8btou64(cdb->addr);
5977		num_blocks = scsi_4btoul(cdb->length);
5978		byte2 = cdb->byte2;
5979		break;
5980	}
5981	default:
5982		/*
5983		 * We got a command we don't support.  This shouldn't
5984		 * happen, commands should be filtered out above us.
5985		 */
5986		ctl_set_invalid_opcode(ctsio);
5987		ctl_done((union ctl_io *)ctsio);
5988
5989		return (CTL_RETVAL_COMPLETE);
5990		break; /* NOTREACHED */
5991	}
5992
5993	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5994	if ((byte2 & SWS_UNMAP) == 0 &&
5995	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5996		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5997		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5998		ctl_done((union ctl_io *)ctsio);
5999		return (CTL_RETVAL_COMPLETE);
6000	}
6001
6002	/*
6003	 * The first check is to make sure we're in bounds, the second
6004	 * check is to catch wrap-around problems.  If the lba + num blocks
6005	 * is less than the lba, then we've wrapped around and the block
6006	 * range is invalid anyway.
6007	 */
6008	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6009	 || ((lba + num_blocks) < lba)) {
6010		ctl_set_lba_out_of_range(ctsio);
6011		ctl_done((union ctl_io *)ctsio);
6012		return (CTL_RETVAL_COMPLETE);
6013	}
6014
6015	/* Zero number of blocks means "to the last logical block" */
6016	if (num_blocks == 0) {
6017		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6018			ctl_set_invalid_field(ctsio,
6019					      /*sks_valid*/ 0,
6020					      /*command*/ 1,
6021					      /*field*/ 0,
6022					      /*bit_valid*/ 0,
6023					      /*bit*/ 0);
6024			ctl_done((union ctl_io *)ctsio);
6025			return (CTL_RETVAL_COMPLETE);
6026		}
6027		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6028	}
6029
6030	len = lun->be_lun->blocksize;
6031
6032	/*
6033	 * If we've got a kernel request that hasn't been malloced yet,
6034	 * malloc it and tell the caller the data buffer is here.
6035	 */
6036	if ((byte2 & SWS_NDOB) == 0 &&
6037	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6038		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6039		ctsio->kern_data_len = len;
6040		ctsio->kern_total_len = len;
6041		ctsio->kern_data_resid = 0;
6042		ctsio->kern_rel_offset = 0;
6043		ctsio->kern_sg_entries = 0;
6044		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6045		ctsio->be_move_done = ctl_config_move_done;
6046		ctl_datamove((union ctl_io *)ctsio);
6047
6048		return (CTL_RETVAL_COMPLETE);
6049	}
6050
6051	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6052	lbalen->lba = lba;
6053	lbalen->len = num_blocks;
6054	lbalen->flags = byte2;
6055	retval = lun->backend->config_write((union ctl_io *)ctsio);
6056
6057	return (retval);
6058}
6059
6060int
6061ctl_unmap(struct ctl_scsiio *ctsio)
6062{
6063	struct ctl_lun *lun;
6064	struct scsi_unmap *cdb;
6065	struct ctl_ptr_len_flags *ptrlen;
6066	struct scsi_unmap_header *hdr;
6067	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6068	uint64_t lba;
6069	uint32_t num_blocks;
6070	int len, retval;
6071	uint8_t byte2;
6072
6073	retval = CTL_RETVAL_COMPLETE;
6074
6075	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6076
6077	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6078	cdb = (struct scsi_unmap *)ctsio->cdb;
6079
6080	len = scsi_2btoul(cdb->length);
6081	byte2 = cdb->byte2;
6082
6083	/*
6084	 * If we've got a kernel request that hasn't been malloced yet,
6085	 * malloc it and tell the caller the data buffer is here.
6086	 */
6087	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6088		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6089		ctsio->kern_data_len = len;
6090		ctsio->kern_total_len = len;
6091		ctsio->kern_data_resid = 0;
6092		ctsio->kern_rel_offset = 0;
6093		ctsio->kern_sg_entries = 0;
6094		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6095		ctsio->be_move_done = ctl_config_move_done;
6096		ctl_datamove((union ctl_io *)ctsio);
6097
6098		return (CTL_RETVAL_COMPLETE);
6099	}
6100
6101	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6102	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6103	if (len < sizeof (*hdr) ||
6104	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6105	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6106	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6107		ctl_set_invalid_field(ctsio,
6108				      /*sks_valid*/ 0,
6109				      /*command*/ 0,
6110				      /*field*/ 0,
6111				      /*bit_valid*/ 0,
6112				      /*bit*/ 0);
6113		ctl_done((union ctl_io *)ctsio);
6114		return (CTL_RETVAL_COMPLETE);
6115	}
6116	len = scsi_2btoul(hdr->desc_length);
6117	buf = (struct scsi_unmap_desc *)(hdr + 1);
6118	end = buf + len / sizeof(*buf);
6119
6120	endnz = buf;
6121	for (range = buf; range < end; range++) {
6122		lba = scsi_8btou64(range->lba);
6123		num_blocks = scsi_4btoul(range->length);
6124		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6125		 || ((lba + num_blocks) < lba)) {
6126			ctl_set_lba_out_of_range(ctsio);
6127			ctl_done((union ctl_io *)ctsio);
6128			return (CTL_RETVAL_COMPLETE);
6129		}
6130		if (num_blocks != 0)
6131			endnz = range + 1;
6132	}
6133
6134	/*
6135	 * Block backend can not handle zero last range.
6136	 * Filter it out and return if there is nothing left.
6137	 */
6138	len = (uint8_t *)endnz - (uint8_t *)buf;
6139	if (len == 0) {
6140		ctl_set_success(ctsio);
6141		ctl_done((union ctl_io *)ctsio);
6142		return (CTL_RETVAL_COMPLETE);
6143	}
6144
6145	mtx_lock(&lun->lun_lock);
6146	ptrlen = (struct ctl_ptr_len_flags *)
6147	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6148	ptrlen->ptr = (void *)buf;
6149	ptrlen->len = len;
6150	ptrlen->flags = byte2;
6151	ctl_check_blocked(lun);
6152	mtx_unlock(&lun->lun_lock);
6153
6154	retval = lun->backend->config_write((union ctl_io *)ctsio);
6155	return (retval);
6156}
6157
6158/*
6159 * Note that this function currently doesn't actually do anything inside
6160 * CTL to enforce things if the DQue bit is turned on.
6161 *
6162 * Also note that this function can't be used in the default case, because
6163 * the DQue bit isn't set in the changeable mask for the control mode page
6164 * anyway.  This is just here as an example for how to implement a page
6165 * handler, and a placeholder in case we want to allow the user to turn
6166 * tagged queueing on and off.
6167 *
6168 * The D_SENSE bit handling is functional, however, and will turn
6169 * descriptor sense on and off for a given LUN.
6170 */
6171int
6172ctl_control_page_handler(struct ctl_scsiio *ctsio,
6173			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6174{
6175	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6176	struct ctl_lun *lun;
6177	struct ctl_softc *softc;
6178	int set_ua;
6179	uint32_t initidx;
6180
6181	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6182	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6183	set_ua = 0;
6184
6185	user_cp = (struct scsi_control_page *)page_ptr;
6186	current_cp = (struct scsi_control_page *)
6187		(page_index->page_data + (page_index->page_len *
6188		CTL_PAGE_CURRENT));
6189	saved_cp = (struct scsi_control_page *)
6190		(page_index->page_data + (page_index->page_len *
6191		CTL_PAGE_SAVED));
6192
6193	softc = control_softc;
6194
6195	mtx_lock(&lun->lun_lock);
6196	if (((current_cp->rlec & SCP_DSENSE) == 0)
6197	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6198		/*
6199		 * Descriptor sense is currently turned off and the user
6200		 * wants to turn it on.
6201		 */
6202		current_cp->rlec |= SCP_DSENSE;
6203		saved_cp->rlec |= SCP_DSENSE;
6204		lun->flags |= CTL_LUN_SENSE_DESC;
6205		set_ua = 1;
6206	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6207		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6208		/*
6209		 * Descriptor sense is currently turned on, and the user
6210		 * wants to turn it off.
6211		 */
6212		current_cp->rlec &= ~SCP_DSENSE;
6213		saved_cp->rlec &= ~SCP_DSENSE;
6214		lun->flags &= ~CTL_LUN_SENSE_DESC;
6215		set_ua = 1;
6216	}
6217	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6218	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6219		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6220		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6221		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6222		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6223		set_ua = 1;
6224	}
6225	if ((current_cp->eca_and_aen & SCP_SWP) !=
6226	    (user_cp->eca_and_aen & SCP_SWP)) {
6227		current_cp->eca_and_aen &= ~SCP_SWP;
6228		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6229		saved_cp->eca_and_aen &= ~SCP_SWP;
6230		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6231		set_ua = 1;
6232	}
6233	if (set_ua != 0) {
6234		int i;
6235		/*
6236		 * Let other initiators know that the mode
6237		 * parameters for this LUN have changed.
6238		 */
6239		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6240			if (i == initidx)
6241				continue;
6242
6243			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6244		}
6245	}
6246	mtx_unlock(&lun->lun_lock);
6247
6248	return (0);
6249}
6250
6251int
6252ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6253		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6254{
6255	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6256	struct ctl_lun *lun;
6257	int set_ua;
6258	uint32_t initidx;
6259
6260	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6261	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6262	set_ua = 0;
6263
6264	user_cp = (struct scsi_caching_page *)page_ptr;
6265	current_cp = (struct scsi_caching_page *)
6266		(page_index->page_data + (page_index->page_len *
6267		CTL_PAGE_CURRENT));
6268	saved_cp = (struct scsi_caching_page *)
6269		(page_index->page_data + (page_index->page_len *
6270		CTL_PAGE_SAVED));
6271
6272	mtx_lock(&lun->lun_lock);
6273	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6274	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6275		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6276		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6277		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6278		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6279		set_ua = 1;
6280	}
6281	if (set_ua != 0) {
6282		int i;
6283		/*
6284		 * Let other initiators know that the mode
6285		 * parameters for this LUN have changed.
6286		 */
6287		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6288			if (i == initidx)
6289				continue;
6290
6291			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6292		}
6293	}
6294	mtx_unlock(&lun->lun_lock);
6295
6296	return (0);
6297}
6298
6299int
6300ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6301		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6302{
6303	return (0);
6304}
6305
6306int
6307ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6308			   struct ctl_page_index *page_index, int pc)
6309{
6310	struct copan_power_subpage *page;
6311
6312	page = (struct copan_power_subpage *)page_index->page_data +
6313		(page_index->page_len * pc);
6314
6315	switch (pc) {
6316	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6317		/*
6318		 * We don't update the changable bits for this page.
6319		 */
6320		break;
6321	case SMS_PAGE_CTRL_CURRENT >> 6:
6322	case SMS_PAGE_CTRL_DEFAULT >> 6:
6323	case SMS_PAGE_CTRL_SAVED >> 6:
6324#ifdef NEEDTOPORT
6325		ctl_update_power_subpage(page);
6326#endif
6327		break;
6328	default:
6329#ifdef NEEDTOPORT
6330		EPRINT(0, "Invalid PC %d!!", pc);
6331#endif
6332		break;
6333	}
6334	return (0);
6335}
6336
6337
6338int
6339ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6340		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6341{
6342	struct copan_aps_subpage *user_sp;
6343	struct copan_aps_subpage *current_sp;
6344	union ctl_modepage_info *modepage_info;
6345	struct ctl_softc *softc;
6346	struct ctl_lun *lun;
6347	int retval;
6348
6349	retval = CTL_RETVAL_COMPLETE;
6350	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6351		     (page_index->page_len * CTL_PAGE_CURRENT));
6352	softc = control_softc;
6353	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6354
6355	user_sp = (struct copan_aps_subpage *)page_ptr;
6356
6357	modepage_info = (union ctl_modepage_info *)
6358		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6359
6360	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6361	modepage_info->header.subpage = page_index->subpage;
6362	modepage_info->aps.lock_active = user_sp->lock_active;
6363
6364	mtx_lock(&softc->ctl_lock);
6365
6366	/*
6367	 * If there is a request to lock the LUN and another LUN is locked
6368	 * this is an error. If the requested LUN is already locked ignore
6369	 * the request. If no LUN is locked attempt to lock it.
6370	 * if there is a request to unlock the LUN and the LUN is currently
6371	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6372	 * if another LUN is locked or no LUN is locked.
6373	 */
6374	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6375		if (softc->aps_locked_lun == lun->lun) {
6376			/*
6377			 * This LUN is already locked, so we're done.
6378			 */
6379			retval = CTL_RETVAL_COMPLETE;
6380		} else if (softc->aps_locked_lun == 0) {
6381			/*
6382			 * No one has the lock, pass the request to the
6383			 * backend.
6384			 */
6385			retval = lun->backend->config_write(
6386				(union ctl_io *)ctsio);
6387		} else {
6388			/*
6389			 * Someone else has the lock, throw out the request.
6390			 */
6391			ctl_set_already_locked(ctsio);
6392			free(ctsio->kern_data_ptr, M_CTL);
6393			ctl_done((union ctl_io *)ctsio);
6394
6395			/*
6396			 * Set the return value so that ctl_do_mode_select()
6397			 * won't try to complete the command.  We already
6398			 * completed it here.
6399			 */
6400			retval = CTL_RETVAL_ERROR;
6401		}
6402	} else if (softc->aps_locked_lun == lun->lun) {
6403		/*
6404		 * This LUN is locked, so pass the unlock request to the
6405		 * backend.
6406		 */
6407		retval = lun->backend->config_write((union ctl_io *)ctsio);
6408	}
6409	mtx_unlock(&softc->ctl_lock);
6410
6411	return (retval);
6412}
6413
6414int
6415ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6416				struct ctl_page_index *page_index,
6417				uint8_t *page_ptr)
6418{
6419	uint8_t *c;
6420	int i;
6421
6422	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6423	ctl_time_io_secs =
6424		(c[0] << 8) |
6425		(c[1] << 0) |
6426		0;
6427	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6428	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6429	printf("page data:");
6430	for (i=0; i<8; i++)
6431		printf(" %.2x",page_ptr[i]);
6432	printf("\n");
6433	return (0);
6434}
6435
6436int
6437ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6438			       struct ctl_page_index *page_index,
6439			       int pc)
6440{
6441	struct copan_debugconf_subpage *page;
6442
6443	page = (struct copan_debugconf_subpage *)page_index->page_data +
6444		(page_index->page_len * pc);
6445
6446	switch (pc) {
6447	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6448	case SMS_PAGE_CTRL_DEFAULT >> 6:
6449	case SMS_PAGE_CTRL_SAVED >> 6:
6450		/*
6451		 * We don't update the changable or default bits for this page.
6452		 */
6453		break;
6454	case SMS_PAGE_CTRL_CURRENT >> 6:
6455		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6456		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6457		break;
6458	default:
6459#ifdef NEEDTOPORT
6460		EPRINT(0, "Invalid PC %d!!", pc);
6461#endif /* NEEDTOPORT */
6462		break;
6463	}
6464	return (0);
6465}
6466
6467
6468static int
6469ctl_do_mode_select(union ctl_io *io)
6470{
6471	struct scsi_mode_page_header *page_header;
6472	struct ctl_page_index *page_index;
6473	struct ctl_scsiio *ctsio;
6474	int control_dev, page_len;
6475	int page_len_offset, page_len_size;
6476	union ctl_modepage_info *modepage_info;
6477	struct ctl_lun *lun;
6478	int *len_left, *len_used;
6479	int retval, i;
6480
6481	ctsio = &io->scsiio;
6482	page_index = NULL;
6483	page_len = 0;
6484	retval = CTL_RETVAL_COMPLETE;
6485
6486	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6487
6488	if (lun->be_lun->lun_type != T_DIRECT)
6489		control_dev = 1;
6490	else
6491		control_dev = 0;
6492
6493	modepage_info = (union ctl_modepage_info *)
6494		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6495	len_left = &modepage_info->header.len_left;
6496	len_used = &modepage_info->header.len_used;
6497
6498do_next_page:
6499
6500	page_header = (struct scsi_mode_page_header *)
6501		(ctsio->kern_data_ptr + *len_used);
6502
6503	if (*len_left == 0) {
6504		free(ctsio->kern_data_ptr, M_CTL);
6505		ctl_set_success(ctsio);
6506		ctl_done((union ctl_io *)ctsio);
6507		return (CTL_RETVAL_COMPLETE);
6508	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6509
6510		free(ctsio->kern_data_ptr, M_CTL);
6511		ctl_set_param_len_error(ctsio);
6512		ctl_done((union ctl_io *)ctsio);
6513		return (CTL_RETVAL_COMPLETE);
6514
6515	} else if ((page_header->page_code & SMPH_SPF)
6516		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6517
6518		free(ctsio->kern_data_ptr, M_CTL);
6519		ctl_set_param_len_error(ctsio);
6520		ctl_done((union ctl_io *)ctsio);
6521		return (CTL_RETVAL_COMPLETE);
6522	}
6523
6524
6525	/*
6526	 * XXX KDM should we do something with the block descriptor?
6527	 */
6528	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6529
6530		if ((control_dev != 0)
6531		 && (lun->mode_pages.index[i].page_flags &
6532		     CTL_PAGE_FLAG_DISK_ONLY))
6533			continue;
6534
6535		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6536		    (page_header->page_code & SMPH_PC_MASK))
6537			continue;
6538
6539		/*
6540		 * If neither page has a subpage code, then we've got a
6541		 * match.
6542		 */
6543		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6544		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6545			page_index = &lun->mode_pages.index[i];
6546			page_len = page_header->page_length;
6547			break;
6548		}
6549
6550		/*
6551		 * If both pages have subpages, then the subpage numbers
6552		 * have to match.
6553		 */
6554		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6555		  && (page_header->page_code & SMPH_SPF)) {
6556			struct scsi_mode_page_header_sp *sph;
6557
6558			sph = (struct scsi_mode_page_header_sp *)page_header;
6559
6560			if (lun->mode_pages.index[i].subpage ==
6561			    sph->subpage) {
6562				page_index = &lun->mode_pages.index[i];
6563				page_len = scsi_2btoul(sph->page_length);
6564				break;
6565			}
6566		}
6567	}
6568
6569	/*
6570	 * If we couldn't find the page, or if we don't have a mode select
6571	 * handler for it, send back an error to the user.
6572	 */
6573	if ((page_index == NULL)
6574	 || (page_index->select_handler == NULL)) {
6575		ctl_set_invalid_field(ctsio,
6576				      /*sks_valid*/ 1,
6577				      /*command*/ 0,
6578				      /*field*/ *len_used,
6579				      /*bit_valid*/ 0,
6580				      /*bit*/ 0);
6581		free(ctsio->kern_data_ptr, M_CTL);
6582		ctl_done((union ctl_io *)ctsio);
6583		return (CTL_RETVAL_COMPLETE);
6584	}
6585
6586	if (page_index->page_code & SMPH_SPF) {
6587		page_len_offset = 2;
6588		page_len_size = 2;
6589	} else {
6590		page_len_size = 1;
6591		page_len_offset = 1;
6592	}
6593
6594	/*
6595	 * If the length the initiator gives us isn't the one we specify in
6596	 * the mode page header, or if they didn't specify enough data in
6597	 * the CDB to avoid truncating this page, kick out the request.
6598	 */
6599	if ((page_len != (page_index->page_len - page_len_offset -
6600			  page_len_size))
6601	 || (*len_left < page_index->page_len)) {
6602
6603
6604		ctl_set_invalid_field(ctsio,
6605				      /*sks_valid*/ 1,
6606				      /*command*/ 0,
6607				      /*field*/ *len_used + page_len_offset,
6608				      /*bit_valid*/ 0,
6609				      /*bit*/ 0);
6610		free(ctsio->kern_data_ptr, M_CTL);
6611		ctl_done((union ctl_io *)ctsio);
6612		return (CTL_RETVAL_COMPLETE);
6613	}
6614
6615	/*
6616	 * Run through the mode page, checking to make sure that the bits
6617	 * the user changed are actually legal for him to change.
6618	 */
6619	for (i = 0; i < page_index->page_len; i++) {
6620		uint8_t *user_byte, *change_mask, *current_byte;
6621		int bad_bit;
6622		int j;
6623
6624		user_byte = (uint8_t *)page_header + i;
6625		change_mask = page_index->page_data +
6626			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6627		current_byte = page_index->page_data +
6628			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6629
6630		/*
6631		 * Check to see whether the user set any bits in this byte
6632		 * that he is not allowed to set.
6633		 */
6634		if ((*user_byte & ~(*change_mask)) ==
6635		    (*current_byte & ~(*change_mask)))
6636			continue;
6637
6638		/*
6639		 * Go through bit by bit to determine which one is illegal.
6640		 */
6641		bad_bit = 0;
6642		for (j = 7; j >= 0; j--) {
6643			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6644			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6645				bad_bit = i;
6646				break;
6647			}
6648		}
6649		ctl_set_invalid_field(ctsio,
6650				      /*sks_valid*/ 1,
6651				      /*command*/ 0,
6652				      /*field*/ *len_used + i,
6653				      /*bit_valid*/ 1,
6654				      /*bit*/ bad_bit);
6655		free(ctsio->kern_data_ptr, M_CTL);
6656		ctl_done((union ctl_io *)ctsio);
6657		return (CTL_RETVAL_COMPLETE);
6658	}
6659
6660	/*
6661	 * Decrement these before we call the page handler, since we may
6662	 * end up getting called back one way or another before the handler
6663	 * returns to this context.
6664	 */
6665	*len_left -= page_index->page_len;
6666	*len_used += page_index->page_len;
6667
6668	retval = page_index->select_handler(ctsio, page_index,
6669					    (uint8_t *)page_header);
6670
6671	/*
6672	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6673	 * wait until this queued command completes to finish processing
6674	 * the mode page.  If it returns anything other than
6675	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6676	 * already set the sense information, freed the data pointer, and
6677	 * completed the io for us.
6678	 */
6679	if (retval != CTL_RETVAL_COMPLETE)
6680		goto bailout_no_done;
6681
6682	/*
6683	 * If the initiator sent us more than one page, parse the next one.
6684	 */
6685	if (*len_left > 0)
6686		goto do_next_page;
6687
6688	ctl_set_success(ctsio);
6689	free(ctsio->kern_data_ptr, M_CTL);
6690	ctl_done((union ctl_io *)ctsio);
6691
6692bailout_no_done:
6693
6694	return (CTL_RETVAL_COMPLETE);
6695
6696}
6697
6698int
6699ctl_mode_select(struct ctl_scsiio *ctsio)
6700{
6701	int param_len, pf, sp;
6702	int header_size, bd_len;
6703	int len_left, len_used;
6704	struct ctl_page_index *page_index;
6705	struct ctl_lun *lun;
6706	int control_dev, page_len;
6707	union ctl_modepage_info *modepage_info;
6708	int retval;
6709
6710	pf = 0;
6711	sp = 0;
6712	page_len = 0;
6713	len_used = 0;
6714	len_left = 0;
6715	retval = 0;
6716	bd_len = 0;
6717	page_index = NULL;
6718
6719	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6720
6721	if (lun->be_lun->lun_type != T_DIRECT)
6722		control_dev = 1;
6723	else
6724		control_dev = 0;
6725
6726	switch (ctsio->cdb[0]) {
6727	case MODE_SELECT_6: {
6728		struct scsi_mode_select_6 *cdb;
6729
6730		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6731
6732		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6733		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6734
6735		param_len = cdb->length;
6736		header_size = sizeof(struct scsi_mode_header_6);
6737		break;
6738	}
6739	case MODE_SELECT_10: {
6740		struct scsi_mode_select_10 *cdb;
6741
6742		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6743
6744		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6745		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6746
6747		param_len = scsi_2btoul(cdb->length);
6748		header_size = sizeof(struct scsi_mode_header_10);
6749		break;
6750	}
6751	default:
6752		ctl_set_invalid_opcode(ctsio);
6753		ctl_done((union ctl_io *)ctsio);
6754		return (CTL_RETVAL_COMPLETE);
6755		break; /* NOTREACHED */
6756	}
6757
6758	/*
6759	 * From SPC-3:
6760	 * "A parameter list length of zero indicates that the Data-Out Buffer
6761	 * shall be empty. This condition shall not be considered as an error."
6762	 */
6763	if (param_len == 0) {
6764		ctl_set_success(ctsio);
6765		ctl_done((union ctl_io *)ctsio);
6766		return (CTL_RETVAL_COMPLETE);
6767	}
6768
6769	/*
6770	 * Since we'll hit this the first time through, prior to
6771	 * allocation, we don't need to free a data buffer here.
6772	 */
6773	if (param_len < header_size) {
6774		ctl_set_param_len_error(ctsio);
6775		ctl_done((union ctl_io *)ctsio);
6776		return (CTL_RETVAL_COMPLETE);
6777	}
6778
6779	/*
6780	 * Allocate the data buffer and grab the user's data.  In theory,
6781	 * we shouldn't have to sanity check the parameter list length here
6782	 * because the maximum size is 64K.  We should be able to malloc
6783	 * that much without too many problems.
6784	 */
6785	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6786		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6787		ctsio->kern_data_len = param_len;
6788		ctsio->kern_total_len = param_len;
6789		ctsio->kern_data_resid = 0;
6790		ctsio->kern_rel_offset = 0;
6791		ctsio->kern_sg_entries = 0;
6792		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6793		ctsio->be_move_done = ctl_config_move_done;
6794		ctl_datamove((union ctl_io *)ctsio);
6795
6796		return (CTL_RETVAL_COMPLETE);
6797	}
6798
6799	switch (ctsio->cdb[0]) {
6800	case MODE_SELECT_6: {
6801		struct scsi_mode_header_6 *mh6;
6802
6803		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6804		bd_len = mh6->blk_desc_len;
6805		break;
6806	}
6807	case MODE_SELECT_10: {
6808		struct scsi_mode_header_10 *mh10;
6809
6810		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6811		bd_len = scsi_2btoul(mh10->blk_desc_len);
6812		break;
6813	}
6814	default:
6815		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6816		break;
6817	}
6818
6819	if (param_len < (header_size + bd_len)) {
6820		free(ctsio->kern_data_ptr, M_CTL);
6821		ctl_set_param_len_error(ctsio);
6822		ctl_done((union ctl_io *)ctsio);
6823		return (CTL_RETVAL_COMPLETE);
6824	}
6825
6826	/*
6827	 * Set the IO_CONT flag, so that if this I/O gets passed to
6828	 * ctl_config_write_done(), it'll get passed back to
6829	 * ctl_do_mode_select() for further processing, or completion if
6830	 * we're all done.
6831	 */
6832	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6833	ctsio->io_cont = ctl_do_mode_select;
6834
6835	modepage_info = (union ctl_modepage_info *)
6836		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6837
6838	memset(modepage_info, 0, sizeof(*modepage_info));
6839
6840	len_left = param_len - header_size - bd_len;
6841	len_used = header_size + bd_len;
6842
6843	modepage_info->header.len_left = len_left;
6844	modepage_info->header.len_used = len_used;
6845
6846	return (ctl_do_mode_select((union ctl_io *)ctsio));
6847}
6848
6849int
6850ctl_mode_sense(struct ctl_scsiio *ctsio)
6851{
6852	struct ctl_lun *lun;
6853	int pc, page_code, dbd, llba, subpage;
6854	int alloc_len, page_len, header_len, total_len;
6855	struct scsi_mode_block_descr *block_desc;
6856	struct ctl_page_index *page_index;
6857	int control_dev;
6858
6859	dbd = 0;
6860	llba = 0;
6861	block_desc = NULL;
6862	page_index = NULL;
6863
6864	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6865
6866	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6867
6868	if (lun->be_lun->lun_type != T_DIRECT)
6869		control_dev = 1;
6870	else
6871		control_dev = 0;
6872
6873	if (lun->flags & CTL_LUN_PR_RESERVED) {
6874		uint32_t residx;
6875
6876		/*
6877		 * XXX KDM need a lock here.
6878		 */
6879		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6880		if ((lun->res_type == SPR_TYPE_EX_AC
6881		  && residx != lun->pr_res_idx)
6882		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6883		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6884		  && lun->pr_keys[residx] == 0)) {
6885			ctl_set_reservation_conflict(ctsio);
6886			ctl_done((union ctl_io *)ctsio);
6887			return (CTL_RETVAL_COMPLETE);
6888		}
6889	}
6890
6891	switch (ctsio->cdb[0]) {
6892	case MODE_SENSE_6: {
6893		struct scsi_mode_sense_6 *cdb;
6894
6895		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6896
6897		header_len = sizeof(struct scsi_mode_hdr_6);
6898		if (cdb->byte2 & SMS_DBD)
6899			dbd = 1;
6900		else
6901			header_len += sizeof(struct scsi_mode_block_descr);
6902
6903		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6904		page_code = cdb->page & SMS_PAGE_CODE;
6905		subpage = cdb->subpage;
6906		alloc_len = cdb->length;
6907		break;
6908	}
6909	case MODE_SENSE_10: {
6910		struct scsi_mode_sense_10 *cdb;
6911
6912		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6913
6914		header_len = sizeof(struct scsi_mode_hdr_10);
6915
6916		if (cdb->byte2 & SMS_DBD)
6917			dbd = 1;
6918		else
6919			header_len += sizeof(struct scsi_mode_block_descr);
6920		if (cdb->byte2 & SMS10_LLBAA)
6921			llba = 1;
6922		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6923		page_code = cdb->page & SMS_PAGE_CODE;
6924		subpage = cdb->subpage;
6925		alloc_len = scsi_2btoul(cdb->length);
6926		break;
6927	}
6928	default:
6929		ctl_set_invalid_opcode(ctsio);
6930		ctl_done((union ctl_io *)ctsio);
6931		return (CTL_RETVAL_COMPLETE);
6932		break; /* NOTREACHED */
6933	}
6934
6935	/*
6936	 * We have to make a first pass through to calculate the size of
6937	 * the pages that match the user's query.  Then we allocate enough
6938	 * memory to hold it, and actually copy the data into the buffer.
6939	 */
6940	switch (page_code) {
6941	case SMS_ALL_PAGES_PAGE: {
6942		int i;
6943
6944		page_len = 0;
6945
6946		/*
6947		 * At the moment, values other than 0 and 0xff here are
6948		 * reserved according to SPC-3.
6949		 */
6950		if ((subpage != SMS_SUBPAGE_PAGE_0)
6951		 && (subpage != SMS_SUBPAGE_ALL)) {
6952			ctl_set_invalid_field(ctsio,
6953					      /*sks_valid*/ 1,
6954					      /*command*/ 1,
6955					      /*field*/ 3,
6956					      /*bit_valid*/ 0,
6957					      /*bit*/ 0);
6958			ctl_done((union ctl_io *)ctsio);
6959			return (CTL_RETVAL_COMPLETE);
6960		}
6961
6962		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6963			if ((control_dev != 0)
6964			 && (lun->mode_pages.index[i].page_flags &
6965			     CTL_PAGE_FLAG_DISK_ONLY))
6966				continue;
6967
6968			/*
6969			 * We don't use this subpage if the user didn't
6970			 * request all subpages.
6971			 */
6972			if ((lun->mode_pages.index[i].subpage != 0)
6973			 && (subpage == SMS_SUBPAGE_PAGE_0))
6974				continue;
6975
6976#if 0
6977			printf("found page %#x len %d\n",
6978			       lun->mode_pages.index[i].page_code &
6979			       SMPH_PC_MASK,
6980			       lun->mode_pages.index[i].page_len);
6981#endif
6982			page_len += lun->mode_pages.index[i].page_len;
6983		}
6984		break;
6985	}
6986	default: {
6987		int i;
6988
6989		page_len = 0;
6990
6991		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6992			/* Look for the right page code */
6993			if ((lun->mode_pages.index[i].page_code &
6994			     SMPH_PC_MASK) != page_code)
6995				continue;
6996
6997			/* Look for the right subpage or the subpage wildcard*/
6998			if ((lun->mode_pages.index[i].subpage != subpage)
6999			 && (subpage != SMS_SUBPAGE_ALL))
7000				continue;
7001
7002			/* Make sure the page is supported for this dev type */
7003			if ((control_dev != 0)
7004			 && (lun->mode_pages.index[i].page_flags &
7005			     CTL_PAGE_FLAG_DISK_ONLY))
7006				continue;
7007
7008#if 0
7009			printf("found page %#x len %d\n",
7010			       lun->mode_pages.index[i].page_code &
7011			       SMPH_PC_MASK,
7012			       lun->mode_pages.index[i].page_len);
7013#endif
7014
7015			page_len += lun->mode_pages.index[i].page_len;
7016		}
7017
7018		if (page_len == 0) {
7019			ctl_set_invalid_field(ctsio,
7020					      /*sks_valid*/ 1,
7021					      /*command*/ 1,
7022					      /*field*/ 2,
7023					      /*bit_valid*/ 1,
7024					      /*bit*/ 5);
7025			ctl_done((union ctl_io *)ctsio);
7026			return (CTL_RETVAL_COMPLETE);
7027		}
7028		break;
7029	}
7030	}
7031
7032	total_len = header_len + page_len;
7033#if 0
7034	printf("header_len = %d, page_len = %d, total_len = %d\n",
7035	       header_len, page_len, total_len);
7036#endif
7037
7038	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7039	ctsio->kern_sg_entries = 0;
7040	ctsio->kern_data_resid = 0;
7041	ctsio->kern_rel_offset = 0;
7042	if (total_len < alloc_len) {
7043		ctsio->residual = alloc_len - total_len;
7044		ctsio->kern_data_len = total_len;
7045		ctsio->kern_total_len = total_len;
7046	} else {
7047		ctsio->residual = 0;
7048		ctsio->kern_data_len = alloc_len;
7049		ctsio->kern_total_len = alloc_len;
7050	}
7051
7052	switch (ctsio->cdb[0]) {
7053	case MODE_SENSE_6: {
7054		struct scsi_mode_hdr_6 *header;
7055
7056		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7057
7058		header->datalen = ctl_min(total_len - 1, 254);
7059		if (control_dev == 0) {
7060			header->dev_specific = 0x10; /* DPOFUA */
7061			if ((lun->flags & CTL_LUN_READONLY) ||
7062			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7063			    .eca_and_aen & SCP_SWP) != 0)
7064				    header->dev_specific |= 0x80; /* WP */
7065		}
7066		if (dbd)
7067			header->block_descr_len = 0;
7068		else
7069			header->block_descr_len =
7070				sizeof(struct scsi_mode_block_descr);
7071		block_desc = (struct scsi_mode_block_descr *)&header[1];
7072		break;
7073	}
7074	case MODE_SENSE_10: {
7075		struct scsi_mode_hdr_10 *header;
7076		int datalen;
7077
7078		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7079
7080		datalen = ctl_min(total_len - 2, 65533);
7081		scsi_ulto2b(datalen, header->datalen);
7082		if (control_dev == 0) {
7083			header->dev_specific = 0x10; /* DPOFUA */
7084			if ((lun->flags & CTL_LUN_READONLY) ||
7085			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7086			    .eca_and_aen & SCP_SWP) != 0)
7087				    header->dev_specific |= 0x80; /* WP */
7088		}
7089		if (dbd)
7090			scsi_ulto2b(0, header->block_descr_len);
7091		else
7092			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7093				    header->block_descr_len);
7094		block_desc = (struct scsi_mode_block_descr *)&header[1];
7095		break;
7096	}
7097	default:
7098		panic("invalid CDB type %#x", ctsio->cdb[0]);
7099		break; /* NOTREACHED */
7100	}
7101
7102	/*
7103	 * If we've got a disk, use its blocksize in the block
7104	 * descriptor.  Otherwise, just set it to 0.
7105	 */
7106	if (dbd == 0) {
7107		if (control_dev == 0)
7108			scsi_ulto3b(lun->be_lun->blocksize,
7109				    block_desc->block_len);
7110		else
7111			scsi_ulto3b(0, block_desc->block_len);
7112	}
7113
7114	switch (page_code) {
7115	case SMS_ALL_PAGES_PAGE: {
7116		int i, data_used;
7117
7118		data_used = header_len;
7119		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7120			struct ctl_page_index *page_index;
7121
7122			page_index = &lun->mode_pages.index[i];
7123
7124			if ((control_dev != 0)
7125			 && (page_index->page_flags &
7126			    CTL_PAGE_FLAG_DISK_ONLY))
7127				continue;
7128
7129			/*
7130			 * We don't use this subpage if the user didn't
7131			 * request all subpages.  We already checked (above)
7132			 * to make sure the user only specified a subpage
7133			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7134			 */
7135			if ((page_index->subpage != 0)
7136			 && (subpage == SMS_SUBPAGE_PAGE_0))
7137				continue;
7138
7139			/*
7140			 * Call the handler, if it exists, to update the
7141			 * page to the latest values.
7142			 */
7143			if (page_index->sense_handler != NULL)
7144				page_index->sense_handler(ctsio, page_index,pc);
7145
7146			memcpy(ctsio->kern_data_ptr + data_used,
7147			       page_index->page_data +
7148			       (page_index->page_len * pc),
7149			       page_index->page_len);
7150			data_used += page_index->page_len;
7151		}
7152		break;
7153	}
7154	default: {
7155		int i, data_used;
7156
7157		data_used = header_len;
7158
7159		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7160			struct ctl_page_index *page_index;
7161
7162			page_index = &lun->mode_pages.index[i];
7163
7164			/* Look for the right page code */
7165			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7166				continue;
7167
7168			/* Look for the right subpage or the subpage wildcard*/
7169			if ((page_index->subpage != subpage)
7170			 && (subpage != SMS_SUBPAGE_ALL))
7171				continue;
7172
7173			/* Make sure the page is supported for this dev type */
7174			if ((control_dev != 0)
7175			 && (page_index->page_flags &
7176			     CTL_PAGE_FLAG_DISK_ONLY))
7177				continue;
7178
7179			/*
7180			 * Call the handler, if it exists, to update the
7181			 * page to the latest values.
7182			 */
7183			if (page_index->sense_handler != NULL)
7184				page_index->sense_handler(ctsio, page_index,pc);
7185
7186			memcpy(ctsio->kern_data_ptr + data_used,
7187			       page_index->page_data +
7188			       (page_index->page_len * pc),
7189			       page_index->page_len);
7190			data_used += page_index->page_len;
7191		}
7192		break;
7193	}
7194	}
7195
7196	ctsio->scsi_status = SCSI_STATUS_OK;
7197
7198	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7199	ctsio->be_move_done = ctl_config_move_done;
7200	ctl_datamove((union ctl_io *)ctsio);
7201
7202	return (CTL_RETVAL_COMPLETE);
7203}
7204
7205int
7206ctl_read_capacity(struct ctl_scsiio *ctsio)
7207{
7208	struct scsi_read_capacity *cdb;
7209	struct scsi_read_capacity_data *data;
7210	struct ctl_lun *lun;
7211	uint32_t lba;
7212
7213	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7214
7215	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7216
7217	lba = scsi_4btoul(cdb->addr);
7218	if (((cdb->pmi & SRC_PMI) == 0)
7219	 && (lba != 0)) {
7220		ctl_set_invalid_field(/*ctsio*/ ctsio,
7221				      /*sks_valid*/ 1,
7222				      /*command*/ 1,
7223				      /*field*/ 2,
7224				      /*bit_valid*/ 0,
7225				      /*bit*/ 0);
7226		ctl_done((union ctl_io *)ctsio);
7227		return (CTL_RETVAL_COMPLETE);
7228	}
7229
7230	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7231
7232	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7233	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7234	ctsio->residual = 0;
7235	ctsio->kern_data_len = sizeof(*data);
7236	ctsio->kern_total_len = sizeof(*data);
7237	ctsio->kern_data_resid = 0;
7238	ctsio->kern_rel_offset = 0;
7239	ctsio->kern_sg_entries = 0;
7240
7241	/*
7242	 * If the maximum LBA is greater than 0xfffffffe, the user must
7243	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7244	 * serivce action set.
7245	 */
7246	if (lun->be_lun->maxlba > 0xfffffffe)
7247		scsi_ulto4b(0xffffffff, data->addr);
7248	else
7249		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7250
7251	/*
7252	 * XXX KDM this may not be 512 bytes...
7253	 */
7254	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7255
7256	ctsio->scsi_status = SCSI_STATUS_OK;
7257
7258	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7259	ctsio->be_move_done = ctl_config_move_done;
7260	ctl_datamove((union ctl_io *)ctsio);
7261
7262	return (CTL_RETVAL_COMPLETE);
7263}
7264
7265int
7266ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7267{
7268	struct scsi_read_capacity_16 *cdb;
7269	struct scsi_read_capacity_data_long *data;
7270	struct ctl_lun *lun;
7271	uint64_t lba;
7272	uint32_t alloc_len;
7273
7274	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7275
7276	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7277
7278	alloc_len = scsi_4btoul(cdb->alloc_len);
7279	lba = scsi_8btou64(cdb->addr);
7280
7281	if ((cdb->reladr & SRC16_PMI)
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_long *)ctsio->kern_data_ptr;
7297
7298	if (sizeof(*data) < alloc_len) {
7299		ctsio->residual = alloc_len - sizeof(*data);
7300		ctsio->kern_data_len = sizeof(*data);
7301		ctsio->kern_total_len = sizeof(*data);
7302	} else {
7303		ctsio->residual = 0;
7304		ctsio->kern_data_len = alloc_len;
7305		ctsio->kern_total_len = alloc_len;
7306	}
7307	ctsio->kern_data_resid = 0;
7308	ctsio->kern_rel_offset = 0;
7309	ctsio->kern_sg_entries = 0;
7310
7311	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7312	/* XXX KDM this may not be 512 bytes... */
7313	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7314	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7315	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7316	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7317		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
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_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7330{
7331	struct scsi_maintenance_in *cdb;
7332	int retval;
7333	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7334	int num_target_port_groups, num_target_ports, single;
7335	struct ctl_lun *lun;
7336	struct ctl_softc *softc;
7337	struct ctl_port *port;
7338	struct scsi_target_group_data *rtg_ptr;
7339	struct scsi_target_group_data_extended *rtg_ext_ptr;
7340	struct scsi_target_port_group_descriptor *tpg_desc;
7341
7342	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7343
7344	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7345	softc = control_softc;
7346	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7347
7348	retval = CTL_RETVAL_COMPLETE;
7349
7350	switch (cdb->byte2 & STG_PDF_MASK) {
7351	case STG_PDF_LENGTH:
7352		ext = 0;
7353		break;
7354	case STG_PDF_EXTENDED:
7355		ext = 1;
7356		break;
7357	default:
7358		ctl_set_invalid_field(/*ctsio*/ ctsio,
7359				      /*sks_valid*/ 1,
7360				      /*command*/ 1,
7361				      /*field*/ 2,
7362				      /*bit_valid*/ 1,
7363				      /*bit*/ 5);
7364		ctl_done((union ctl_io *)ctsio);
7365		return(retval);
7366	}
7367
7368	single = ctl_is_single;
7369	if (single)
7370		num_target_port_groups = 1;
7371	else
7372		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7373	num_target_ports = 0;
7374	mtx_lock(&softc->ctl_lock);
7375	STAILQ_FOREACH(port, &softc->port_list, links) {
7376		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7377			continue;
7378		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7379			continue;
7380		num_target_ports++;
7381	}
7382	mtx_unlock(&softc->ctl_lock);
7383
7384	if (ext)
7385		total_len = sizeof(struct scsi_target_group_data_extended);
7386	else
7387		total_len = sizeof(struct scsi_target_group_data);
7388	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7389		num_target_port_groups +
7390	    sizeof(struct scsi_target_port_descriptor) *
7391		num_target_ports * num_target_port_groups;
7392
7393	alloc_len = scsi_4btoul(cdb->length);
7394
7395	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7396
7397	ctsio->kern_sg_entries = 0;
7398
7399	if (total_len < alloc_len) {
7400		ctsio->residual = alloc_len - total_len;
7401		ctsio->kern_data_len = total_len;
7402		ctsio->kern_total_len = total_len;
7403	} else {
7404		ctsio->residual = 0;
7405		ctsio->kern_data_len = alloc_len;
7406		ctsio->kern_total_len = alloc_len;
7407	}
7408	ctsio->kern_data_resid = 0;
7409	ctsio->kern_rel_offset = 0;
7410
7411	if (ext) {
7412		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7413		    ctsio->kern_data_ptr;
7414		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7415		rtg_ext_ptr->format_type = 0x10;
7416		rtg_ext_ptr->implicit_transition_time = 0;
7417		tpg_desc = &rtg_ext_ptr->groups[0];
7418	} else {
7419		rtg_ptr = (struct scsi_target_group_data *)
7420		    ctsio->kern_data_ptr;
7421		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7422		tpg_desc = &rtg_ptr->groups[0];
7423	}
7424
7425	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7426	mtx_lock(&softc->ctl_lock);
7427	for (g = 0; g < num_target_port_groups; g++) {
7428		if (g == pg)
7429			tpg_desc->pref_state = TPG_PRIMARY |
7430			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7431		else
7432			tpg_desc->pref_state =
7433			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7434		tpg_desc->support = TPG_AO_SUP;
7435		if (!single)
7436			tpg_desc->support |= TPG_AN_SUP;
7437		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7438		tpg_desc->status = TPG_IMPLICIT;
7439		pc = 0;
7440		STAILQ_FOREACH(port, &softc->port_list, links) {
7441			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7442				continue;
7443			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7444			    CTL_MAX_LUNS)
7445				continue;
7446			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7447			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7448			    relative_target_port_identifier);
7449			pc++;
7450		}
7451		tpg_desc->target_port_count = pc;
7452		tpg_desc = (struct scsi_target_port_group_descriptor *)
7453		    &tpg_desc->descriptors[pc];
7454	}
7455	mtx_unlock(&softc->ctl_lock);
7456
7457	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7458	ctsio->be_move_done = ctl_config_move_done;
7459
7460	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7461			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7462			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7463			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7464			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7465
7466	ctl_datamove((union ctl_io *)ctsio);
7467	return(retval);
7468}
7469
7470int
7471ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7472{
7473	struct ctl_lun *lun;
7474	struct scsi_report_supported_opcodes *cdb;
7475	const struct ctl_cmd_entry *entry, *sentry;
7476	struct scsi_report_supported_opcodes_all *all;
7477	struct scsi_report_supported_opcodes_descr *descr;
7478	struct scsi_report_supported_opcodes_one *one;
7479	int retval;
7480	int alloc_len, total_len;
7481	int opcode, service_action, i, j, num;
7482
7483	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7484
7485	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7486	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7487
7488	retval = CTL_RETVAL_COMPLETE;
7489
7490	opcode = cdb->requested_opcode;
7491	service_action = scsi_2btoul(cdb->requested_service_action);
7492	switch (cdb->options & RSO_OPTIONS_MASK) {
7493	case RSO_OPTIONS_ALL:
7494		num = 0;
7495		for (i = 0; i < 256; i++) {
7496			entry = &ctl_cmd_table[i];
7497			if (entry->flags & CTL_CMD_FLAG_SA5) {
7498				for (j = 0; j < 32; j++) {
7499					sentry = &((const struct ctl_cmd_entry *)
7500					    entry->execute)[j];
7501					if (ctl_cmd_applicable(
7502					    lun->be_lun->lun_type, sentry))
7503						num++;
7504				}
7505			} else {
7506				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7507				    entry))
7508					num++;
7509			}
7510		}
7511		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7512		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7513		break;
7514	case RSO_OPTIONS_OC:
7515		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7516			ctl_set_invalid_field(/*ctsio*/ ctsio,
7517					      /*sks_valid*/ 1,
7518					      /*command*/ 1,
7519					      /*field*/ 2,
7520					      /*bit_valid*/ 1,
7521					      /*bit*/ 2);
7522			ctl_done((union ctl_io *)ctsio);
7523			return (CTL_RETVAL_COMPLETE);
7524		}
7525		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7526		break;
7527	case RSO_OPTIONS_OC_SA:
7528		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7529		    service_action >= 32) {
7530			ctl_set_invalid_field(/*ctsio*/ ctsio,
7531					      /*sks_valid*/ 1,
7532					      /*command*/ 1,
7533					      /*field*/ 2,
7534					      /*bit_valid*/ 1,
7535					      /*bit*/ 2);
7536			ctl_done((union ctl_io *)ctsio);
7537			return (CTL_RETVAL_COMPLETE);
7538		}
7539		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7540		break;
7541	default:
7542		ctl_set_invalid_field(/*ctsio*/ ctsio,
7543				      /*sks_valid*/ 1,
7544				      /*command*/ 1,
7545				      /*field*/ 2,
7546				      /*bit_valid*/ 1,
7547				      /*bit*/ 2);
7548		ctl_done((union ctl_io *)ctsio);
7549		return (CTL_RETVAL_COMPLETE);
7550	}
7551
7552	alloc_len = scsi_4btoul(cdb->length);
7553
7554	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7555
7556	ctsio->kern_sg_entries = 0;
7557
7558	if (total_len < alloc_len) {
7559		ctsio->residual = alloc_len - total_len;
7560		ctsio->kern_data_len = total_len;
7561		ctsio->kern_total_len = total_len;
7562	} else {
7563		ctsio->residual = 0;
7564		ctsio->kern_data_len = alloc_len;
7565		ctsio->kern_total_len = alloc_len;
7566	}
7567	ctsio->kern_data_resid = 0;
7568	ctsio->kern_rel_offset = 0;
7569
7570	switch (cdb->options & RSO_OPTIONS_MASK) {
7571	case RSO_OPTIONS_ALL:
7572		all = (struct scsi_report_supported_opcodes_all *)
7573		    ctsio->kern_data_ptr;
7574		num = 0;
7575		for (i = 0; i < 256; i++) {
7576			entry = &ctl_cmd_table[i];
7577			if (entry->flags & CTL_CMD_FLAG_SA5) {
7578				for (j = 0; j < 32; j++) {
7579					sentry = &((const struct ctl_cmd_entry *)
7580					    entry->execute)[j];
7581					if (!ctl_cmd_applicable(
7582					    lun->be_lun->lun_type, sentry))
7583						continue;
7584					descr = &all->descr[num++];
7585					descr->opcode = i;
7586					scsi_ulto2b(j, descr->service_action);
7587					descr->flags = RSO_SERVACTV;
7588					scsi_ulto2b(sentry->length,
7589					    descr->cdb_length);
7590				}
7591			} else {
7592				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7593				    entry))
7594					continue;
7595				descr = &all->descr[num++];
7596				descr->opcode = i;
7597				scsi_ulto2b(0, descr->service_action);
7598				descr->flags = 0;
7599				scsi_ulto2b(entry->length, descr->cdb_length);
7600			}
7601		}
7602		scsi_ulto4b(
7603		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7604		    all->length);
7605		break;
7606	case RSO_OPTIONS_OC:
7607		one = (struct scsi_report_supported_opcodes_one *)
7608		    ctsio->kern_data_ptr;
7609		entry = &ctl_cmd_table[opcode];
7610		goto fill_one;
7611	case RSO_OPTIONS_OC_SA:
7612		one = (struct scsi_report_supported_opcodes_one *)
7613		    ctsio->kern_data_ptr;
7614		entry = &ctl_cmd_table[opcode];
7615		entry = &((const struct ctl_cmd_entry *)
7616		    entry->execute)[service_action];
7617fill_one:
7618		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7619			one->support = 3;
7620			scsi_ulto2b(entry->length, one->cdb_length);
7621			one->cdb_usage[0] = opcode;
7622			memcpy(&one->cdb_usage[1], entry->usage,
7623			    entry->length - 1);
7624		} else
7625			one->support = 1;
7626		break;
7627	}
7628
7629	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7630	ctsio->be_move_done = ctl_config_move_done;
7631
7632	ctl_datamove((union ctl_io *)ctsio);
7633	return(retval);
7634}
7635
7636int
7637ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7638{
7639	struct ctl_lun *lun;
7640	struct scsi_report_supported_tmf *cdb;
7641	struct scsi_report_supported_tmf_data *data;
7642	int retval;
7643	int alloc_len, total_len;
7644
7645	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7646
7647	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7648	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7649
7650	retval = CTL_RETVAL_COMPLETE;
7651
7652	total_len = sizeof(struct scsi_report_supported_tmf_data);
7653	alloc_len = scsi_4btoul(cdb->length);
7654
7655	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7656
7657	ctsio->kern_sg_entries = 0;
7658
7659	if (total_len < alloc_len) {
7660		ctsio->residual = alloc_len - total_len;
7661		ctsio->kern_data_len = total_len;
7662		ctsio->kern_total_len = total_len;
7663	} else {
7664		ctsio->residual = 0;
7665		ctsio->kern_data_len = alloc_len;
7666		ctsio->kern_total_len = alloc_len;
7667	}
7668	ctsio->kern_data_resid = 0;
7669	ctsio->kern_rel_offset = 0;
7670
7671	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7672	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7673	data->byte2 |= RST_ITNRS;
7674
7675	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7676	ctsio->be_move_done = ctl_config_move_done;
7677
7678	ctl_datamove((union ctl_io *)ctsio);
7679	return (retval);
7680}
7681
7682int
7683ctl_report_timestamp(struct ctl_scsiio *ctsio)
7684{
7685	struct ctl_lun *lun;
7686	struct scsi_report_timestamp *cdb;
7687	struct scsi_report_timestamp_data *data;
7688	struct timeval tv;
7689	int64_t timestamp;
7690	int retval;
7691	int alloc_len, total_len;
7692
7693	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7694
7695	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7696	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7697
7698	retval = CTL_RETVAL_COMPLETE;
7699
7700	total_len = sizeof(struct scsi_report_timestamp_data);
7701	alloc_len = scsi_4btoul(cdb->length);
7702
7703	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7704
7705	ctsio->kern_sg_entries = 0;
7706
7707	if (total_len < alloc_len) {
7708		ctsio->residual = alloc_len - total_len;
7709		ctsio->kern_data_len = total_len;
7710		ctsio->kern_total_len = total_len;
7711	} else {
7712		ctsio->residual = 0;
7713		ctsio->kern_data_len = alloc_len;
7714		ctsio->kern_total_len = alloc_len;
7715	}
7716	ctsio->kern_data_resid = 0;
7717	ctsio->kern_rel_offset = 0;
7718
7719	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7720	scsi_ulto2b(sizeof(*data) - 2, data->length);
7721	data->origin = RTS_ORIG_OUTSIDE;
7722	getmicrotime(&tv);
7723	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7724	scsi_ulto4b(timestamp >> 16, data->timestamp);
7725	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7726
7727	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7728	ctsio->be_move_done = ctl_config_move_done;
7729
7730	ctl_datamove((union ctl_io *)ctsio);
7731	return (retval);
7732}
7733
7734int
7735ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7736{
7737	struct scsi_per_res_in *cdb;
7738	int alloc_len, total_len = 0;
7739	/* struct scsi_per_res_in_rsrv in_data; */
7740	struct ctl_lun *lun;
7741	struct ctl_softc *softc;
7742
7743	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7744
7745	softc = control_softc;
7746
7747	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7748
7749	alloc_len = scsi_2btoul(cdb->length);
7750
7751	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7752
7753retry:
7754	mtx_lock(&lun->lun_lock);
7755	switch (cdb->action) {
7756	case SPRI_RK: /* read keys */
7757		total_len = sizeof(struct scsi_per_res_in_keys) +
7758			lun->pr_key_count *
7759			sizeof(struct scsi_per_res_key);
7760		break;
7761	case SPRI_RR: /* read reservation */
7762		if (lun->flags & CTL_LUN_PR_RESERVED)
7763			total_len = sizeof(struct scsi_per_res_in_rsrv);
7764		else
7765			total_len = sizeof(struct scsi_per_res_in_header);
7766		break;
7767	case SPRI_RC: /* report capabilities */
7768		total_len = sizeof(struct scsi_per_res_cap);
7769		break;
7770	case SPRI_RS: /* read full status */
7771		total_len = sizeof(struct scsi_per_res_in_header) +
7772		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7773		    lun->pr_key_count;
7774		break;
7775	default:
7776		panic("Invalid PR type %x", cdb->action);
7777	}
7778	mtx_unlock(&lun->lun_lock);
7779
7780	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7781
7782	if (total_len < alloc_len) {
7783		ctsio->residual = alloc_len - total_len;
7784		ctsio->kern_data_len = total_len;
7785		ctsio->kern_total_len = total_len;
7786	} else {
7787		ctsio->residual = 0;
7788		ctsio->kern_data_len = alloc_len;
7789		ctsio->kern_total_len = alloc_len;
7790	}
7791
7792	ctsio->kern_data_resid = 0;
7793	ctsio->kern_rel_offset = 0;
7794	ctsio->kern_sg_entries = 0;
7795
7796	mtx_lock(&lun->lun_lock);
7797	switch (cdb->action) {
7798	case SPRI_RK: { // read keys
7799        struct scsi_per_res_in_keys *res_keys;
7800		int i, key_count;
7801
7802		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7803
7804		/*
7805		 * We had to drop the lock to allocate our buffer, which
7806		 * leaves time for someone to come in with another
7807		 * persistent reservation.  (That is unlikely, though,
7808		 * since this should be the only persistent reservation
7809		 * command active right now.)
7810		 */
7811		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7812		    (lun->pr_key_count *
7813		     sizeof(struct scsi_per_res_key)))){
7814			mtx_unlock(&lun->lun_lock);
7815			free(ctsio->kern_data_ptr, M_CTL);
7816			printf("%s: reservation length changed, retrying\n",
7817			       __func__);
7818			goto retry;
7819		}
7820
7821		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7822
7823		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7824			     lun->pr_key_count, res_keys->header.length);
7825
7826		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7827			if (lun->pr_keys[i] == 0)
7828				continue;
7829
7830			/*
7831			 * We used lun->pr_key_count to calculate the
7832			 * size to allocate.  If it turns out the number of
7833			 * initiators with the registered flag set is
7834			 * larger than that (i.e. they haven't been kept in
7835			 * sync), we've got a problem.
7836			 */
7837			if (key_count >= lun->pr_key_count) {
7838#ifdef NEEDTOPORT
7839				csevent_log(CSC_CTL | CSC_SHELF_SW |
7840					    CTL_PR_ERROR,
7841					    csevent_LogType_Fault,
7842					    csevent_AlertLevel_Yellow,
7843					    csevent_FRU_ShelfController,
7844					    csevent_FRU_Firmware,
7845				        csevent_FRU_Unknown,
7846					    "registered keys %d >= key "
7847					    "count %d", key_count,
7848					    lun->pr_key_count);
7849#endif
7850				key_count++;
7851				continue;
7852			}
7853			scsi_u64to8b(lun->pr_keys[i],
7854			    res_keys->keys[key_count].key);
7855			key_count++;
7856		}
7857		break;
7858	}
7859	case SPRI_RR: { // read reservation
7860		struct scsi_per_res_in_rsrv *res;
7861		int tmp_len, header_only;
7862
7863		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7864
7865		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7866
7867		if (lun->flags & CTL_LUN_PR_RESERVED)
7868		{
7869			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7870			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7871				    res->header.length);
7872			header_only = 0;
7873		} else {
7874			tmp_len = sizeof(struct scsi_per_res_in_header);
7875			scsi_ulto4b(0, res->header.length);
7876			header_only = 1;
7877		}
7878
7879		/*
7880		 * We had to drop the lock to allocate our buffer, which
7881		 * leaves time for someone to come in with another
7882		 * persistent reservation.  (That is unlikely, though,
7883		 * since this should be the only persistent reservation
7884		 * command active right now.)
7885		 */
7886		if (tmp_len != total_len) {
7887			mtx_unlock(&lun->lun_lock);
7888			free(ctsio->kern_data_ptr, M_CTL);
7889			printf("%s: reservation status changed, retrying\n",
7890			       __func__);
7891			goto retry;
7892		}
7893
7894		/*
7895		 * No reservation held, so we're done.
7896		 */
7897		if (header_only != 0)
7898			break;
7899
7900		/*
7901		 * If the registration is an All Registrants type, the key
7902		 * is 0, since it doesn't really matter.
7903		 */
7904		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7905			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7906			    res->data.reservation);
7907		}
7908		res->data.scopetype = lun->res_type;
7909		break;
7910	}
7911	case SPRI_RC:     //report capabilities
7912	{
7913		struct scsi_per_res_cap *res_cap;
7914		uint16_t type_mask;
7915
7916		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7917		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7918		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7919		type_mask = SPRI_TM_WR_EX_AR |
7920			    SPRI_TM_EX_AC_RO |
7921			    SPRI_TM_WR_EX_RO |
7922			    SPRI_TM_EX_AC |
7923			    SPRI_TM_WR_EX |
7924			    SPRI_TM_EX_AC_AR;
7925		scsi_ulto2b(type_mask, res_cap->type_mask);
7926		break;
7927	}
7928	case SPRI_RS: { // read full status
7929		struct scsi_per_res_in_full *res_status;
7930		struct scsi_per_res_in_full_desc *res_desc;
7931		struct ctl_port *port;
7932		int i, len;
7933
7934		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7935
7936		/*
7937		 * We had to drop the lock to allocate our buffer, which
7938		 * leaves time for someone to come in with another
7939		 * persistent reservation.  (That is unlikely, though,
7940		 * since this should be the only persistent reservation
7941		 * command active right now.)
7942		 */
7943		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7944		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7945		     lun->pr_key_count)){
7946			mtx_unlock(&lun->lun_lock);
7947			free(ctsio->kern_data_ptr, M_CTL);
7948			printf("%s: reservation length changed, retrying\n",
7949			       __func__);
7950			goto retry;
7951		}
7952
7953		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7954
7955		res_desc = &res_status->desc[0];
7956		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7957			if (lun->pr_keys[i] == 0)
7958				continue;
7959
7960			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7961			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7962			    (lun->pr_res_idx == i ||
7963			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7964				res_desc->flags = SPRI_FULL_R_HOLDER;
7965				res_desc->scopetype = lun->res_type;
7966			}
7967			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7968			    res_desc->rel_trgt_port_id);
7969			len = 0;
7970			port = softc->ctl_ports[
7971			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7972			if (port != NULL)
7973				len = ctl_create_iid(port,
7974				    i % CTL_MAX_INIT_PER_PORT,
7975				    res_desc->transport_id);
7976			scsi_ulto4b(len, res_desc->additional_length);
7977			res_desc = (struct scsi_per_res_in_full_desc *)
7978			    &res_desc->transport_id[len];
7979		}
7980		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7981		    res_status->header.length);
7982		break;
7983	}
7984	default:
7985		/*
7986		 * This is a bug, because we just checked for this above,
7987		 * and should have returned an error.
7988		 */
7989		panic("Invalid PR type %x", cdb->action);
7990		break; /* NOTREACHED */
7991	}
7992	mtx_unlock(&lun->lun_lock);
7993
7994	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7995	ctsio->be_move_done = ctl_config_move_done;
7996
7997	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7998			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7999			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8000			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8001			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8002
8003	ctl_datamove((union ctl_io *)ctsio);
8004
8005	return (CTL_RETVAL_COMPLETE);
8006}
8007
8008/*
8009 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8010 * it should return.
8011 */
8012static int
8013ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8014		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8015		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8016		struct scsi_per_res_out_parms* param)
8017{
8018	union ctl_ha_msg persis_io;
8019	int retval, i;
8020	int isc_retval;
8021
8022	retval = 0;
8023
8024	mtx_lock(&lun->lun_lock);
8025	if (sa_res_key == 0) {
8026		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8027			/* validate scope and type */
8028			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8029			     SPR_LU_SCOPE) {
8030				mtx_unlock(&lun->lun_lock);
8031				ctl_set_invalid_field(/*ctsio*/ ctsio,
8032						      /*sks_valid*/ 1,
8033						      /*command*/ 1,
8034						      /*field*/ 2,
8035						      /*bit_valid*/ 1,
8036						      /*bit*/ 4);
8037				ctl_done((union ctl_io *)ctsio);
8038				return (1);
8039			}
8040
8041		        if (type>8 || type==2 || type==4 || type==0) {
8042				mtx_unlock(&lun->lun_lock);
8043				ctl_set_invalid_field(/*ctsio*/ ctsio,
8044       	           				      /*sks_valid*/ 1,
8045						      /*command*/ 1,
8046						      /*field*/ 2,
8047						      /*bit_valid*/ 1,
8048						      /*bit*/ 0);
8049				ctl_done((union ctl_io *)ctsio);
8050				return (1);
8051		        }
8052
8053			/*
8054			 * Unregister everybody else and build UA for
8055			 * them
8056			 */
8057			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8058				if (i == residx || lun->pr_keys[i] == 0)
8059					continue;
8060
8061				if (!persis_offset
8062				 && i <CTL_MAX_INITIATORS)
8063					lun->pending_ua[i] |=
8064						CTL_UA_REG_PREEMPT;
8065				else if (persis_offset
8066				      && i >= persis_offset)
8067					lun->pending_ua[i-persis_offset] |=
8068						CTL_UA_REG_PREEMPT;
8069				lun->pr_keys[i] = 0;
8070			}
8071			lun->pr_key_count = 1;
8072			lun->res_type = type;
8073			if (lun->res_type != SPR_TYPE_WR_EX_AR
8074			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8075				lun->pr_res_idx = residx;
8076
8077			/* send msg to other side */
8078			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8079			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8080			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8081			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8082			persis_io.pr.pr_info.res_type = type;
8083			memcpy(persis_io.pr.pr_info.sa_res_key,
8084			       param->serv_act_res_key,
8085			       sizeof(param->serv_act_res_key));
8086			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8087			     &persis_io, sizeof(persis_io), 0)) >
8088			     CTL_HA_STATUS_SUCCESS) {
8089				printf("CTL:Persis Out error returned "
8090				       "from ctl_ha_msg_send %d\n",
8091				       isc_retval);
8092			}
8093		} else {
8094			/* not all registrants */
8095			mtx_unlock(&lun->lun_lock);
8096			free(ctsio->kern_data_ptr, M_CTL);
8097			ctl_set_invalid_field(ctsio,
8098					      /*sks_valid*/ 1,
8099					      /*command*/ 0,
8100					      /*field*/ 8,
8101					      /*bit_valid*/ 0,
8102					      /*bit*/ 0);
8103			ctl_done((union ctl_io *)ctsio);
8104			return (1);
8105		}
8106	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8107		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8108		int found = 0;
8109
8110		if (res_key == sa_res_key) {
8111			/* special case */
8112			/*
8113			 * The spec implies this is not good but doesn't
8114			 * say what to do. There are two choices either
8115			 * generate a res conflict or check condition
8116			 * with illegal field in parameter data. Since
8117			 * that is what is done when the sa_res_key is
8118			 * zero I'll take that approach since this has
8119			 * to do with the sa_res_key.
8120			 */
8121			mtx_unlock(&lun->lun_lock);
8122			free(ctsio->kern_data_ptr, M_CTL);
8123			ctl_set_invalid_field(ctsio,
8124					      /*sks_valid*/ 1,
8125					      /*command*/ 0,
8126					      /*field*/ 8,
8127					      /*bit_valid*/ 0,
8128					      /*bit*/ 0);
8129			ctl_done((union ctl_io *)ctsio);
8130			return (1);
8131		}
8132
8133		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8134			if (lun->pr_keys[i] != sa_res_key)
8135				continue;
8136
8137			found = 1;
8138			lun->pr_keys[i] = 0;
8139			lun->pr_key_count--;
8140
8141			if (!persis_offset && i < CTL_MAX_INITIATORS)
8142				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8143			else if (persis_offset && i >= persis_offset)
8144				lun->pending_ua[i-persis_offset] |=
8145					CTL_UA_REG_PREEMPT;
8146		}
8147		if (!found) {
8148			mtx_unlock(&lun->lun_lock);
8149			free(ctsio->kern_data_ptr, M_CTL);
8150			ctl_set_reservation_conflict(ctsio);
8151			ctl_done((union ctl_io *)ctsio);
8152			return (CTL_RETVAL_COMPLETE);
8153		}
8154		/* send msg to other side */
8155		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8156		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8157		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8158		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8159		persis_io.pr.pr_info.res_type = type;
8160		memcpy(persis_io.pr.pr_info.sa_res_key,
8161		       param->serv_act_res_key,
8162		       sizeof(param->serv_act_res_key));
8163		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8164		     &persis_io, sizeof(persis_io), 0)) >
8165		     CTL_HA_STATUS_SUCCESS) {
8166			printf("CTL:Persis Out error returned from "
8167			       "ctl_ha_msg_send %d\n", isc_retval);
8168		}
8169	} else {
8170		/* Reserved but not all registrants */
8171		/* sa_res_key is res holder */
8172		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
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			 * Do the following:
8201			 * if sa_res_key != res_key remove all
8202			 * registrants w/sa_res_key and generate UA
8203			 * for these registrants(Registrations
8204			 * Preempted) if it wasn't an exclusive
8205			 * reservation generate UA(Reservations
8206			 * Preempted) for all other registered nexuses
8207			 * if the type has changed. Establish the new
8208			 * reservation and holder. If res_key and
8209			 * sa_res_key are the same do the above
8210			 * except don't unregister the res holder.
8211			 */
8212
8213			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8214				if (i == residx || lun->pr_keys[i] == 0)
8215					continue;
8216
8217				if (sa_res_key == lun->pr_keys[i]) {
8218					lun->pr_keys[i] = 0;
8219					lun->pr_key_count--;
8220
8221					if (!persis_offset
8222					 && i < CTL_MAX_INITIATORS)
8223						lun->pending_ua[i] |=
8224							CTL_UA_REG_PREEMPT;
8225					else if (persis_offset
8226					      && i >= persis_offset)
8227						lun->pending_ua[i-persis_offset] |=
8228						  CTL_UA_REG_PREEMPT;
8229				} else if (type != lun->res_type
8230					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8231					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8232						if (!persis_offset
8233						 && i < CTL_MAX_INITIATORS)
8234							lun->pending_ua[i] |=
8235							CTL_UA_RES_RELEASE;
8236						else if (persis_offset
8237						      && i >= persis_offset)
8238							lun->pending_ua[
8239							i-persis_offset] |=
8240							CTL_UA_RES_RELEASE;
8241				}
8242			}
8243			lun->res_type = type;
8244			if (lun->res_type != SPR_TYPE_WR_EX_AR
8245			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8246				lun->pr_res_idx = residx;
8247			else
8248				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8249
8250			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8251			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8252			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8253			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8254			persis_io.pr.pr_info.res_type = type;
8255			memcpy(persis_io.pr.pr_info.sa_res_key,
8256			       param->serv_act_res_key,
8257			       sizeof(param->serv_act_res_key));
8258			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8259			     &persis_io, sizeof(persis_io), 0)) >
8260			     CTL_HA_STATUS_SUCCESS) {
8261				printf("CTL:Persis Out error returned "
8262				       "from ctl_ha_msg_send %d\n",
8263				       isc_retval);
8264			}
8265		} else {
8266			/*
8267			 * sa_res_key is not the res holder just
8268			 * remove registrants
8269			 */
8270			int found=0;
8271
8272			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8273				if (sa_res_key != lun->pr_keys[i])
8274					continue;
8275
8276				found = 1;
8277				lun->pr_keys[i] = 0;
8278				lun->pr_key_count--;
8279
8280				if (!persis_offset
8281				 && i < CTL_MAX_INITIATORS)
8282					lun->pending_ua[i] |=
8283						CTL_UA_REG_PREEMPT;
8284				else if (persis_offset
8285				      && i >= persis_offset)
8286					lun->pending_ua[i-persis_offset] |=
8287						CTL_UA_REG_PREEMPT;
8288			}
8289
8290			if (!found) {
8291				mtx_unlock(&lun->lun_lock);
8292				free(ctsio->kern_data_ptr, M_CTL);
8293				ctl_set_reservation_conflict(ctsio);
8294				ctl_done((union ctl_io *)ctsio);
8295		        	return (1);
8296			}
8297			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8298			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8299			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8300			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8301			persis_io.pr.pr_info.res_type = type;
8302			memcpy(persis_io.pr.pr_info.sa_res_key,
8303			       param->serv_act_res_key,
8304			       sizeof(param->serv_act_res_key));
8305			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8306			     &persis_io, sizeof(persis_io), 0)) >
8307			     CTL_HA_STATUS_SUCCESS) {
8308				printf("CTL:Persis Out error returned "
8309				       "from ctl_ha_msg_send %d\n",
8310				isc_retval);
8311			}
8312		}
8313	}
8314
8315	lun->PRGeneration++;
8316	mtx_unlock(&lun->lun_lock);
8317
8318	return (retval);
8319}
8320
8321static void
8322ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8323{
8324	uint64_t sa_res_key;
8325	int i;
8326
8327	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8328
8329	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8330	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8331	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8332		if (sa_res_key == 0) {
8333			/*
8334			 * Unregister everybody else and build UA for
8335			 * them
8336			 */
8337			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8338				if (i == msg->pr.pr_info.residx ||
8339				    lun->pr_keys[i] == 0)
8340					continue;
8341
8342				if (!persis_offset
8343				 && i < CTL_MAX_INITIATORS)
8344					lun->pending_ua[i] |=
8345						CTL_UA_REG_PREEMPT;
8346				else if (persis_offset && i >= persis_offset)
8347					lun->pending_ua[i - persis_offset] |=
8348						CTL_UA_REG_PREEMPT;
8349				lun->pr_keys[i] = 0;
8350			}
8351
8352			lun->pr_key_count = 1;
8353			lun->res_type = msg->pr.pr_info.res_type;
8354			if (lun->res_type != SPR_TYPE_WR_EX_AR
8355			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8356				lun->pr_res_idx = msg->pr.pr_info.residx;
8357		} else {
8358		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8359				if (sa_res_key == lun->pr_keys[i])
8360					continue;
8361
8362				lun->pr_keys[i] = 0;
8363				lun->pr_key_count--;
8364
8365				if (!persis_offset
8366				 && i < persis_offset)
8367					lun->pending_ua[i] |=
8368						CTL_UA_REG_PREEMPT;
8369				else if (persis_offset
8370				      && i >= persis_offset)
8371					lun->pending_ua[i - persis_offset] |=
8372						CTL_UA_REG_PREEMPT;
8373			}
8374		}
8375	} else {
8376		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8377			if (i == msg->pr.pr_info.residx ||
8378			    lun->pr_keys[i] == 0)
8379				continue;
8380
8381			if (sa_res_key == lun->pr_keys[i]) {
8382				lun->pr_keys[i] = 0;
8383				lun->pr_key_count--;
8384				if (!persis_offset
8385				 && i < CTL_MAX_INITIATORS)
8386					lun->pending_ua[i] |=
8387						CTL_UA_REG_PREEMPT;
8388				else if (persis_offset
8389				      && i >= persis_offset)
8390					lun->pending_ua[i - persis_offset] |=
8391						CTL_UA_REG_PREEMPT;
8392			} else if (msg->pr.pr_info.res_type != lun->res_type
8393				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8394				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8395					if (!persis_offset
8396					 && i < persis_offset)
8397						lun->pending_ua[i] |=
8398							CTL_UA_RES_RELEASE;
8399					else if (persis_offset
8400					      && i >= persis_offset)
8401					lun->pending_ua[i - persis_offset] |=
8402						CTL_UA_RES_RELEASE;
8403			}
8404		}
8405		lun->res_type = msg->pr.pr_info.res_type;
8406		if (lun->res_type != SPR_TYPE_WR_EX_AR
8407		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8408			lun->pr_res_idx = msg->pr.pr_info.residx;
8409		else
8410			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8411	}
8412	lun->PRGeneration++;
8413
8414}
8415
8416
8417int
8418ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8419{
8420	int retval;
8421	int isc_retval;
8422	u_int32_t param_len;
8423	struct scsi_per_res_out *cdb;
8424	struct ctl_lun *lun;
8425	struct scsi_per_res_out_parms* param;
8426	struct ctl_softc *softc;
8427	uint32_t residx;
8428	uint64_t res_key, sa_res_key;
8429	uint8_t type;
8430	union ctl_ha_msg persis_io;
8431	int    i;
8432
8433	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8434
8435	retval = CTL_RETVAL_COMPLETE;
8436
8437	softc = control_softc;
8438
8439	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8440	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8441
8442	/*
8443	 * We only support whole-LUN scope.  The scope & type are ignored for
8444	 * register, register and ignore existing key and clear.
8445	 * We sometimes ignore scope and type on preempts too!!
8446	 * Verify reservation type here as well.
8447	 */
8448	type = cdb->scope_type & SPR_TYPE_MASK;
8449	if ((cdb->action == SPRO_RESERVE)
8450	 || (cdb->action == SPRO_RELEASE)) {
8451		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8452			ctl_set_invalid_field(/*ctsio*/ ctsio,
8453					      /*sks_valid*/ 1,
8454					      /*command*/ 1,
8455					      /*field*/ 2,
8456					      /*bit_valid*/ 1,
8457					      /*bit*/ 4);
8458			ctl_done((union ctl_io *)ctsio);
8459			return (CTL_RETVAL_COMPLETE);
8460		}
8461
8462		if (type>8 || type==2 || type==4 || type==0) {
8463			ctl_set_invalid_field(/*ctsio*/ ctsio,
8464					      /*sks_valid*/ 1,
8465					      /*command*/ 1,
8466					      /*field*/ 2,
8467					      /*bit_valid*/ 1,
8468					      /*bit*/ 0);
8469			ctl_done((union ctl_io *)ctsio);
8470			return (CTL_RETVAL_COMPLETE);
8471		}
8472	}
8473
8474	param_len = scsi_4btoul(cdb->length);
8475
8476	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8477		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8478		ctsio->kern_data_len = param_len;
8479		ctsio->kern_total_len = param_len;
8480		ctsio->kern_data_resid = 0;
8481		ctsio->kern_rel_offset = 0;
8482		ctsio->kern_sg_entries = 0;
8483		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8484		ctsio->be_move_done = ctl_config_move_done;
8485		ctl_datamove((union ctl_io *)ctsio);
8486
8487		return (CTL_RETVAL_COMPLETE);
8488	}
8489
8490	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8491
8492	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8493	res_key = scsi_8btou64(param->res_key.key);
8494	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8495
8496	/*
8497	 * Validate the reservation key here except for SPRO_REG_IGNO
8498	 * This must be done for all other service actions
8499	 */
8500	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8501		mtx_lock(&lun->lun_lock);
8502		if (lun->pr_keys[residx] != 0) {
8503		    if (res_key != lun->pr_keys[residx]) {
8504				/*
8505				 * The current key passed in doesn't match
8506				 * the one the initiator previously
8507				 * registered.
8508				 */
8509				mtx_unlock(&lun->lun_lock);
8510				free(ctsio->kern_data_ptr, M_CTL);
8511				ctl_set_reservation_conflict(ctsio);
8512				ctl_done((union ctl_io *)ctsio);
8513				return (CTL_RETVAL_COMPLETE);
8514			}
8515		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8516			/*
8517			 * We are not registered
8518			 */
8519			mtx_unlock(&lun->lun_lock);
8520			free(ctsio->kern_data_ptr, M_CTL);
8521			ctl_set_reservation_conflict(ctsio);
8522			ctl_done((union ctl_io *)ctsio);
8523			return (CTL_RETVAL_COMPLETE);
8524		} else if (res_key != 0) {
8525			/*
8526			 * We are not registered and trying to register but
8527			 * the register key isn't zero.
8528			 */
8529			mtx_unlock(&lun->lun_lock);
8530			free(ctsio->kern_data_ptr, M_CTL);
8531			ctl_set_reservation_conflict(ctsio);
8532			ctl_done((union ctl_io *)ctsio);
8533			return (CTL_RETVAL_COMPLETE);
8534		}
8535		mtx_unlock(&lun->lun_lock);
8536	}
8537
8538	switch (cdb->action & SPRO_ACTION_MASK) {
8539	case SPRO_REGISTER:
8540	case SPRO_REG_IGNO: {
8541
8542#if 0
8543		printf("Registration received\n");
8544#endif
8545
8546		/*
8547		 * We don't support any of these options, as we report in
8548		 * the read capabilities request (see
8549		 * ctl_persistent_reserve_in(), above).
8550		 */
8551		if ((param->flags & SPR_SPEC_I_PT)
8552		 || (param->flags & SPR_ALL_TG_PT)
8553		 || (param->flags & SPR_APTPL)) {
8554			int bit_ptr;
8555
8556			if (param->flags & SPR_APTPL)
8557				bit_ptr = 0;
8558			else if (param->flags & SPR_ALL_TG_PT)
8559				bit_ptr = 2;
8560			else /* SPR_SPEC_I_PT */
8561				bit_ptr = 3;
8562
8563			free(ctsio->kern_data_ptr, M_CTL);
8564			ctl_set_invalid_field(ctsio,
8565					      /*sks_valid*/ 1,
8566					      /*command*/ 0,
8567					      /*field*/ 20,
8568					      /*bit_valid*/ 1,
8569					      /*bit*/ bit_ptr);
8570			ctl_done((union ctl_io *)ctsio);
8571			return (CTL_RETVAL_COMPLETE);
8572		}
8573
8574		mtx_lock(&lun->lun_lock);
8575
8576		/*
8577		 * The initiator wants to clear the
8578		 * key/unregister.
8579		 */
8580		if (sa_res_key == 0) {
8581			if ((res_key == 0
8582			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8583			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8584			  && lun->pr_keys[residx] == 0)) {
8585				mtx_unlock(&lun->lun_lock);
8586				goto done;
8587			}
8588
8589			lun->pr_keys[residx] = 0;
8590			lun->pr_key_count--;
8591
8592			if (residx == lun->pr_res_idx) {
8593				lun->flags &= ~CTL_LUN_PR_RESERVED;
8594				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8595
8596				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8597				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8598				 && lun->pr_key_count) {
8599					/*
8600					 * If the reservation is a registrants
8601					 * only type we need to generate a UA
8602					 * for other registered inits.  The
8603					 * sense code should be RESERVATIONS
8604					 * RELEASED
8605					 */
8606
8607					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8608						if (lun->pr_keys[
8609						    i + persis_offset] == 0)
8610							continue;
8611						lun->pending_ua[i] |=
8612							CTL_UA_RES_RELEASE;
8613					}
8614				}
8615				lun->res_type = 0;
8616			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8617				if (lun->pr_key_count==0) {
8618					lun->flags &= ~CTL_LUN_PR_RESERVED;
8619					lun->res_type = 0;
8620					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8621				}
8622			}
8623			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8624			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8625			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8626			persis_io.pr.pr_info.residx = residx;
8627			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8628			     &persis_io, sizeof(persis_io), 0 )) >
8629			     CTL_HA_STATUS_SUCCESS) {
8630				printf("CTL:Persis Out error returned from "
8631				       "ctl_ha_msg_send %d\n", isc_retval);
8632			}
8633		} else /* sa_res_key != 0 */ {
8634
8635			/*
8636			 * If we aren't registered currently then increment
8637			 * the key count and set the registered flag.
8638			 */
8639			if (lun->pr_keys[residx] == 0)
8640				lun->pr_key_count++;
8641			lun->pr_keys[residx] = sa_res_key;
8642
8643			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8644			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8645			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8646			persis_io.pr.pr_info.residx = residx;
8647			memcpy(persis_io.pr.pr_info.sa_res_key,
8648			       param->serv_act_res_key,
8649			       sizeof(param->serv_act_res_key));
8650			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8651			     &persis_io, sizeof(persis_io), 0)) >
8652			     CTL_HA_STATUS_SUCCESS) {
8653				printf("CTL:Persis Out error returned from "
8654				       "ctl_ha_msg_send %d\n", isc_retval);
8655			}
8656		}
8657		lun->PRGeneration++;
8658		mtx_unlock(&lun->lun_lock);
8659
8660		break;
8661	}
8662	case SPRO_RESERVE:
8663#if 0
8664                printf("Reserve executed type %d\n", type);
8665#endif
8666		mtx_lock(&lun->lun_lock);
8667		if (lun->flags & CTL_LUN_PR_RESERVED) {
8668			/*
8669			 * if this isn't the reservation holder and it's
8670			 * not a "all registrants" type or if the type is
8671			 * different then we have a conflict
8672			 */
8673			if ((lun->pr_res_idx != residx
8674			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8675			 || lun->res_type != type) {
8676				mtx_unlock(&lun->lun_lock);
8677				free(ctsio->kern_data_ptr, M_CTL);
8678				ctl_set_reservation_conflict(ctsio);
8679				ctl_done((union ctl_io *)ctsio);
8680				return (CTL_RETVAL_COMPLETE);
8681			}
8682			mtx_unlock(&lun->lun_lock);
8683		} else /* create a reservation */ {
8684			/*
8685			 * If it's not an "all registrants" type record
8686			 * reservation holder
8687			 */
8688			if (type != SPR_TYPE_WR_EX_AR
8689			 && type != SPR_TYPE_EX_AC_AR)
8690				lun->pr_res_idx = residx; /* Res holder */
8691			else
8692				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8693
8694			lun->flags |= CTL_LUN_PR_RESERVED;
8695			lun->res_type = type;
8696
8697			mtx_unlock(&lun->lun_lock);
8698
8699			/* send msg to other side */
8700			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8701			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8702			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8703			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8704			persis_io.pr.pr_info.res_type = type;
8705			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8706			     &persis_io, sizeof(persis_io), 0)) >
8707			     CTL_HA_STATUS_SUCCESS) {
8708				printf("CTL:Persis Out error returned from "
8709				       "ctl_ha_msg_send %d\n", isc_retval);
8710			}
8711		}
8712		break;
8713
8714	case SPRO_RELEASE:
8715		mtx_lock(&lun->lun_lock);
8716		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8717			/* No reservation exists return good status */
8718			mtx_unlock(&lun->lun_lock);
8719			goto done;
8720		}
8721		/*
8722		 * Is this nexus a reservation holder?
8723		 */
8724		if (lun->pr_res_idx != residx
8725		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8726			/*
8727			 * not a res holder return good status but
8728			 * do nothing
8729			 */
8730			mtx_unlock(&lun->lun_lock);
8731			goto done;
8732		}
8733
8734		if (lun->res_type != type) {
8735			mtx_unlock(&lun->lun_lock);
8736			free(ctsio->kern_data_ptr, M_CTL);
8737			ctl_set_illegal_pr_release(ctsio);
8738			ctl_done((union ctl_io *)ctsio);
8739			return (CTL_RETVAL_COMPLETE);
8740		}
8741
8742		/* okay to release */
8743		lun->flags &= ~CTL_LUN_PR_RESERVED;
8744		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8745		lun->res_type = 0;
8746
8747		/*
8748		 * if this isn't an exclusive access
8749		 * res generate UA for all other
8750		 * registrants.
8751		 */
8752		if (type != SPR_TYPE_EX_AC
8753		 && type != SPR_TYPE_WR_EX) {
8754			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8755				if (i == residx ||
8756				    lun->pr_keys[i + persis_offset] == 0)
8757					continue;
8758				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8759			}
8760		}
8761		mtx_unlock(&lun->lun_lock);
8762		/* Send msg to other side */
8763		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8764		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8765		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8766		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8767		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8768			printf("CTL:Persis Out error returned from "
8769			       "ctl_ha_msg_send %d\n", isc_retval);
8770		}
8771		break;
8772
8773	case SPRO_CLEAR:
8774		/* send msg to other side */
8775
8776		mtx_lock(&lun->lun_lock);
8777		lun->flags &= ~CTL_LUN_PR_RESERVED;
8778		lun->res_type = 0;
8779		lun->pr_key_count = 0;
8780		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8781
8782		lun->pr_keys[residx] = 0;
8783
8784		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8785			if (lun->pr_keys[i] != 0) {
8786				if (!persis_offset && i < CTL_MAX_INITIATORS)
8787					lun->pending_ua[i] |=
8788						CTL_UA_RES_PREEMPT;
8789				else if (persis_offset && i >= persis_offset)
8790					lun->pending_ua[i-persis_offset] |=
8791					    CTL_UA_RES_PREEMPT;
8792
8793				lun->pr_keys[i] = 0;
8794			}
8795		lun->PRGeneration++;
8796		mtx_unlock(&lun->lun_lock);
8797		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8798		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8799		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8800		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8801		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8802			printf("CTL:Persis Out error returned from "
8803			       "ctl_ha_msg_send %d\n", isc_retval);
8804		}
8805		break;
8806
8807	case SPRO_PREEMPT: {
8808		int nretval;
8809
8810		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8811					  residx, ctsio, cdb, param);
8812		if (nretval != 0)
8813			return (CTL_RETVAL_COMPLETE);
8814		break;
8815	}
8816	default:
8817		panic("Invalid PR type %x", cdb->action);
8818	}
8819
8820done:
8821	free(ctsio->kern_data_ptr, M_CTL);
8822	ctl_set_success(ctsio);
8823	ctl_done((union ctl_io *)ctsio);
8824
8825	return (retval);
8826}
8827
8828/*
8829 * This routine is for handling a message from the other SC pertaining to
8830 * persistent reserve out. All the error checking will have been done
8831 * so only perorming the action need be done here to keep the two
8832 * in sync.
8833 */
8834static void
8835ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8836{
8837	struct ctl_lun *lun;
8838	struct ctl_softc *softc;
8839	int i;
8840	uint32_t targ_lun;
8841
8842	softc = control_softc;
8843
8844	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8845	lun = softc->ctl_luns[targ_lun];
8846	mtx_lock(&lun->lun_lock);
8847	switch(msg->pr.pr_info.action) {
8848	case CTL_PR_REG_KEY:
8849		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8850			lun->pr_key_count++;
8851		lun->pr_keys[msg->pr.pr_info.residx] =
8852		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8853		lun->PRGeneration++;
8854		break;
8855
8856	case CTL_PR_UNREG_KEY:
8857		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8858		lun->pr_key_count--;
8859
8860		/* XXX Need to see if the reservation has been released */
8861		/* if so do we need to generate UA? */
8862		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8863			lun->flags &= ~CTL_LUN_PR_RESERVED;
8864			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8865
8866			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8867			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8868			 && lun->pr_key_count) {
8869				/*
8870				 * If the reservation is a registrants
8871				 * only type we need to generate a UA
8872				 * for other registered inits.  The
8873				 * sense code should be RESERVATIONS
8874				 * RELEASED
8875				 */
8876
8877				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8878					if (lun->pr_keys[i+
8879					    persis_offset] == 0)
8880						continue;
8881
8882					lun->pending_ua[i] |=
8883						CTL_UA_RES_RELEASE;
8884				}
8885			}
8886			lun->res_type = 0;
8887		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8888			if (lun->pr_key_count==0) {
8889				lun->flags &= ~CTL_LUN_PR_RESERVED;
8890				lun->res_type = 0;
8891				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8892			}
8893		}
8894		lun->PRGeneration++;
8895		break;
8896
8897	case CTL_PR_RESERVE:
8898		lun->flags |= CTL_LUN_PR_RESERVED;
8899		lun->res_type = msg->pr.pr_info.res_type;
8900		lun->pr_res_idx = msg->pr.pr_info.residx;
8901
8902		break;
8903
8904	case CTL_PR_RELEASE:
8905		/*
8906		 * if this isn't an exclusive access res generate UA for all
8907		 * other registrants.
8908		 */
8909		if (lun->res_type != SPR_TYPE_EX_AC
8910		 && lun->res_type != SPR_TYPE_WR_EX) {
8911			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8912				if (lun->pr_keys[i+persis_offset] != 0)
8913					lun->pending_ua[i] |=
8914						CTL_UA_RES_RELEASE;
8915		}
8916
8917		lun->flags &= ~CTL_LUN_PR_RESERVED;
8918		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8919		lun->res_type = 0;
8920		break;
8921
8922	case CTL_PR_PREEMPT:
8923		ctl_pro_preempt_other(lun, msg);
8924		break;
8925	case CTL_PR_CLEAR:
8926		lun->flags &= ~CTL_LUN_PR_RESERVED;
8927		lun->res_type = 0;
8928		lun->pr_key_count = 0;
8929		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8930
8931		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8932			if (lun->pr_keys[i] == 0)
8933				continue;
8934			if (!persis_offset
8935			 && i < CTL_MAX_INITIATORS)
8936				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8937			else if (persis_offset
8938			      && i >= persis_offset)
8939				lun->pending_ua[i-persis_offset] |=
8940					CTL_UA_RES_PREEMPT;
8941			lun->pr_keys[i] = 0;
8942		}
8943		lun->PRGeneration++;
8944		break;
8945	}
8946
8947	mtx_unlock(&lun->lun_lock);
8948}
8949
8950int
8951ctl_read_write(struct ctl_scsiio *ctsio)
8952{
8953	struct ctl_lun *lun;
8954	struct ctl_lba_len_flags *lbalen;
8955	uint64_t lba;
8956	uint32_t num_blocks;
8957	int flags, retval;
8958	int isread;
8959
8960	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8961
8962	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8963
8964	flags = 0;
8965	retval = CTL_RETVAL_COMPLETE;
8966
8967	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8968	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8969	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8970		uint32_t residx;
8971
8972		/*
8973		 * XXX KDM need a lock here.
8974		 */
8975		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8976		if ((lun->res_type == SPR_TYPE_EX_AC
8977		  && residx != lun->pr_res_idx)
8978		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8979		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8980		  && lun->pr_keys[residx] == 0)) {
8981			ctl_set_reservation_conflict(ctsio);
8982			ctl_done((union ctl_io *)ctsio);
8983			return (CTL_RETVAL_COMPLETE);
8984	        }
8985	}
8986
8987	switch (ctsio->cdb[0]) {
8988	case READ_6:
8989	case WRITE_6: {
8990		struct scsi_rw_6 *cdb;
8991
8992		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8993
8994		lba = scsi_3btoul(cdb->addr);
8995		/* only 5 bits are valid in the most significant address byte */
8996		lba &= 0x1fffff;
8997		num_blocks = cdb->length;
8998		/*
8999		 * This is correct according to SBC-2.
9000		 */
9001		if (num_blocks == 0)
9002			num_blocks = 256;
9003		break;
9004	}
9005	case READ_10:
9006	case WRITE_10: {
9007		struct scsi_rw_10 *cdb;
9008
9009		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9010		if (cdb->byte2 & SRW10_FUA)
9011			flags |= CTL_LLF_FUA;
9012		if (cdb->byte2 & SRW10_DPO)
9013			flags |= CTL_LLF_DPO;
9014		lba = scsi_4btoul(cdb->addr);
9015		num_blocks = scsi_2btoul(cdb->length);
9016		break;
9017	}
9018	case WRITE_VERIFY_10: {
9019		struct scsi_write_verify_10 *cdb;
9020
9021		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9022		flags |= CTL_LLF_FUA;
9023		if (cdb->byte2 & SWV_DPO)
9024			flags |= CTL_LLF_DPO;
9025		lba = scsi_4btoul(cdb->addr);
9026		num_blocks = scsi_2btoul(cdb->length);
9027		break;
9028	}
9029	case READ_12:
9030	case WRITE_12: {
9031		struct scsi_rw_12 *cdb;
9032
9033		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9034		if (cdb->byte2 & SRW12_FUA)
9035			flags |= CTL_LLF_FUA;
9036		if (cdb->byte2 & SRW12_DPO)
9037			flags |= CTL_LLF_DPO;
9038		lba = scsi_4btoul(cdb->addr);
9039		num_blocks = scsi_4btoul(cdb->length);
9040		break;
9041	}
9042	case WRITE_VERIFY_12: {
9043		struct scsi_write_verify_12 *cdb;
9044
9045		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9046		flags |= CTL_LLF_FUA;
9047		if (cdb->byte2 & SWV_DPO)
9048			flags |= CTL_LLF_DPO;
9049		lba = scsi_4btoul(cdb->addr);
9050		num_blocks = scsi_4btoul(cdb->length);
9051		break;
9052	}
9053	case READ_16:
9054	case WRITE_16: {
9055		struct scsi_rw_16 *cdb;
9056
9057		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9058		if (cdb->byte2 & SRW12_FUA)
9059			flags |= CTL_LLF_FUA;
9060		if (cdb->byte2 & SRW12_DPO)
9061			flags |= CTL_LLF_DPO;
9062		lba = scsi_8btou64(cdb->addr);
9063		num_blocks = scsi_4btoul(cdb->length);
9064		break;
9065	}
9066	case WRITE_ATOMIC_16: {
9067		struct scsi_rw_16 *cdb;
9068
9069		if (lun->be_lun->atomicblock == 0) {
9070			ctl_set_invalid_opcode(ctsio);
9071			ctl_done((union ctl_io *)ctsio);
9072			return (CTL_RETVAL_COMPLETE);
9073		}
9074
9075		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9076		if (cdb->byte2 & SRW12_FUA)
9077			flags |= CTL_LLF_FUA;
9078		if (cdb->byte2 & SRW12_DPO)
9079			flags |= CTL_LLF_DPO;
9080		lba = scsi_8btou64(cdb->addr);
9081		num_blocks = scsi_4btoul(cdb->length);
9082		if (num_blocks > lun->be_lun->atomicblock) {
9083			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9084			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9085			    /*bit*/ 0);
9086			ctl_done((union ctl_io *)ctsio);
9087			return (CTL_RETVAL_COMPLETE);
9088		}
9089		break;
9090	}
9091	case WRITE_VERIFY_16: {
9092		struct scsi_write_verify_16 *cdb;
9093
9094		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9095		flags |= CTL_LLF_FUA;
9096		if (cdb->byte2 & SWV_DPO)
9097			flags |= CTL_LLF_DPO;
9098		lba = scsi_8btou64(cdb->addr);
9099		num_blocks = scsi_4btoul(cdb->length);
9100		break;
9101	}
9102	default:
9103		/*
9104		 * We got a command we don't support.  This shouldn't
9105		 * happen, commands should be filtered out above us.
9106		 */
9107		ctl_set_invalid_opcode(ctsio);
9108		ctl_done((union ctl_io *)ctsio);
9109
9110		return (CTL_RETVAL_COMPLETE);
9111		break; /* NOTREACHED */
9112	}
9113
9114	/*
9115	 * The first check is to make sure we're in bounds, the second
9116	 * check is to catch wrap-around problems.  If the lba + num blocks
9117	 * is less than the lba, then we've wrapped around and the block
9118	 * range is invalid anyway.
9119	 */
9120	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9121	 || ((lba + num_blocks) < lba)) {
9122		ctl_set_lba_out_of_range(ctsio);
9123		ctl_done((union ctl_io *)ctsio);
9124		return (CTL_RETVAL_COMPLETE);
9125	}
9126
9127	/*
9128	 * According to SBC-3, a transfer length of 0 is not an error.
9129	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9130	 * translates to 256 blocks for those commands.
9131	 */
9132	if (num_blocks == 0) {
9133		ctl_set_success(ctsio);
9134		ctl_done((union ctl_io *)ctsio);
9135		return (CTL_RETVAL_COMPLETE);
9136	}
9137
9138	/* Set FUA and/or DPO if caches are disabled. */
9139	if (isread) {
9140		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9141		    SCP_RCD) != 0)
9142			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9143	} else {
9144		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9145		    SCP_WCE) == 0)
9146			flags |= CTL_LLF_FUA;
9147	}
9148
9149	lbalen = (struct ctl_lba_len_flags *)
9150	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9151	lbalen->lba = lba;
9152	lbalen->len = num_blocks;
9153	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9154
9155	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9156	ctsio->kern_rel_offset = 0;
9157
9158	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9159
9160	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9161
9162	return (retval);
9163}
9164
9165static int
9166ctl_cnw_cont(union ctl_io *io)
9167{
9168	struct ctl_scsiio *ctsio;
9169	struct ctl_lun *lun;
9170	struct ctl_lba_len_flags *lbalen;
9171	int retval;
9172
9173	ctsio = &io->scsiio;
9174	ctsio->io_hdr.status = CTL_STATUS_NONE;
9175	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9176	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9177	lbalen = (struct ctl_lba_len_flags *)
9178	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9179	lbalen->flags &= ~CTL_LLF_COMPARE;
9180	lbalen->flags |= CTL_LLF_WRITE;
9181
9182	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9183	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9184	return (retval);
9185}
9186
9187int
9188ctl_cnw(struct ctl_scsiio *ctsio)
9189{
9190	struct ctl_lun *lun;
9191	struct ctl_lba_len_flags *lbalen;
9192	uint64_t lba;
9193	uint32_t num_blocks;
9194	int flags, retval;
9195
9196	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9197
9198	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9199
9200	flags = 0;
9201	retval = CTL_RETVAL_COMPLETE;
9202
9203	switch (ctsio->cdb[0]) {
9204	case COMPARE_AND_WRITE: {
9205		struct scsi_compare_and_write *cdb;
9206
9207		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9208		if (cdb->byte2 & SRW10_FUA)
9209			flags |= CTL_LLF_FUA;
9210		if (cdb->byte2 & SRW10_DPO)
9211			flags |= CTL_LLF_DPO;
9212		lba = scsi_8btou64(cdb->addr);
9213		num_blocks = cdb->length;
9214		break;
9215	}
9216	default:
9217		/*
9218		 * We got a command we don't support.  This shouldn't
9219		 * happen, commands should be filtered out above us.
9220		 */
9221		ctl_set_invalid_opcode(ctsio);
9222		ctl_done((union ctl_io *)ctsio);
9223
9224		return (CTL_RETVAL_COMPLETE);
9225		break; /* NOTREACHED */
9226	}
9227
9228	/*
9229	 * The first check is to make sure we're in bounds, the second
9230	 * check is to catch wrap-around problems.  If the lba + num blocks
9231	 * is less than the lba, then we've wrapped around and the block
9232	 * range is invalid anyway.
9233	 */
9234	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9235	 || ((lba + num_blocks) < lba)) {
9236		ctl_set_lba_out_of_range(ctsio);
9237		ctl_done((union ctl_io *)ctsio);
9238		return (CTL_RETVAL_COMPLETE);
9239	}
9240
9241	/*
9242	 * According to SBC-3, a transfer length of 0 is not an error.
9243	 */
9244	if (num_blocks == 0) {
9245		ctl_set_success(ctsio);
9246		ctl_done((union ctl_io *)ctsio);
9247		return (CTL_RETVAL_COMPLETE);
9248	}
9249
9250	/* Set FUA if write cache is disabled. */
9251	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9252	    SCP_WCE) == 0)
9253		flags |= CTL_LLF_FUA;
9254
9255	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9256	ctsio->kern_rel_offset = 0;
9257
9258	/*
9259	 * Set the IO_CONT flag, so that if this I/O gets passed to
9260	 * ctl_data_submit_done(), it'll get passed back to
9261	 * ctl_ctl_cnw_cont() for further processing.
9262	 */
9263	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9264	ctsio->io_cont = ctl_cnw_cont;
9265
9266	lbalen = (struct ctl_lba_len_flags *)
9267	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9268	lbalen->lba = lba;
9269	lbalen->len = num_blocks;
9270	lbalen->flags = CTL_LLF_COMPARE | flags;
9271
9272	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9273	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9274	return (retval);
9275}
9276
9277int
9278ctl_verify(struct ctl_scsiio *ctsio)
9279{
9280	struct ctl_lun *lun;
9281	struct ctl_lba_len_flags *lbalen;
9282	uint64_t lba;
9283	uint32_t num_blocks;
9284	int bytchk, flags;
9285	int retval;
9286
9287	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9288
9289	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9290
9291	bytchk = 0;
9292	flags = CTL_LLF_FUA;
9293	retval = CTL_RETVAL_COMPLETE;
9294
9295	switch (ctsio->cdb[0]) {
9296	case VERIFY_10: {
9297		struct scsi_verify_10 *cdb;
9298
9299		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9300		if (cdb->byte2 & SVFY_BYTCHK)
9301			bytchk = 1;
9302		if (cdb->byte2 & SVFY_DPO)
9303			flags |= CTL_LLF_DPO;
9304		lba = scsi_4btoul(cdb->addr);
9305		num_blocks = scsi_2btoul(cdb->length);
9306		break;
9307	}
9308	case VERIFY_12: {
9309		struct scsi_verify_12 *cdb;
9310
9311		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9312		if (cdb->byte2 & SVFY_BYTCHK)
9313			bytchk = 1;
9314		if (cdb->byte2 & SVFY_DPO)
9315			flags |= CTL_LLF_DPO;
9316		lba = scsi_4btoul(cdb->addr);
9317		num_blocks = scsi_4btoul(cdb->length);
9318		break;
9319	}
9320	case VERIFY_16: {
9321		struct scsi_rw_16 *cdb;
9322
9323		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9324		if (cdb->byte2 & SVFY_BYTCHK)
9325			bytchk = 1;
9326		if (cdb->byte2 & SVFY_DPO)
9327			flags |= CTL_LLF_DPO;
9328		lba = scsi_8btou64(cdb->addr);
9329		num_blocks = scsi_4btoul(cdb->length);
9330		break;
9331	}
9332	default:
9333		/*
9334		 * We got a command we don't support.  This shouldn't
9335		 * happen, commands should be filtered out above us.
9336		 */
9337		ctl_set_invalid_opcode(ctsio);
9338		ctl_done((union ctl_io *)ctsio);
9339		return (CTL_RETVAL_COMPLETE);
9340	}
9341
9342	/*
9343	 * The first check is to make sure we're in bounds, the second
9344	 * check is to catch wrap-around problems.  If the lba + num blocks
9345	 * is less than the lba, then we've wrapped around and the block
9346	 * range is invalid anyway.
9347	 */
9348	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9349	 || ((lba + num_blocks) < lba)) {
9350		ctl_set_lba_out_of_range(ctsio);
9351		ctl_done((union ctl_io *)ctsio);
9352		return (CTL_RETVAL_COMPLETE);
9353	}
9354
9355	/*
9356	 * According to SBC-3, a transfer length of 0 is not an error.
9357	 */
9358	if (num_blocks == 0) {
9359		ctl_set_success(ctsio);
9360		ctl_done((union ctl_io *)ctsio);
9361		return (CTL_RETVAL_COMPLETE);
9362	}
9363
9364	lbalen = (struct ctl_lba_len_flags *)
9365	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9366	lbalen->lba = lba;
9367	lbalen->len = num_blocks;
9368	if (bytchk) {
9369		lbalen->flags = CTL_LLF_COMPARE | flags;
9370		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9371	} else {
9372		lbalen->flags = CTL_LLF_VERIFY | flags;
9373		ctsio->kern_total_len = 0;
9374	}
9375	ctsio->kern_rel_offset = 0;
9376
9377	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9378	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9379	return (retval);
9380}
9381
9382int
9383ctl_report_luns(struct ctl_scsiio *ctsio)
9384{
9385	struct scsi_report_luns *cdb;
9386	struct scsi_report_luns_data *lun_data;
9387	struct ctl_lun *lun, *request_lun;
9388	int num_luns, retval;
9389	uint32_t alloc_len, lun_datalen;
9390	int num_filled, well_known;
9391	uint32_t initidx, targ_lun_id, lun_id;
9392
9393	retval = CTL_RETVAL_COMPLETE;
9394	well_known = 0;
9395
9396	cdb = (struct scsi_report_luns *)ctsio->cdb;
9397
9398	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9399
9400	mtx_lock(&control_softc->ctl_lock);
9401	num_luns = control_softc->num_luns;
9402	mtx_unlock(&control_softc->ctl_lock);
9403
9404	switch (cdb->select_report) {
9405	case RPL_REPORT_DEFAULT:
9406	case RPL_REPORT_ALL:
9407		break;
9408	case RPL_REPORT_WELLKNOWN:
9409		well_known = 1;
9410		num_luns = 0;
9411		break;
9412	default:
9413		ctl_set_invalid_field(ctsio,
9414				      /*sks_valid*/ 1,
9415				      /*command*/ 1,
9416				      /*field*/ 2,
9417				      /*bit_valid*/ 0,
9418				      /*bit*/ 0);
9419		ctl_done((union ctl_io *)ctsio);
9420		return (retval);
9421		break; /* NOTREACHED */
9422	}
9423
9424	alloc_len = scsi_4btoul(cdb->length);
9425	/*
9426	 * The initiator has to allocate at least 16 bytes for this request,
9427	 * so he can at least get the header and the first LUN.  Otherwise
9428	 * we reject the request (per SPC-3 rev 14, section 6.21).
9429	 */
9430	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9431	    sizeof(struct scsi_report_luns_lundata))) {
9432		ctl_set_invalid_field(ctsio,
9433				      /*sks_valid*/ 1,
9434				      /*command*/ 1,
9435				      /*field*/ 6,
9436				      /*bit_valid*/ 0,
9437				      /*bit*/ 0);
9438		ctl_done((union ctl_io *)ctsio);
9439		return (retval);
9440	}
9441
9442	request_lun = (struct ctl_lun *)
9443		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9444
9445	lun_datalen = sizeof(*lun_data) +
9446		(num_luns * sizeof(struct scsi_report_luns_lundata));
9447
9448	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9449	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9450	ctsio->kern_sg_entries = 0;
9451
9452	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9453
9454	mtx_lock(&control_softc->ctl_lock);
9455	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9456		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9457		if (lun_id >= CTL_MAX_LUNS)
9458			continue;
9459		lun = control_softc->ctl_luns[lun_id];
9460		if (lun == NULL)
9461			continue;
9462
9463		if (targ_lun_id <= 0xff) {
9464			/*
9465			 * Peripheral addressing method, bus number 0.
9466			 */
9467			lun_data->luns[num_filled].lundata[0] =
9468				RPL_LUNDATA_ATYP_PERIPH;
9469			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9470			num_filled++;
9471		} else if (targ_lun_id <= 0x3fff) {
9472			/*
9473			 * Flat addressing method.
9474			 */
9475			lun_data->luns[num_filled].lundata[0] =
9476				RPL_LUNDATA_ATYP_FLAT |
9477				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9478#ifdef OLDCTLHEADERS
9479				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9480				(targ_lun_id & SRLD_BUS_LUN_MASK);
9481#endif
9482			lun_data->luns[num_filled].lundata[1] =
9483#ifdef OLDCTLHEADERS
9484				targ_lun_id >> SRLD_BUS_LUN_BITS;
9485#endif
9486				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9487			num_filled++;
9488		} else {
9489			printf("ctl_report_luns: bogus LUN number %jd, "
9490			       "skipping\n", (intmax_t)targ_lun_id);
9491		}
9492		/*
9493		 * According to SPC-3, rev 14 section 6.21:
9494		 *
9495		 * "The execution of a REPORT LUNS command to any valid and
9496		 * installed logical unit shall clear the REPORTED LUNS DATA
9497		 * HAS CHANGED unit attention condition for all logical
9498		 * units of that target with respect to the requesting
9499		 * initiator. A valid and installed logical unit is one
9500		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9501		 * INQUIRY data (see 6.4.2)."
9502		 *
9503		 * If request_lun is NULL, the LUN this report luns command
9504		 * was issued to is either disabled or doesn't exist. In that
9505		 * case, we shouldn't clear any pending lun change unit
9506		 * attention.
9507		 */
9508		if (request_lun != NULL) {
9509			mtx_lock(&lun->lun_lock);
9510			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9511			mtx_unlock(&lun->lun_lock);
9512		}
9513	}
9514	mtx_unlock(&control_softc->ctl_lock);
9515
9516	/*
9517	 * It's quite possible that we've returned fewer LUNs than we allocated
9518	 * space for.  Trim it.
9519	 */
9520	lun_datalen = sizeof(*lun_data) +
9521		(num_filled * sizeof(struct scsi_report_luns_lundata));
9522
9523	if (lun_datalen < alloc_len) {
9524		ctsio->residual = alloc_len - lun_datalen;
9525		ctsio->kern_data_len = lun_datalen;
9526		ctsio->kern_total_len = lun_datalen;
9527	} else {
9528		ctsio->residual = 0;
9529		ctsio->kern_data_len = alloc_len;
9530		ctsio->kern_total_len = alloc_len;
9531	}
9532	ctsio->kern_data_resid = 0;
9533	ctsio->kern_rel_offset = 0;
9534	ctsio->kern_sg_entries = 0;
9535
9536	/*
9537	 * We set this to the actual data length, regardless of how much
9538	 * space we actually have to return results.  If the user looks at
9539	 * this value, he'll know whether or not he allocated enough space
9540	 * and reissue the command if necessary.  We don't support well
9541	 * known logical units, so if the user asks for that, return none.
9542	 */
9543	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9544
9545	/*
9546	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9547	 * this request.
9548	 */
9549	ctsio->scsi_status = SCSI_STATUS_OK;
9550
9551	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9552	ctsio->be_move_done = ctl_config_move_done;
9553	ctl_datamove((union ctl_io *)ctsio);
9554
9555	return (retval);
9556}
9557
9558int
9559ctl_request_sense(struct ctl_scsiio *ctsio)
9560{
9561	struct scsi_request_sense *cdb;
9562	struct scsi_sense_data *sense_ptr;
9563	struct ctl_lun *lun;
9564	uint32_t initidx;
9565	int have_error;
9566	scsi_sense_data_type sense_format;
9567
9568	cdb = (struct scsi_request_sense *)ctsio->cdb;
9569
9570	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9571
9572	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9573
9574	/*
9575	 * Determine which sense format the user wants.
9576	 */
9577	if (cdb->byte2 & SRS_DESC)
9578		sense_format = SSD_TYPE_DESC;
9579	else
9580		sense_format = SSD_TYPE_FIXED;
9581
9582	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9583	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9584	ctsio->kern_sg_entries = 0;
9585
9586	/*
9587	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9588	 * larger than the largest allowed value for the length field in the
9589	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9590	 */
9591	ctsio->residual = 0;
9592	ctsio->kern_data_len = cdb->length;
9593	ctsio->kern_total_len = cdb->length;
9594
9595	ctsio->kern_data_resid = 0;
9596	ctsio->kern_rel_offset = 0;
9597	ctsio->kern_sg_entries = 0;
9598
9599	/*
9600	 * If we don't have a LUN, we don't have any pending sense.
9601	 */
9602	if (lun == NULL)
9603		goto no_sense;
9604
9605	have_error = 0;
9606	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9607	/*
9608	 * Check for pending sense, and then for pending unit attentions.
9609	 * Pending sense gets returned first, then pending unit attentions.
9610	 */
9611	mtx_lock(&lun->lun_lock);
9612#ifdef CTL_WITH_CA
9613	if (ctl_is_set(lun->have_ca, initidx)) {
9614		scsi_sense_data_type stored_format;
9615
9616		/*
9617		 * Check to see which sense format was used for the stored
9618		 * sense data.
9619		 */
9620		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9621
9622		/*
9623		 * If the user requested a different sense format than the
9624		 * one we stored, then we need to convert it to the other
9625		 * format.  If we're going from descriptor to fixed format
9626		 * sense data, we may lose things in translation, depending
9627		 * on what options were used.
9628		 *
9629		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9630		 * for some reason we'll just copy it out as-is.
9631		 */
9632		if ((stored_format == SSD_TYPE_FIXED)
9633		 && (sense_format == SSD_TYPE_DESC))
9634			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9635			    &lun->pending_sense[initidx],
9636			    (struct scsi_sense_data_desc *)sense_ptr);
9637		else if ((stored_format == SSD_TYPE_DESC)
9638		      && (sense_format == SSD_TYPE_FIXED))
9639			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9640			    &lun->pending_sense[initidx],
9641			    (struct scsi_sense_data_fixed *)sense_ptr);
9642		else
9643			memcpy(sense_ptr, &lun->pending_sense[initidx],
9644			       ctl_min(sizeof(*sense_ptr),
9645			       sizeof(lun->pending_sense[initidx])));
9646
9647		ctl_clear_mask(lun->have_ca, initidx);
9648		have_error = 1;
9649	} else
9650#endif
9651	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9652		ctl_ua_type ua_type;
9653
9654		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9655				       sense_ptr, sense_format);
9656		if (ua_type != CTL_UA_NONE)
9657			have_error = 1;
9658	}
9659	mtx_unlock(&lun->lun_lock);
9660
9661	/*
9662	 * We already have a pending error, return it.
9663	 */
9664	if (have_error != 0) {
9665		/*
9666		 * We report the SCSI status as OK, since the status of the
9667		 * request sense command itself is OK.
9668		 */
9669		ctsio->scsi_status = SCSI_STATUS_OK;
9670
9671		/*
9672		 * We report 0 for the sense length, because we aren't doing
9673		 * autosense in this case.  We're reporting sense as
9674		 * parameter data.
9675		 */
9676		ctsio->sense_len = 0;
9677		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9678		ctsio->be_move_done = ctl_config_move_done;
9679		ctl_datamove((union ctl_io *)ctsio);
9680
9681		return (CTL_RETVAL_COMPLETE);
9682	}
9683
9684no_sense:
9685
9686	/*
9687	 * No sense information to report, so we report that everything is
9688	 * okay.
9689	 */
9690	ctl_set_sense_data(sense_ptr,
9691			   lun,
9692			   sense_format,
9693			   /*current_error*/ 1,
9694			   /*sense_key*/ SSD_KEY_NO_SENSE,
9695			   /*asc*/ 0x00,
9696			   /*ascq*/ 0x00,
9697			   SSD_ELEM_NONE);
9698
9699	ctsio->scsi_status = SCSI_STATUS_OK;
9700
9701	/*
9702	 * We report 0 for the sense length, because we aren't doing
9703	 * autosense in this case.  We're reporting sense as parameter data.
9704	 */
9705	ctsio->sense_len = 0;
9706	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9707	ctsio->be_move_done = ctl_config_move_done;
9708	ctl_datamove((union ctl_io *)ctsio);
9709
9710	return (CTL_RETVAL_COMPLETE);
9711}
9712
9713int
9714ctl_tur(struct ctl_scsiio *ctsio)
9715{
9716	struct ctl_lun *lun;
9717
9718	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9719
9720	CTL_DEBUG_PRINT(("ctl_tur\n"));
9721
9722	if (lun == NULL)
9723		return (EINVAL);
9724
9725	ctsio->scsi_status = SCSI_STATUS_OK;
9726	ctsio->io_hdr.status = CTL_SUCCESS;
9727
9728	ctl_done((union ctl_io *)ctsio);
9729
9730	return (CTL_RETVAL_COMPLETE);
9731}
9732
9733#ifdef notyet
9734static int
9735ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9736{
9737
9738}
9739#endif
9740
9741static int
9742ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9743{
9744	struct scsi_vpd_supported_pages *pages;
9745	int sup_page_size;
9746	struct ctl_lun *lun;
9747
9748	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9749
9750	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9751	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9752	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9753	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9754	ctsio->kern_sg_entries = 0;
9755
9756	if (sup_page_size < alloc_len) {
9757		ctsio->residual = alloc_len - sup_page_size;
9758		ctsio->kern_data_len = sup_page_size;
9759		ctsio->kern_total_len = sup_page_size;
9760	} else {
9761		ctsio->residual = 0;
9762		ctsio->kern_data_len = alloc_len;
9763		ctsio->kern_total_len = alloc_len;
9764	}
9765	ctsio->kern_data_resid = 0;
9766	ctsio->kern_rel_offset = 0;
9767	ctsio->kern_sg_entries = 0;
9768
9769	/*
9770	 * The control device is always connected.  The disk device, on the
9771	 * other hand, may not be online all the time.  Need to change this
9772	 * to figure out whether the disk device is actually online or not.
9773	 */
9774	if (lun != NULL)
9775		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9776				lun->be_lun->lun_type;
9777	else
9778		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9779
9780	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9781	/* Supported VPD pages */
9782	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9783	/* Serial Number */
9784	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9785	/* Device Identification */
9786	pages->page_list[2] = SVPD_DEVICE_ID;
9787	/* Extended INQUIRY Data */
9788	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9789	/* Mode Page Policy */
9790	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9791	/* SCSI Ports */
9792	pages->page_list[5] = SVPD_SCSI_PORTS;
9793	/* Third-party Copy */
9794	pages->page_list[6] = SVPD_SCSI_TPC;
9795	/* Block limits */
9796	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9797	/* Block Device Characteristics */
9798	pages->page_list[8] = SVPD_BDC;
9799	/* Logical Block Provisioning */
9800	pages->page_list[9] = SVPD_LBP;
9801
9802	ctsio->scsi_status = SCSI_STATUS_OK;
9803
9804	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9805	ctsio->be_move_done = ctl_config_move_done;
9806	ctl_datamove((union ctl_io *)ctsio);
9807
9808	return (CTL_RETVAL_COMPLETE);
9809}
9810
9811static int
9812ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9813{
9814	struct scsi_vpd_unit_serial_number *sn_ptr;
9815	struct ctl_lun *lun;
9816
9817	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9818
9819	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9820	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9821	ctsio->kern_sg_entries = 0;
9822
9823	if (sizeof(*sn_ptr) < alloc_len) {
9824		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9825		ctsio->kern_data_len = sizeof(*sn_ptr);
9826		ctsio->kern_total_len = sizeof(*sn_ptr);
9827	} else {
9828		ctsio->residual = 0;
9829		ctsio->kern_data_len = alloc_len;
9830		ctsio->kern_total_len = alloc_len;
9831	}
9832	ctsio->kern_data_resid = 0;
9833	ctsio->kern_rel_offset = 0;
9834	ctsio->kern_sg_entries = 0;
9835
9836	/*
9837	 * The control device is always connected.  The disk device, on the
9838	 * other hand, may not be online all the time.  Need to change this
9839	 * to figure out whether the disk device is actually online or not.
9840	 */
9841	if (lun != NULL)
9842		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9843				  lun->be_lun->lun_type;
9844	else
9845		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9846
9847	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9848	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9849	/*
9850	 * If we don't have a LUN, we just leave the serial number as
9851	 * all spaces.
9852	 */
9853	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9854	if (lun != NULL) {
9855		strncpy((char *)sn_ptr->serial_num,
9856			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9857	}
9858	ctsio->scsi_status = SCSI_STATUS_OK;
9859
9860	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9861	ctsio->be_move_done = ctl_config_move_done;
9862	ctl_datamove((union ctl_io *)ctsio);
9863
9864	return (CTL_RETVAL_COMPLETE);
9865}
9866
9867
9868static int
9869ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9870{
9871	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9872	struct ctl_lun *lun;
9873	int data_len;
9874
9875	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9876
9877	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9878	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9879	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9880	ctsio->kern_sg_entries = 0;
9881
9882	if (data_len < alloc_len) {
9883		ctsio->residual = alloc_len - data_len;
9884		ctsio->kern_data_len = data_len;
9885		ctsio->kern_total_len = data_len;
9886	} else {
9887		ctsio->residual = 0;
9888		ctsio->kern_data_len = alloc_len;
9889		ctsio->kern_total_len = alloc_len;
9890	}
9891	ctsio->kern_data_resid = 0;
9892	ctsio->kern_rel_offset = 0;
9893	ctsio->kern_sg_entries = 0;
9894
9895	/*
9896	 * The control device is always connected.  The disk device, on the
9897	 * other hand, may not be online all the time.
9898	 */
9899	if (lun != NULL)
9900		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9901				     lun->be_lun->lun_type;
9902	else
9903		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9904	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9905	eid_ptr->page_length = data_len - 4;
9906	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9907	eid_ptr->flags3 = SVPD_EID_V_SUP;
9908
9909	ctsio->scsi_status = SCSI_STATUS_OK;
9910	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9911	ctsio->be_move_done = ctl_config_move_done;
9912	ctl_datamove((union ctl_io *)ctsio);
9913
9914	return (CTL_RETVAL_COMPLETE);
9915}
9916
9917static int
9918ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9919{
9920	struct scsi_vpd_mode_page_policy *mpp_ptr;
9921	struct ctl_lun *lun;
9922	int data_len;
9923
9924	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9925
9926	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9927	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9928
9929	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9930	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9931	ctsio->kern_sg_entries = 0;
9932
9933	if (data_len < alloc_len) {
9934		ctsio->residual = alloc_len - data_len;
9935		ctsio->kern_data_len = data_len;
9936		ctsio->kern_total_len = data_len;
9937	} else {
9938		ctsio->residual = 0;
9939		ctsio->kern_data_len = alloc_len;
9940		ctsio->kern_total_len = alloc_len;
9941	}
9942	ctsio->kern_data_resid = 0;
9943	ctsio->kern_rel_offset = 0;
9944	ctsio->kern_sg_entries = 0;
9945
9946	/*
9947	 * The control device is always connected.  The disk device, on the
9948	 * other hand, may not be online all the time.
9949	 */
9950	if (lun != NULL)
9951		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9952				     lun->be_lun->lun_type;
9953	else
9954		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9955	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9956	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9957	mpp_ptr->descr[0].page_code = 0x3f;
9958	mpp_ptr->descr[0].subpage_code = 0xff;
9959	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9960
9961	ctsio->scsi_status = SCSI_STATUS_OK;
9962	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9963	ctsio->be_move_done = ctl_config_move_done;
9964	ctl_datamove((union ctl_io *)ctsio);
9965
9966	return (CTL_RETVAL_COMPLETE);
9967}
9968
9969static int
9970ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9971{
9972	struct scsi_vpd_device_id *devid_ptr;
9973	struct scsi_vpd_id_descriptor *desc;
9974	struct ctl_softc *ctl_softc;
9975	struct ctl_lun *lun;
9976	struct ctl_port *port;
9977	int data_len;
9978	uint8_t proto;
9979
9980	ctl_softc = control_softc;
9981
9982	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9983	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9984
9985	data_len = sizeof(struct scsi_vpd_device_id) +
9986	    sizeof(struct scsi_vpd_id_descriptor) +
9987		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9988	    sizeof(struct scsi_vpd_id_descriptor) +
9989		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9990	if (lun && lun->lun_devid)
9991		data_len += lun->lun_devid->len;
9992	if (port->port_devid)
9993		data_len += port->port_devid->len;
9994	if (port->target_devid)
9995		data_len += port->target_devid->len;
9996
9997	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9998	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9999	ctsio->kern_sg_entries = 0;
10000
10001	if (data_len < alloc_len) {
10002		ctsio->residual = alloc_len - data_len;
10003		ctsio->kern_data_len = data_len;
10004		ctsio->kern_total_len = data_len;
10005	} else {
10006		ctsio->residual = 0;
10007		ctsio->kern_data_len = alloc_len;
10008		ctsio->kern_total_len = alloc_len;
10009	}
10010	ctsio->kern_data_resid = 0;
10011	ctsio->kern_rel_offset = 0;
10012	ctsio->kern_sg_entries = 0;
10013
10014	/*
10015	 * The control device is always connected.  The disk device, on the
10016	 * other hand, may not be online all the time.
10017	 */
10018	if (lun != NULL)
10019		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10020				     lun->be_lun->lun_type;
10021	else
10022		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10023	devid_ptr->page_code = SVPD_DEVICE_ID;
10024	scsi_ulto2b(data_len - 4, devid_ptr->length);
10025
10026	if (port->port_type == CTL_PORT_FC)
10027		proto = SCSI_PROTO_FC << 4;
10028	else if (port->port_type == CTL_PORT_ISCSI)
10029		proto = SCSI_PROTO_ISCSI << 4;
10030	else
10031		proto = SCSI_PROTO_SPI << 4;
10032	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10033
10034	/*
10035	 * We're using a LUN association here.  i.e., this device ID is a
10036	 * per-LUN identifier.
10037	 */
10038	if (lun && lun->lun_devid) {
10039		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10040		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10041		    lun->lun_devid->len);
10042	}
10043
10044	/*
10045	 * This is for the WWPN which is a port association.
10046	 */
10047	if (port->port_devid) {
10048		memcpy(desc, port->port_devid->data, port->port_devid->len);
10049		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10050		    port->port_devid->len);
10051	}
10052
10053	/*
10054	 * This is for the Relative Target Port(type 4h) identifier
10055	 */
10056	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10057	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10058	    SVPD_ID_TYPE_RELTARG;
10059	desc->length = 4;
10060	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10061	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10062	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10063
10064	/*
10065	 * This is for the Target Port Group(type 5h) identifier
10066	 */
10067	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10068	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10069	    SVPD_ID_TYPE_TPORTGRP;
10070	desc->length = 4;
10071	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10072	    &desc->identifier[2]);
10073	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10074	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10075
10076	/*
10077	 * This is for the Target identifier
10078	 */
10079	if (port->target_devid) {
10080		memcpy(desc, port->target_devid->data, port->target_devid->len);
10081	}
10082
10083	ctsio->scsi_status = SCSI_STATUS_OK;
10084	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10085	ctsio->be_move_done = ctl_config_move_done;
10086	ctl_datamove((union ctl_io *)ctsio);
10087
10088	return (CTL_RETVAL_COMPLETE);
10089}
10090
10091static int
10092ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10093{
10094	struct ctl_softc *softc = control_softc;
10095	struct scsi_vpd_scsi_ports *sp;
10096	struct scsi_vpd_port_designation *pd;
10097	struct scsi_vpd_port_designation_cont *pdc;
10098	struct ctl_lun *lun;
10099	struct ctl_port *port;
10100	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10101	int num_target_port_groups, single;
10102
10103	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10104
10105	single = ctl_is_single;
10106	if (single)
10107		num_target_port_groups = 1;
10108	else
10109		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10110	num_target_ports = 0;
10111	iid_len = 0;
10112	id_len = 0;
10113	mtx_lock(&softc->ctl_lock);
10114	STAILQ_FOREACH(port, &softc->port_list, links) {
10115		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10116			continue;
10117		if (lun != NULL &&
10118		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10119		    CTL_MAX_LUNS)
10120			continue;
10121		num_target_ports++;
10122		if (port->init_devid)
10123			iid_len += port->init_devid->len;
10124		if (port->port_devid)
10125			id_len += port->port_devid->len;
10126	}
10127	mtx_unlock(&softc->ctl_lock);
10128
10129	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10130	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10131	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10132	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10133	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10134	ctsio->kern_sg_entries = 0;
10135
10136	if (data_len < alloc_len) {
10137		ctsio->residual = alloc_len - data_len;
10138		ctsio->kern_data_len = data_len;
10139		ctsio->kern_total_len = data_len;
10140	} else {
10141		ctsio->residual = 0;
10142		ctsio->kern_data_len = alloc_len;
10143		ctsio->kern_total_len = alloc_len;
10144	}
10145	ctsio->kern_data_resid = 0;
10146	ctsio->kern_rel_offset = 0;
10147	ctsio->kern_sg_entries = 0;
10148
10149	/*
10150	 * The control device is always connected.  The disk device, on the
10151	 * other hand, may not be online all the time.  Need to change this
10152	 * to figure out whether the disk device is actually online or not.
10153	 */
10154	if (lun != NULL)
10155		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10156				  lun->be_lun->lun_type;
10157	else
10158		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10159
10160	sp->page_code = SVPD_SCSI_PORTS;
10161	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10162	    sp->page_length);
10163	pd = &sp->design[0];
10164
10165	mtx_lock(&softc->ctl_lock);
10166	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10167		pg = 0;
10168	else
10169		pg = 1;
10170	for (g = 0; g < num_target_port_groups; g++) {
10171		STAILQ_FOREACH(port, &softc->port_list, links) {
10172			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10173				continue;
10174			if (lun != NULL &&
10175			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10176			    CTL_MAX_LUNS)
10177				continue;
10178			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10179			scsi_ulto2b(p, pd->relative_port_id);
10180			if (port->init_devid && g == pg) {
10181				iid_len = port->init_devid->len;
10182				memcpy(pd->initiator_transportid,
10183				    port->init_devid->data, port->init_devid->len);
10184			} else
10185				iid_len = 0;
10186			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10187			pdc = (struct scsi_vpd_port_designation_cont *)
10188			    (&pd->initiator_transportid[iid_len]);
10189			if (port->port_devid && g == pg) {
10190				id_len = port->port_devid->len;
10191				memcpy(pdc->target_port_descriptors,
10192				    port->port_devid->data, port->port_devid->len);
10193			} else
10194				id_len = 0;
10195			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10196			pd = (struct scsi_vpd_port_designation *)
10197			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10198		}
10199	}
10200	mtx_unlock(&softc->ctl_lock);
10201
10202	ctsio->scsi_status = SCSI_STATUS_OK;
10203	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10204	ctsio->be_move_done = ctl_config_move_done;
10205	ctl_datamove((union ctl_io *)ctsio);
10206
10207	return (CTL_RETVAL_COMPLETE);
10208}
10209
10210static int
10211ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10212{
10213	struct scsi_vpd_block_limits *bl_ptr;
10214	struct ctl_lun *lun;
10215	int bs;
10216
10217	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10218
10219	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10220	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10221	ctsio->kern_sg_entries = 0;
10222
10223	if (sizeof(*bl_ptr) < alloc_len) {
10224		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10225		ctsio->kern_data_len = sizeof(*bl_ptr);
10226		ctsio->kern_total_len = sizeof(*bl_ptr);
10227	} else {
10228		ctsio->residual = 0;
10229		ctsio->kern_data_len = alloc_len;
10230		ctsio->kern_total_len = alloc_len;
10231	}
10232	ctsio->kern_data_resid = 0;
10233	ctsio->kern_rel_offset = 0;
10234	ctsio->kern_sg_entries = 0;
10235
10236	/*
10237	 * The control device is always connected.  The disk device, on the
10238	 * other hand, may not be online all the time.  Need to change this
10239	 * to figure out whether the disk device is actually online or not.
10240	 */
10241	if (lun != NULL)
10242		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10243				  lun->be_lun->lun_type;
10244	else
10245		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10246
10247	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10248	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10249	bl_ptr->max_cmp_write_len = 0xff;
10250	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10251	if (lun != NULL) {
10252		bs = lun->be_lun->blocksize;
10253		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10254		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10255			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10256			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10257			if (lun->be_lun->pblockexp != 0) {
10258				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10259				    bl_ptr->opt_unmap_grain);
10260				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10261				    bl_ptr->unmap_grain_align);
10262			}
10263		}
10264		scsi_ulto4b(lun->be_lun->atomicblock,
10265		    bl_ptr->max_atomic_transfer_length);
10266		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10267		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10268	}
10269	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10270
10271	ctsio->scsi_status = SCSI_STATUS_OK;
10272	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10273	ctsio->be_move_done = ctl_config_move_done;
10274	ctl_datamove((union ctl_io *)ctsio);
10275
10276	return (CTL_RETVAL_COMPLETE);
10277}
10278
10279static int
10280ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10281{
10282	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10283	struct ctl_lun *lun;
10284
10285	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10286
10287	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10288	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10289	ctsio->kern_sg_entries = 0;
10290
10291	if (sizeof(*bdc_ptr) < alloc_len) {
10292		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10293		ctsio->kern_data_len = sizeof(*bdc_ptr);
10294		ctsio->kern_total_len = sizeof(*bdc_ptr);
10295	} else {
10296		ctsio->residual = 0;
10297		ctsio->kern_data_len = alloc_len;
10298		ctsio->kern_total_len = alloc_len;
10299	}
10300	ctsio->kern_data_resid = 0;
10301	ctsio->kern_rel_offset = 0;
10302	ctsio->kern_sg_entries = 0;
10303
10304	/*
10305	 * The control device is always connected.  The disk device, on the
10306	 * other hand, may not be online all the time.  Need to change this
10307	 * to figure out whether the disk device is actually online or not.
10308	 */
10309	if (lun != NULL)
10310		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10311				  lun->be_lun->lun_type;
10312	else
10313		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10314	bdc_ptr->page_code = SVPD_BDC;
10315	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10316	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10317	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10318
10319	ctsio->scsi_status = SCSI_STATUS_OK;
10320	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10321	ctsio->be_move_done = ctl_config_move_done;
10322	ctl_datamove((union ctl_io *)ctsio);
10323
10324	return (CTL_RETVAL_COMPLETE);
10325}
10326
10327static int
10328ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10329{
10330	struct scsi_vpd_logical_block_prov *lbp_ptr;
10331	struct ctl_lun *lun;
10332
10333	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10334
10335	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10336	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10337	ctsio->kern_sg_entries = 0;
10338
10339	if (sizeof(*lbp_ptr) < alloc_len) {
10340		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10341		ctsio->kern_data_len = sizeof(*lbp_ptr);
10342		ctsio->kern_total_len = sizeof(*lbp_ptr);
10343	} else {
10344		ctsio->residual = 0;
10345		ctsio->kern_data_len = alloc_len;
10346		ctsio->kern_total_len = alloc_len;
10347	}
10348	ctsio->kern_data_resid = 0;
10349	ctsio->kern_rel_offset = 0;
10350	ctsio->kern_sg_entries = 0;
10351
10352	/*
10353	 * The control device is always connected.  The disk device, on the
10354	 * other hand, may not be online all the time.  Need to change this
10355	 * to figure out whether the disk device is actually online or not.
10356	 */
10357	if (lun != NULL)
10358		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10359				  lun->be_lun->lun_type;
10360	else
10361		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10362
10363	lbp_ptr->page_code = SVPD_LBP;
10364	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10365	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10366		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10367		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10368		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10369	}
10370
10371	ctsio->scsi_status = SCSI_STATUS_OK;
10372	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10373	ctsio->be_move_done = ctl_config_move_done;
10374	ctl_datamove((union ctl_io *)ctsio);
10375
10376	return (CTL_RETVAL_COMPLETE);
10377}
10378
10379static int
10380ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10381{
10382	struct scsi_inquiry *cdb;
10383	struct ctl_lun *lun;
10384	int alloc_len, retval;
10385
10386	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10387	cdb = (struct scsi_inquiry *)ctsio->cdb;
10388
10389	retval = CTL_RETVAL_COMPLETE;
10390
10391	alloc_len = scsi_2btoul(cdb->length);
10392
10393	switch (cdb->page_code) {
10394	case SVPD_SUPPORTED_PAGES:
10395		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10396		break;
10397	case SVPD_UNIT_SERIAL_NUMBER:
10398		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10399		break;
10400	case SVPD_DEVICE_ID:
10401		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10402		break;
10403	case SVPD_EXTENDED_INQUIRY_DATA:
10404		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10405		break;
10406	case SVPD_MODE_PAGE_POLICY:
10407		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10408		break;
10409	case SVPD_SCSI_PORTS:
10410		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10411		break;
10412	case SVPD_SCSI_TPC:
10413		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10414		break;
10415	case SVPD_BLOCK_LIMITS:
10416		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10417		break;
10418	case SVPD_BDC:
10419		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10420		break;
10421	case SVPD_LBP:
10422		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10423		break;
10424	default:
10425		ctl_set_invalid_field(ctsio,
10426				      /*sks_valid*/ 1,
10427				      /*command*/ 1,
10428				      /*field*/ 2,
10429				      /*bit_valid*/ 0,
10430				      /*bit*/ 0);
10431		ctl_done((union ctl_io *)ctsio);
10432		retval = CTL_RETVAL_COMPLETE;
10433		break;
10434	}
10435
10436	return (retval);
10437}
10438
10439static int
10440ctl_inquiry_std(struct ctl_scsiio *ctsio)
10441{
10442	struct scsi_inquiry_data *inq_ptr;
10443	struct scsi_inquiry *cdb;
10444	struct ctl_softc *ctl_softc;
10445	struct ctl_lun *lun;
10446	char *val;
10447	uint32_t alloc_len, data_len;
10448	ctl_port_type port_type;
10449
10450	ctl_softc = control_softc;
10451
10452	/*
10453	 * Figure out whether we're talking to a Fibre Channel port or not.
10454	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10455	 * SCSI front ends.
10456	 */
10457	port_type = ctl_softc->ctl_ports[
10458	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10459	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10460		port_type = CTL_PORT_SCSI;
10461
10462	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10463	cdb = (struct scsi_inquiry *)ctsio->cdb;
10464	alloc_len = scsi_2btoul(cdb->length);
10465
10466	/*
10467	 * We malloc the full inquiry data size here and fill it
10468	 * in.  If the user only asks for less, we'll give him
10469	 * that much.
10470	 */
10471	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10472	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10473	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10474	ctsio->kern_sg_entries = 0;
10475	ctsio->kern_data_resid = 0;
10476	ctsio->kern_rel_offset = 0;
10477
10478	if (data_len < alloc_len) {
10479		ctsio->residual = alloc_len - data_len;
10480		ctsio->kern_data_len = data_len;
10481		ctsio->kern_total_len = data_len;
10482	} else {
10483		ctsio->residual = 0;
10484		ctsio->kern_data_len = alloc_len;
10485		ctsio->kern_total_len = alloc_len;
10486	}
10487
10488	/*
10489	 * If we have a LUN configured, report it as connected.  Otherwise,
10490	 * report that it is offline or no device is supported, depending
10491	 * on the value of inquiry_pq_no_lun.
10492	 *
10493	 * According to the spec (SPC-4 r34), the peripheral qualifier
10494	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10495	 *
10496	 * "A peripheral device having the specified peripheral device type
10497	 * is not connected to this logical unit. However, the device
10498	 * server is capable of supporting the specified peripheral device
10499	 * type on this logical unit."
10500	 *
10501	 * According to the same spec, the peripheral qualifier
10502	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10503	 *
10504	 * "The device server is not capable of supporting a peripheral
10505	 * device on this logical unit. For this peripheral qualifier the
10506	 * peripheral device type shall be set to 1Fh. All other peripheral
10507	 * device type values are reserved for this peripheral qualifier."
10508	 *
10509	 * Given the text, it would seem that we probably want to report that
10510	 * the LUN is offline here.  There is no LUN connected, but we can
10511	 * support a LUN at the given LUN number.
10512	 *
10513	 * In the real world, though, it sounds like things are a little
10514	 * different:
10515	 *
10516	 * - Linux, when presented with a LUN with the offline peripheral
10517	 *   qualifier, will create an sg driver instance for it.  So when
10518	 *   you attach it to CTL, you wind up with a ton of sg driver
10519	 *   instances.  (One for every LUN that Linux bothered to probe.)
10520	 *   Linux does this despite the fact that it issues a REPORT LUNs
10521	 *   to LUN 0 to get the inventory of supported LUNs.
10522	 *
10523	 * - There is other anecdotal evidence (from Emulex folks) about
10524	 *   arrays that use the offline peripheral qualifier for LUNs that
10525	 *   are on the "passive" path in an active/passive array.
10526	 *
10527	 * So the solution is provide a hopefully reasonable default
10528	 * (return bad/no LUN) and allow the user to change the behavior
10529	 * with a tunable/sysctl variable.
10530	 */
10531	if (lun != NULL)
10532		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10533				  lun->be_lun->lun_type;
10534	else if (ctl_softc->inquiry_pq_no_lun == 0)
10535		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10536	else
10537		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10538
10539	/* RMB in byte 2 is 0 */
10540	inq_ptr->version = SCSI_REV_SPC4;
10541
10542	/*
10543	 * According to SAM-3, even if a device only supports a single
10544	 * level of LUN addressing, it should still set the HISUP bit:
10545	 *
10546	 * 4.9.1 Logical unit numbers overview
10547	 *
10548	 * All logical unit number formats described in this standard are
10549	 * hierarchical in structure even when only a single level in that
10550	 * hierarchy is used. The HISUP bit shall be set to one in the
10551	 * standard INQUIRY data (see SPC-2) when any logical unit number
10552	 * format described in this standard is used.  Non-hierarchical
10553	 * formats are outside the scope of this standard.
10554	 *
10555	 * Therefore we set the HiSup bit here.
10556	 *
10557	 * The reponse format is 2, per SPC-3.
10558	 */
10559	inq_ptr->response_format = SID_HiSup | 2;
10560
10561	inq_ptr->additional_length = data_len -
10562	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10563	CTL_DEBUG_PRINT(("additional_length = %d\n",
10564			 inq_ptr->additional_length));
10565
10566	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10567	/* 16 bit addressing */
10568	if (port_type == CTL_PORT_SCSI)
10569		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10570	/* XXX set the SID_MultiP bit here if we're actually going to
10571	   respond on multiple ports */
10572	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10573
10574	/* 16 bit data bus, synchronous transfers */
10575	if (port_type == CTL_PORT_SCSI)
10576		inq_ptr->flags = SID_WBus16 | SID_Sync;
10577	/*
10578	 * XXX KDM do we want to support tagged queueing on the control
10579	 * device at all?
10580	 */
10581	if ((lun == NULL)
10582	 || (lun->be_lun->lun_type != T_PROCESSOR))
10583		inq_ptr->flags |= SID_CmdQue;
10584	/*
10585	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10586	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10587	 * name and 4 bytes for the revision.
10588	 */
10589	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10590	    "vendor")) == NULL) {
10591		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10592	} else {
10593		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10594		strncpy(inq_ptr->vendor, val,
10595		    min(sizeof(inq_ptr->vendor), strlen(val)));
10596	}
10597	if (lun == NULL) {
10598		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10599		    sizeof(inq_ptr->product));
10600	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10601		switch (lun->be_lun->lun_type) {
10602		case T_DIRECT:
10603			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10604			    sizeof(inq_ptr->product));
10605			break;
10606		case T_PROCESSOR:
10607			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10608			    sizeof(inq_ptr->product));
10609			break;
10610		default:
10611			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10612			    sizeof(inq_ptr->product));
10613			break;
10614		}
10615	} else {
10616		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10617		strncpy(inq_ptr->product, val,
10618		    min(sizeof(inq_ptr->product), strlen(val)));
10619	}
10620
10621	/*
10622	 * XXX make this a macro somewhere so it automatically gets
10623	 * incremented when we make changes.
10624	 */
10625	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10626	    "revision")) == NULL) {
10627		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10628	} else {
10629		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10630		strncpy(inq_ptr->revision, val,
10631		    min(sizeof(inq_ptr->revision), strlen(val)));
10632	}
10633
10634	/*
10635	 * For parallel SCSI, we support double transition and single
10636	 * transition clocking.  We also support QAS (Quick Arbitration
10637	 * and Selection) and Information Unit transfers on both the
10638	 * control and array devices.
10639	 */
10640	if (port_type == CTL_PORT_SCSI)
10641		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10642				    SID_SPI_IUS;
10643
10644	/* SAM-5 (no version claimed) */
10645	scsi_ulto2b(0x00A0, inq_ptr->version1);
10646	/* SPC-4 (no version claimed) */
10647	scsi_ulto2b(0x0460, inq_ptr->version2);
10648	if (port_type == CTL_PORT_FC) {
10649		/* FCP-2 ANSI INCITS.350:2003 */
10650		scsi_ulto2b(0x0917, inq_ptr->version3);
10651	} else if (port_type == CTL_PORT_SCSI) {
10652		/* SPI-4 ANSI INCITS.362:200x */
10653		scsi_ulto2b(0x0B56, inq_ptr->version3);
10654	} else if (port_type == CTL_PORT_ISCSI) {
10655		/* iSCSI (no version claimed) */
10656		scsi_ulto2b(0x0960, inq_ptr->version3);
10657	} else if (port_type == CTL_PORT_SAS) {
10658		/* SAS (no version claimed) */
10659		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10660	}
10661
10662	if (lun == NULL) {
10663		/* SBC-4 (no version claimed) */
10664		scsi_ulto2b(0x0600, inq_ptr->version4);
10665	} else {
10666		switch (lun->be_lun->lun_type) {
10667		case T_DIRECT:
10668			/* SBC-4 (no version claimed) */
10669			scsi_ulto2b(0x0600, inq_ptr->version4);
10670			break;
10671		case T_PROCESSOR:
10672		default:
10673			break;
10674		}
10675	}
10676
10677	ctsio->scsi_status = SCSI_STATUS_OK;
10678	if (ctsio->kern_data_len > 0) {
10679		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10680		ctsio->be_move_done = ctl_config_move_done;
10681		ctl_datamove((union ctl_io *)ctsio);
10682	} else {
10683		ctsio->io_hdr.status = CTL_SUCCESS;
10684		ctl_done((union ctl_io *)ctsio);
10685	}
10686
10687	return (CTL_RETVAL_COMPLETE);
10688}
10689
10690int
10691ctl_inquiry(struct ctl_scsiio *ctsio)
10692{
10693	struct scsi_inquiry *cdb;
10694	int retval;
10695
10696	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10697
10698	cdb = (struct scsi_inquiry *)ctsio->cdb;
10699	if (cdb->byte2 & SI_EVPD)
10700		retval = ctl_inquiry_evpd(ctsio);
10701	else if (cdb->page_code == 0)
10702		retval = ctl_inquiry_std(ctsio);
10703	else {
10704		ctl_set_invalid_field(ctsio,
10705				      /*sks_valid*/ 1,
10706				      /*command*/ 1,
10707				      /*field*/ 2,
10708				      /*bit_valid*/ 0,
10709				      /*bit*/ 0);
10710		ctl_done((union ctl_io *)ctsio);
10711		return (CTL_RETVAL_COMPLETE);
10712	}
10713
10714	return (retval);
10715}
10716
10717/*
10718 * For known CDB types, parse the LBA and length.
10719 */
10720static int
10721ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10722{
10723	if (io->io_hdr.io_type != CTL_IO_SCSI)
10724		return (1);
10725
10726	switch (io->scsiio.cdb[0]) {
10727	case COMPARE_AND_WRITE: {
10728		struct scsi_compare_and_write *cdb;
10729
10730		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10731
10732		*lba = scsi_8btou64(cdb->addr);
10733		*len = cdb->length;
10734		break;
10735	}
10736	case READ_6:
10737	case WRITE_6: {
10738		struct scsi_rw_6 *cdb;
10739
10740		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10741
10742		*lba = scsi_3btoul(cdb->addr);
10743		/* only 5 bits are valid in the most significant address byte */
10744		*lba &= 0x1fffff;
10745		*len = cdb->length;
10746		break;
10747	}
10748	case READ_10:
10749	case WRITE_10: {
10750		struct scsi_rw_10 *cdb;
10751
10752		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10753
10754		*lba = scsi_4btoul(cdb->addr);
10755		*len = scsi_2btoul(cdb->length);
10756		break;
10757	}
10758	case WRITE_VERIFY_10: {
10759		struct scsi_write_verify_10 *cdb;
10760
10761		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10762
10763		*lba = scsi_4btoul(cdb->addr);
10764		*len = scsi_2btoul(cdb->length);
10765		break;
10766	}
10767	case READ_12:
10768	case WRITE_12: {
10769		struct scsi_rw_12 *cdb;
10770
10771		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10772
10773		*lba = scsi_4btoul(cdb->addr);
10774		*len = scsi_4btoul(cdb->length);
10775		break;
10776	}
10777	case WRITE_VERIFY_12: {
10778		struct scsi_write_verify_12 *cdb;
10779
10780		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10781
10782		*lba = scsi_4btoul(cdb->addr);
10783		*len = scsi_4btoul(cdb->length);
10784		break;
10785	}
10786	case READ_16:
10787	case WRITE_16:
10788	case WRITE_ATOMIC_16: {
10789		struct scsi_rw_16 *cdb;
10790
10791		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10792
10793		*lba = scsi_8btou64(cdb->addr);
10794		*len = scsi_4btoul(cdb->length);
10795		break;
10796	}
10797	case WRITE_VERIFY_16: {
10798		struct scsi_write_verify_16 *cdb;
10799
10800		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10801
10802		*lba = scsi_8btou64(cdb->addr);
10803		*len = scsi_4btoul(cdb->length);
10804		break;
10805	}
10806	case WRITE_SAME_10: {
10807		struct scsi_write_same_10 *cdb;
10808
10809		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10810
10811		*lba = scsi_4btoul(cdb->addr);
10812		*len = scsi_2btoul(cdb->length);
10813		break;
10814	}
10815	case WRITE_SAME_16: {
10816		struct scsi_write_same_16 *cdb;
10817
10818		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10819
10820		*lba = scsi_8btou64(cdb->addr);
10821		*len = scsi_4btoul(cdb->length);
10822		break;
10823	}
10824	case VERIFY_10: {
10825		struct scsi_verify_10 *cdb;
10826
10827		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10828
10829		*lba = scsi_4btoul(cdb->addr);
10830		*len = scsi_2btoul(cdb->length);
10831		break;
10832	}
10833	case VERIFY_12: {
10834		struct scsi_verify_12 *cdb;
10835
10836		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10837
10838		*lba = scsi_4btoul(cdb->addr);
10839		*len = scsi_4btoul(cdb->length);
10840		break;
10841	}
10842	case VERIFY_16: {
10843		struct scsi_verify_16 *cdb;
10844
10845		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10846
10847		*lba = scsi_8btou64(cdb->addr);
10848		*len = scsi_4btoul(cdb->length);
10849		break;
10850	}
10851	case UNMAP: {
10852		*lba = 0;
10853		*len = UINT64_MAX;
10854		break;
10855	}
10856	default:
10857		return (1);
10858		break; /* NOTREACHED */
10859	}
10860
10861	return (0);
10862}
10863
10864static ctl_action
10865ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10866{
10867	uint64_t endlba1, endlba2;
10868
10869	endlba1 = lba1 + len1 - 1;
10870	endlba2 = lba2 + len2 - 1;
10871
10872	if ((endlba1 < lba2)
10873	 || (endlba2 < lba1))
10874		return (CTL_ACTION_PASS);
10875	else
10876		return (CTL_ACTION_BLOCK);
10877}
10878
10879static int
10880ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10881{
10882	struct ctl_ptr_len_flags *ptrlen;
10883	struct scsi_unmap_desc *buf, *end, *range;
10884	uint64_t lba;
10885	uint32_t len;
10886
10887	/* If not UNMAP -- go other way. */
10888	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10889	    io->scsiio.cdb[0] != UNMAP)
10890		return (CTL_ACTION_ERROR);
10891
10892	/* If UNMAP without data -- block and wait for data. */
10893	ptrlen = (struct ctl_ptr_len_flags *)
10894	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10895	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10896	    ptrlen->ptr == NULL)
10897		return (CTL_ACTION_BLOCK);
10898
10899	/* UNMAP with data -- check for collision. */
10900	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10901	end = buf + ptrlen->len / sizeof(*buf);
10902	for (range = buf; range < end; range++) {
10903		lba = scsi_8btou64(range->lba);
10904		len = scsi_4btoul(range->length);
10905		if ((lba < lba2 + len2) && (lba + len > lba2))
10906			return (CTL_ACTION_BLOCK);
10907	}
10908	return (CTL_ACTION_PASS);
10909}
10910
10911static ctl_action
10912ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10913{
10914	uint64_t lba1, lba2;
10915	uint64_t len1, len2;
10916	int retval;
10917
10918	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10919		return (CTL_ACTION_ERROR);
10920
10921	retval = ctl_extent_check_unmap(io2, lba1, len1);
10922	if (retval != CTL_ACTION_ERROR)
10923		return (retval);
10924
10925	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10926		return (CTL_ACTION_ERROR);
10927
10928	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10929}
10930
10931static ctl_action
10932ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10933    union ctl_io *ooa_io)
10934{
10935	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10936	ctl_serialize_action *serialize_row;
10937
10938	/*
10939	 * The initiator attempted multiple untagged commands at the same
10940	 * time.  Can't do that.
10941	 */
10942	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10943	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10944	 && ((pending_io->io_hdr.nexus.targ_port ==
10945	      ooa_io->io_hdr.nexus.targ_port)
10946	  && (pending_io->io_hdr.nexus.initid.id ==
10947	      ooa_io->io_hdr.nexus.initid.id))
10948	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10949		return (CTL_ACTION_OVERLAP);
10950
10951	/*
10952	 * The initiator attempted to send multiple tagged commands with
10953	 * the same ID.  (It's fine if different initiators have the same
10954	 * tag ID.)
10955	 *
10956	 * Even if all of those conditions are true, we don't kill the I/O
10957	 * if the command ahead of us has been aborted.  We won't end up
10958	 * sending it to the FETD, and it's perfectly legal to resend a
10959	 * command with the same tag number as long as the previous
10960	 * instance of this tag number has been aborted somehow.
10961	 */
10962	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10963	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10964	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10965	 && ((pending_io->io_hdr.nexus.targ_port ==
10966	      ooa_io->io_hdr.nexus.targ_port)
10967	  && (pending_io->io_hdr.nexus.initid.id ==
10968	      ooa_io->io_hdr.nexus.initid.id))
10969	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10970		return (CTL_ACTION_OVERLAP_TAG);
10971
10972	/*
10973	 * If we get a head of queue tag, SAM-3 says that we should
10974	 * immediately execute it.
10975	 *
10976	 * What happens if this command would normally block for some other
10977	 * reason?  e.g. a request sense with a head of queue tag
10978	 * immediately after a write.  Normally that would block, but this
10979	 * will result in its getting executed immediately...
10980	 *
10981	 * We currently return "pass" instead of "skip", so we'll end up
10982	 * going through the rest of the queue to check for overlapped tags.
10983	 *
10984	 * XXX KDM check for other types of blockage first??
10985	 */
10986	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10987		return (CTL_ACTION_PASS);
10988
10989	/*
10990	 * Ordered tags have to block until all items ahead of them
10991	 * have completed.  If we get called with an ordered tag, we always
10992	 * block, if something else is ahead of us in the queue.
10993	 */
10994	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10995		return (CTL_ACTION_BLOCK);
10996
10997	/*
10998	 * Simple tags get blocked until all head of queue and ordered tags
10999	 * ahead of them have completed.  I'm lumping untagged commands in
11000	 * with simple tags here.  XXX KDM is that the right thing to do?
11001	 */
11002	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11003	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11004	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11005	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11006		return (CTL_ACTION_BLOCK);
11007
11008	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11009	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11010
11011	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11012
11013	switch (serialize_row[pending_entry->seridx]) {
11014	case CTL_SER_BLOCK:
11015		return (CTL_ACTION_BLOCK);
11016	case CTL_SER_EXTENT:
11017		return (ctl_extent_check(pending_io, ooa_io));
11018	case CTL_SER_EXTENTOPT:
11019		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11020		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11021			return (ctl_extent_check(pending_io, ooa_io));
11022		/* FALLTHROUGH */
11023	case CTL_SER_PASS:
11024		return (CTL_ACTION_PASS);
11025	case CTL_SER_BLOCKOPT:
11026		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11027		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11028			return (CTL_ACTION_BLOCK);
11029		return (CTL_ACTION_PASS);
11030	case CTL_SER_SKIP:
11031		return (CTL_ACTION_SKIP);
11032	default:
11033		panic("invalid serialization value %d",
11034		      serialize_row[pending_entry->seridx]);
11035	}
11036
11037	return (CTL_ACTION_ERROR);
11038}
11039
11040/*
11041 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11042 * Assumptions:
11043 * - pending_io is generally either incoming, or on the blocked queue
11044 * - starting I/O is the I/O we want to start the check with.
11045 */
11046static ctl_action
11047ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11048	      union ctl_io *starting_io)
11049{
11050	union ctl_io *ooa_io;
11051	ctl_action action;
11052
11053	mtx_assert(&lun->lun_lock, MA_OWNED);
11054
11055	/*
11056	 * Run back along the OOA queue, starting with the current
11057	 * blocked I/O and going through every I/O before it on the
11058	 * queue.  If starting_io is NULL, we'll just end up returning
11059	 * CTL_ACTION_PASS.
11060	 */
11061	for (ooa_io = starting_io; ooa_io != NULL;
11062	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11063	     ooa_links)){
11064
11065		/*
11066		 * This routine just checks to see whether
11067		 * cur_blocked is blocked by ooa_io, which is ahead
11068		 * of it in the queue.  It doesn't queue/dequeue
11069		 * cur_blocked.
11070		 */
11071		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11072		switch (action) {
11073		case CTL_ACTION_BLOCK:
11074		case CTL_ACTION_OVERLAP:
11075		case CTL_ACTION_OVERLAP_TAG:
11076		case CTL_ACTION_SKIP:
11077		case CTL_ACTION_ERROR:
11078			return (action);
11079			break; /* NOTREACHED */
11080		case CTL_ACTION_PASS:
11081			break;
11082		default:
11083			panic("invalid action %d", action);
11084			break;  /* NOTREACHED */
11085		}
11086	}
11087
11088	return (CTL_ACTION_PASS);
11089}
11090
11091/*
11092 * Assumptions:
11093 * - An I/O has just completed, and has been removed from the per-LUN OOA
11094 *   queue, so some items on the blocked queue may now be unblocked.
11095 */
11096static int
11097ctl_check_blocked(struct ctl_lun *lun)
11098{
11099	union ctl_io *cur_blocked, *next_blocked;
11100
11101	mtx_assert(&lun->lun_lock, MA_OWNED);
11102
11103	/*
11104	 * Run forward from the head of the blocked queue, checking each
11105	 * entry against the I/Os prior to it on the OOA queue to see if
11106	 * there is still any blockage.
11107	 *
11108	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11109	 * with our removing a variable on it while it is traversing the
11110	 * list.
11111	 */
11112	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11113	     cur_blocked != NULL; cur_blocked = next_blocked) {
11114		union ctl_io *prev_ooa;
11115		ctl_action action;
11116
11117		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11118							  blocked_links);
11119
11120		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11121						      ctl_ooaq, ooa_links);
11122
11123		/*
11124		 * If cur_blocked happens to be the first item in the OOA
11125		 * queue now, prev_ooa will be NULL, and the action
11126		 * returned will just be CTL_ACTION_PASS.
11127		 */
11128		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11129
11130		switch (action) {
11131		case CTL_ACTION_BLOCK:
11132			/* Nothing to do here, still blocked */
11133			break;
11134		case CTL_ACTION_OVERLAP:
11135		case CTL_ACTION_OVERLAP_TAG:
11136			/*
11137			 * This shouldn't happen!  In theory we've already
11138			 * checked this command for overlap...
11139			 */
11140			break;
11141		case CTL_ACTION_PASS:
11142		case CTL_ACTION_SKIP: {
11143			struct ctl_softc *softc;
11144			const struct ctl_cmd_entry *entry;
11145			uint32_t initidx;
11146			int isc_retval;
11147
11148			/*
11149			 * The skip case shouldn't happen, this transaction
11150			 * should have never made it onto the blocked queue.
11151			 */
11152			/*
11153			 * This I/O is no longer blocked, we can remove it
11154			 * from the blocked queue.  Since this is a TAILQ
11155			 * (doubly linked list), we can do O(1) removals
11156			 * from any place on the list.
11157			 */
11158			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11159				     blocked_links);
11160			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11161
11162			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11163				/*
11164				 * Need to send IO back to original side to
11165				 * run
11166				 */
11167				union ctl_ha_msg msg_info;
11168
11169				msg_info.hdr.original_sc =
11170					cur_blocked->io_hdr.original_sc;
11171				msg_info.hdr.serializing_sc = cur_blocked;
11172				msg_info.hdr.msg_type = CTL_MSG_R2R;
11173				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11174				     &msg_info, sizeof(msg_info), 0)) >
11175				     CTL_HA_STATUS_SUCCESS) {
11176					printf("CTL:Check Blocked error from "
11177					       "ctl_ha_msg_send %d\n",
11178					       isc_retval);
11179				}
11180				break;
11181			}
11182			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11183			softc = control_softc;
11184
11185			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11186
11187			/*
11188			 * Check this I/O for LUN state changes that may
11189			 * have happened while this command was blocked.
11190			 * The LUN state may have been changed by a command
11191			 * ahead of us in the queue, so we need to re-check
11192			 * for any states that can be caused by SCSI
11193			 * commands.
11194			 */
11195			if (ctl_scsiio_lun_check(softc, lun, entry,
11196						 &cur_blocked->scsiio) == 0) {
11197				cur_blocked->io_hdr.flags |=
11198				                      CTL_FLAG_IS_WAS_ON_RTR;
11199				ctl_enqueue_rtr(cur_blocked);
11200			} else
11201				ctl_done(cur_blocked);
11202			break;
11203		}
11204		default:
11205			/*
11206			 * This probably shouldn't happen -- we shouldn't
11207			 * get CTL_ACTION_ERROR, or anything else.
11208			 */
11209			break;
11210		}
11211	}
11212
11213	return (CTL_RETVAL_COMPLETE);
11214}
11215
11216/*
11217 * This routine (with one exception) checks LUN flags that can be set by
11218 * commands ahead of us in the OOA queue.  These flags have to be checked
11219 * when a command initially comes in, and when we pull a command off the
11220 * blocked queue and are preparing to execute it.  The reason we have to
11221 * check these flags for commands on the blocked queue is that the LUN
11222 * state may have been changed by a command ahead of us while we're on the
11223 * blocked queue.
11224 *
11225 * Ordering is somewhat important with these checks, so please pay
11226 * careful attention to the placement of any new checks.
11227 */
11228static int
11229ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11230    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11231{
11232	int retval;
11233	uint32_t residx;
11234
11235	retval = 0;
11236
11237	mtx_assert(&lun->lun_lock, MA_OWNED);
11238
11239	/*
11240	 * If this shelf is a secondary shelf controller, we have to reject
11241	 * any media access commands.
11242	 */
11243#if 0
11244	/* No longer needed for HA */
11245	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11246	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11247		ctl_set_lun_standby(ctsio);
11248		retval = 1;
11249		goto bailout;
11250	}
11251#endif
11252
11253	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11254		if (lun->flags & CTL_LUN_READONLY) {
11255			ctl_set_sense(ctsio, /*current_error*/ 1,
11256			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11257			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11258			retval = 1;
11259			goto bailout;
11260		}
11261		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11262		    .eca_and_aen & SCP_SWP) != 0) {
11263			ctl_set_sense(ctsio, /*current_error*/ 1,
11264			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11265			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11266			retval = 1;
11267			goto bailout;
11268		}
11269	}
11270
11271	/*
11272	 * Check for a reservation conflict.  If this command isn't allowed
11273	 * even on reserved LUNs, and if this initiator isn't the one who
11274	 * reserved us, reject the command with a reservation conflict.
11275	 */
11276	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11277	if ((lun->flags & CTL_LUN_RESERVED)
11278	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11279		if (lun->res_idx != residx) {
11280			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11281			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11282			retval = 1;
11283			goto bailout;
11284		}
11285	}
11286
11287	if ((lun->flags & CTL_LUN_PR_RESERVED)
11288	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11289		/*
11290		 * if we aren't registered or it's a res holder type
11291		 * reservation and this isn't the res holder then set a
11292		 * conflict.
11293		 * NOTE: Commands which might be allowed on write exclusive
11294		 * type reservations are checked in the particular command
11295		 * for a conflict. Read and SSU are the only ones.
11296		 */
11297		if (lun->pr_keys[residx] == 0
11298		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11299			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11300			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11301			retval = 1;
11302			goto bailout;
11303		}
11304
11305	}
11306
11307	if ((lun->flags & CTL_LUN_OFFLINE)
11308	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11309		ctl_set_lun_not_ready(ctsio);
11310		retval = 1;
11311		goto bailout;
11312	}
11313
11314	/*
11315	 * If the LUN is stopped, see if this particular command is allowed
11316	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11317	 */
11318	if ((lun->flags & CTL_LUN_STOPPED)
11319	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11320		/* "Logical unit not ready, initializing cmd. required" */
11321		ctl_set_lun_stopped(ctsio);
11322		retval = 1;
11323		goto bailout;
11324	}
11325
11326	if ((lun->flags & CTL_LUN_INOPERABLE)
11327	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11328		/* "Medium format corrupted" */
11329		ctl_set_medium_format_corrupted(ctsio);
11330		retval = 1;
11331		goto bailout;
11332	}
11333
11334bailout:
11335	return (retval);
11336
11337}
11338
11339static void
11340ctl_failover_io(union ctl_io *io, int have_lock)
11341{
11342	ctl_set_busy(&io->scsiio);
11343	ctl_done(io);
11344}
11345
11346static void
11347ctl_failover(void)
11348{
11349	struct ctl_lun *lun;
11350	struct ctl_softc *ctl_softc;
11351	union ctl_io *next_io, *pending_io;
11352	union ctl_io *io;
11353	int lun_idx;
11354	int i;
11355
11356	ctl_softc = control_softc;
11357
11358	mtx_lock(&ctl_softc->ctl_lock);
11359	/*
11360	 * Remove any cmds from the other SC from the rtr queue.  These
11361	 * will obviously only be for LUNs for which we're the primary.
11362	 * We can't send status or get/send data for these commands.
11363	 * Since they haven't been executed yet, we can just remove them.
11364	 * We'll either abort them or delete them below, depending on
11365	 * which HA mode we're in.
11366	 */
11367#ifdef notyet
11368	mtx_lock(&ctl_softc->queue_lock);
11369	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11370	     io != NULL; io = next_io) {
11371		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11372		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11373			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11374				      ctl_io_hdr, links);
11375	}
11376	mtx_unlock(&ctl_softc->queue_lock);
11377#endif
11378
11379	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11380		lun = ctl_softc->ctl_luns[lun_idx];
11381		if (lun==NULL)
11382			continue;
11383
11384		/*
11385		 * Processor LUNs are primary on both sides.
11386		 * XXX will this always be true?
11387		 */
11388		if (lun->be_lun->lun_type == T_PROCESSOR)
11389			continue;
11390
11391		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11392		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11393			printf("FAILOVER: primary lun %d\n", lun_idx);
11394		        /*
11395			 * Remove all commands from the other SC. First from the
11396			 * blocked queue then from the ooa queue. Once we have
11397			 * removed them. Call ctl_check_blocked to see if there
11398			 * is anything that can run.
11399			 */
11400			for (io = (union ctl_io *)TAILQ_FIRST(
11401			     &lun->blocked_queue); io != NULL; io = next_io) {
11402
11403		        	next_io = (union ctl_io *)TAILQ_NEXT(
11404				    &io->io_hdr, blocked_links);
11405
11406				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11407					TAILQ_REMOVE(&lun->blocked_queue,
11408						     &io->io_hdr,blocked_links);
11409					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11410					TAILQ_REMOVE(&lun->ooa_queue,
11411						     &io->io_hdr, ooa_links);
11412
11413					ctl_free_io(io);
11414				}
11415			}
11416
11417			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11418	     		     io != NULL; io = next_io) {
11419
11420		        	next_io = (union ctl_io *)TAILQ_NEXT(
11421				    &io->io_hdr, ooa_links);
11422
11423				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11424
11425					TAILQ_REMOVE(&lun->ooa_queue,
11426						&io->io_hdr,
11427					     	ooa_links);
11428
11429					ctl_free_io(io);
11430				}
11431			}
11432			ctl_check_blocked(lun);
11433		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11434			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11435
11436			printf("FAILOVER: primary lun %d\n", lun_idx);
11437			/*
11438			 * Abort all commands from the other SC.  We can't
11439			 * send status back for them now.  These should get
11440			 * cleaned up when they are completed or come out
11441			 * for a datamove operation.
11442			 */
11443			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11444	     		     io != NULL; io = next_io) {
11445		        	next_io = (union ctl_io *)TAILQ_NEXT(
11446					&io->io_hdr, ooa_links);
11447
11448				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11449					io->io_hdr.flags |= CTL_FLAG_ABORT;
11450			}
11451		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11452			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11453
11454			printf("FAILOVER: secondary lun %d\n", lun_idx);
11455
11456			lun->flags |= CTL_LUN_PRIMARY_SC;
11457
11458			/*
11459			 * We send all I/O that was sent to this controller
11460			 * and redirected to the other side back with
11461			 * busy status, and have the initiator retry it.
11462			 * Figuring out how much data has been transferred,
11463			 * etc. and picking up where we left off would be
11464			 * very tricky.
11465			 *
11466			 * XXX KDM need to remove I/O from the blocked
11467			 * queue as well!
11468			 */
11469			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11470			     &lun->ooa_queue); pending_io != NULL;
11471			     pending_io = next_io) {
11472
11473				next_io =  (union ctl_io *)TAILQ_NEXT(
11474					&pending_io->io_hdr, ooa_links);
11475
11476				pending_io->io_hdr.flags &=
11477					~CTL_FLAG_SENT_2OTHER_SC;
11478
11479				if (pending_io->io_hdr.flags &
11480				    CTL_FLAG_IO_ACTIVE) {
11481					pending_io->io_hdr.flags |=
11482						CTL_FLAG_FAILOVER;
11483				} else {
11484					ctl_set_busy(&pending_io->scsiio);
11485					ctl_done(pending_io);
11486				}
11487			}
11488
11489			/*
11490			 * Build Unit Attention
11491			 */
11492			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11493				lun->pending_ua[i] |=
11494				                     CTL_UA_ASYM_ACC_CHANGE;
11495			}
11496		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11497			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11498			printf("FAILOVER: secondary lun %d\n", lun_idx);
11499			/*
11500			 * if the first io on the OOA is not on the RtR queue
11501			 * add it.
11502			 */
11503			lun->flags |= CTL_LUN_PRIMARY_SC;
11504
11505			pending_io = (union ctl_io *)TAILQ_FIRST(
11506			    &lun->ooa_queue);
11507			if (pending_io==NULL) {
11508				printf("Nothing on OOA queue\n");
11509				continue;
11510			}
11511
11512			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11513			if ((pending_io->io_hdr.flags &
11514			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11515				pending_io->io_hdr.flags |=
11516				    CTL_FLAG_IS_WAS_ON_RTR;
11517				ctl_enqueue_rtr(pending_io);
11518			}
11519#if 0
11520			else
11521			{
11522				printf("Tag 0x%04x is running\n",
11523				      pending_io->scsiio.tag_num);
11524			}
11525#endif
11526
11527			next_io = (union ctl_io *)TAILQ_NEXT(
11528			    &pending_io->io_hdr, ooa_links);
11529			for (pending_io=next_io; pending_io != NULL;
11530			     pending_io = next_io) {
11531				pending_io->io_hdr.flags &=
11532				    ~CTL_FLAG_SENT_2OTHER_SC;
11533				next_io = (union ctl_io *)TAILQ_NEXT(
11534					&pending_io->io_hdr, ooa_links);
11535				if (pending_io->io_hdr.flags &
11536				    CTL_FLAG_IS_WAS_ON_RTR) {
11537#if 0
11538				        printf("Tag 0x%04x is running\n",
11539				      		pending_io->scsiio.tag_num);
11540#endif
11541					continue;
11542				}
11543
11544				switch (ctl_check_ooa(lun, pending_io,
11545			            (union ctl_io *)TAILQ_PREV(
11546				    &pending_io->io_hdr, ctl_ooaq,
11547				    ooa_links))) {
11548
11549				case CTL_ACTION_BLOCK:
11550					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11551							  &pending_io->io_hdr,
11552							  blocked_links);
11553					pending_io->io_hdr.flags |=
11554					    CTL_FLAG_BLOCKED;
11555					break;
11556				case CTL_ACTION_PASS:
11557				case CTL_ACTION_SKIP:
11558					pending_io->io_hdr.flags |=
11559					    CTL_FLAG_IS_WAS_ON_RTR;
11560					ctl_enqueue_rtr(pending_io);
11561					break;
11562				case CTL_ACTION_OVERLAP:
11563					ctl_set_overlapped_cmd(
11564					    (struct ctl_scsiio *)pending_io);
11565					ctl_done(pending_io);
11566					break;
11567				case CTL_ACTION_OVERLAP_TAG:
11568					ctl_set_overlapped_tag(
11569					    (struct ctl_scsiio *)pending_io,
11570					    pending_io->scsiio.tag_num & 0xff);
11571					ctl_done(pending_io);
11572					break;
11573				case CTL_ACTION_ERROR:
11574				default:
11575					ctl_set_internal_failure(
11576						(struct ctl_scsiio *)pending_io,
11577						0,  // sks_valid
11578						0); //retry count
11579					ctl_done(pending_io);
11580					break;
11581				}
11582			}
11583
11584			/*
11585			 * Build Unit Attention
11586			 */
11587			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11588				lun->pending_ua[i] |=
11589				                     CTL_UA_ASYM_ACC_CHANGE;
11590			}
11591		} else {
11592			panic("Unhandled HA mode failover, LUN flags = %#x, "
11593			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11594		}
11595	}
11596	ctl_pause_rtr = 0;
11597	mtx_unlock(&ctl_softc->ctl_lock);
11598}
11599
11600static int
11601ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11602{
11603	struct ctl_lun *lun;
11604	const struct ctl_cmd_entry *entry;
11605	uint32_t initidx, targ_lun;
11606	int retval;
11607
11608	retval = 0;
11609
11610	lun = NULL;
11611
11612	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11613	if ((targ_lun < CTL_MAX_LUNS)
11614	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11615		lun = ctl_softc->ctl_luns[targ_lun];
11616		/*
11617		 * If the LUN is invalid, pretend that it doesn't exist.
11618		 * It will go away as soon as all pending I/O has been
11619		 * completed.
11620		 */
11621		if (lun->flags & CTL_LUN_DISABLED) {
11622			lun = NULL;
11623		} else {
11624			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11625			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11626				lun->be_lun;
11627			if (lun->be_lun->lun_type == T_PROCESSOR) {
11628				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11629			}
11630
11631			/*
11632			 * Every I/O goes into the OOA queue for a
11633			 * particular LUN, and stays there until completion.
11634			 */
11635			mtx_lock(&lun->lun_lock);
11636			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11637			    ooa_links);
11638		}
11639	} else {
11640		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11641		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11642	}
11643
11644	/* Get command entry and return error if it is unsuppotyed. */
11645	entry = ctl_validate_command(ctsio);
11646	if (entry == NULL) {
11647		if (lun)
11648			mtx_unlock(&lun->lun_lock);
11649		return (retval);
11650	}
11651
11652	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11653	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11654
11655	/*
11656	 * Check to see whether we can send this command to LUNs that don't
11657	 * exist.  This should pretty much only be the case for inquiry
11658	 * and request sense.  Further checks, below, really require having
11659	 * a LUN, so we can't really check the command anymore.  Just put
11660	 * it on the rtr queue.
11661	 */
11662	if (lun == NULL) {
11663		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11664			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11665			ctl_enqueue_rtr((union ctl_io *)ctsio);
11666			return (retval);
11667		}
11668
11669		ctl_set_unsupported_lun(ctsio);
11670		ctl_done((union ctl_io *)ctsio);
11671		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11672		return (retval);
11673	} else {
11674		/*
11675		 * Make sure we support this particular command on this LUN.
11676		 * e.g., we don't support writes to the control LUN.
11677		 */
11678		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11679			mtx_unlock(&lun->lun_lock);
11680			ctl_set_invalid_opcode(ctsio);
11681			ctl_done((union ctl_io *)ctsio);
11682			return (retval);
11683		}
11684	}
11685
11686	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11687
11688#ifdef CTL_WITH_CA
11689	/*
11690	 * If we've got a request sense, it'll clear the contingent
11691	 * allegiance condition.  Otherwise, if we have a CA condition for
11692	 * this initiator, clear it, because it sent down a command other
11693	 * than request sense.
11694	 */
11695	if ((ctsio->cdb[0] != REQUEST_SENSE)
11696	 && (ctl_is_set(lun->have_ca, initidx)))
11697		ctl_clear_mask(lun->have_ca, initidx);
11698#endif
11699
11700	/*
11701	 * If the command has this flag set, it handles its own unit
11702	 * attention reporting, we shouldn't do anything.  Otherwise we
11703	 * check for any pending unit attentions, and send them back to the
11704	 * initiator.  We only do this when a command initially comes in,
11705	 * not when we pull it off the blocked queue.
11706	 *
11707	 * According to SAM-3, section 5.3.2, the order that things get
11708	 * presented back to the host is basically unit attentions caused
11709	 * by some sort of reset event, busy status, reservation conflicts
11710	 * or task set full, and finally any other status.
11711	 *
11712	 * One issue here is that some of the unit attentions we report
11713	 * don't fall into the "reset" category (e.g. "reported luns data
11714	 * has changed").  So reporting it here, before the reservation
11715	 * check, may be technically wrong.  I guess the only thing to do
11716	 * would be to check for and report the reset events here, and then
11717	 * check for the other unit attention types after we check for a
11718	 * reservation conflict.
11719	 *
11720	 * XXX KDM need to fix this
11721	 */
11722	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11723		ctl_ua_type ua_type;
11724
11725		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11726			scsi_sense_data_type sense_format;
11727
11728			if (lun != NULL)
11729				sense_format = (lun->flags &
11730				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11731				    SSD_TYPE_FIXED;
11732			else
11733				sense_format = SSD_TYPE_FIXED;
11734
11735			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11736			    &ctsio->sense_data, sense_format);
11737			if (ua_type != CTL_UA_NONE) {
11738				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11739				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11740						       CTL_AUTOSENSE;
11741				ctsio->sense_len = SSD_FULL_SIZE;
11742				mtx_unlock(&lun->lun_lock);
11743				ctl_done((union ctl_io *)ctsio);
11744				return (retval);
11745			}
11746		}
11747	}
11748
11749
11750	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11751		mtx_unlock(&lun->lun_lock);
11752		ctl_done((union ctl_io *)ctsio);
11753		return (retval);
11754	}
11755
11756	/*
11757	 * XXX CHD this is where we want to send IO to other side if
11758	 * this LUN is secondary on this SC. We will need to make a copy
11759	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11760	 * the copy we send as FROM_OTHER.
11761	 * We also need to stuff the address of the original IO so we can
11762	 * find it easily. Something similar will need be done on the other
11763	 * side so when we are done we can find the copy.
11764	 */
11765	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11766		union ctl_ha_msg msg_info;
11767		int isc_retval;
11768
11769		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11770
11771		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11772		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11773#if 0
11774		printf("1. ctsio %p\n", ctsio);
11775#endif
11776		msg_info.hdr.serializing_sc = NULL;
11777		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11778		msg_info.scsi.tag_num = ctsio->tag_num;
11779		msg_info.scsi.tag_type = ctsio->tag_type;
11780		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11781
11782		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11783
11784		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11785		    (void *)&msg_info, sizeof(msg_info), 0)) >
11786		    CTL_HA_STATUS_SUCCESS) {
11787			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11788			       isc_retval);
11789			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11790		} else {
11791#if 0
11792			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11793#endif
11794		}
11795
11796		/*
11797		 * XXX KDM this I/O is off the incoming queue, but hasn't
11798		 * been inserted on any other queue.  We may need to come
11799		 * up with a holding queue while we wait for serialization
11800		 * so that we have an idea of what we're waiting for from
11801		 * the other side.
11802		 */
11803		mtx_unlock(&lun->lun_lock);
11804		return (retval);
11805	}
11806
11807	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11808			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11809			      ctl_ooaq, ooa_links))) {
11810	case CTL_ACTION_BLOCK:
11811		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11812		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11813				  blocked_links);
11814		mtx_unlock(&lun->lun_lock);
11815		return (retval);
11816	case CTL_ACTION_PASS:
11817	case CTL_ACTION_SKIP:
11818		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11819		mtx_unlock(&lun->lun_lock);
11820		ctl_enqueue_rtr((union ctl_io *)ctsio);
11821		break;
11822	case CTL_ACTION_OVERLAP:
11823		mtx_unlock(&lun->lun_lock);
11824		ctl_set_overlapped_cmd(ctsio);
11825		ctl_done((union ctl_io *)ctsio);
11826		break;
11827	case CTL_ACTION_OVERLAP_TAG:
11828		mtx_unlock(&lun->lun_lock);
11829		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11830		ctl_done((union ctl_io *)ctsio);
11831		break;
11832	case CTL_ACTION_ERROR:
11833	default:
11834		mtx_unlock(&lun->lun_lock);
11835		ctl_set_internal_failure(ctsio,
11836					 /*sks_valid*/ 0,
11837					 /*retry_count*/ 0);
11838		ctl_done((union ctl_io *)ctsio);
11839		break;
11840	}
11841	return (retval);
11842}
11843
11844const struct ctl_cmd_entry *
11845ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11846{
11847	const struct ctl_cmd_entry *entry;
11848	int service_action;
11849
11850	entry = &ctl_cmd_table[ctsio->cdb[0]];
11851	if (sa)
11852		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11853	if (entry->flags & CTL_CMD_FLAG_SA5) {
11854		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11855		entry = &((const struct ctl_cmd_entry *)
11856		    entry->execute)[service_action];
11857	}
11858	return (entry);
11859}
11860
11861const struct ctl_cmd_entry *
11862ctl_validate_command(struct ctl_scsiio *ctsio)
11863{
11864	const struct ctl_cmd_entry *entry;
11865	int i, sa;
11866	uint8_t diff;
11867
11868	entry = ctl_get_cmd_entry(ctsio, &sa);
11869	if (entry->execute == NULL) {
11870		if (sa)
11871			ctl_set_invalid_field(ctsio,
11872					      /*sks_valid*/ 1,
11873					      /*command*/ 1,
11874					      /*field*/ 1,
11875					      /*bit_valid*/ 1,
11876					      /*bit*/ 4);
11877		else
11878			ctl_set_invalid_opcode(ctsio);
11879		ctl_done((union ctl_io *)ctsio);
11880		return (NULL);
11881	}
11882	KASSERT(entry->length > 0,
11883	    ("Not defined length for command 0x%02x/0x%02x",
11884	     ctsio->cdb[0], ctsio->cdb[1]));
11885	for (i = 1; i < entry->length; i++) {
11886		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11887		if (diff == 0)
11888			continue;
11889		ctl_set_invalid_field(ctsio,
11890				      /*sks_valid*/ 1,
11891				      /*command*/ 1,
11892				      /*field*/ i,
11893				      /*bit_valid*/ 1,
11894				      /*bit*/ fls(diff) - 1);
11895		ctl_done((union ctl_io *)ctsio);
11896		return (NULL);
11897	}
11898	return (entry);
11899}
11900
11901static int
11902ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11903{
11904
11905	switch (lun_type) {
11906	case T_PROCESSOR:
11907		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11908		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11909			return (0);
11910		break;
11911	case T_DIRECT:
11912		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11913		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11914			return (0);
11915		break;
11916	default:
11917		return (0);
11918	}
11919	return (1);
11920}
11921
11922static int
11923ctl_scsiio(struct ctl_scsiio *ctsio)
11924{
11925	int retval;
11926	const struct ctl_cmd_entry *entry;
11927
11928	retval = CTL_RETVAL_COMPLETE;
11929
11930	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11931
11932	entry = ctl_get_cmd_entry(ctsio, NULL);
11933
11934	/*
11935	 * If this I/O has been aborted, just send it straight to
11936	 * ctl_done() without executing it.
11937	 */
11938	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11939		ctl_done((union ctl_io *)ctsio);
11940		goto bailout;
11941	}
11942
11943	/*
11944	 * All the checks should have been handled by ctl_scsiio_precheck().
11945	 * We should be clear now to just execute the I/O.
11946	 */
11947	retval = entry->execute(ctsio);
11948
11949bailout:
11950	return (retval);
11951}
11952
11953/*
11954 * Since we only implement one target right now, a bus reset simply resets
11955 * our single target.
11956 */
11957static int
11958ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11959{
11960	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11961}
11962
11963static int
11964ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11965		 ctl_ua_type ua_type)
11966{
11967	struct ctl_lun *lun;
11968	int retval;
11969
11970	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11971		union ctl_ha_msg msg_info;
11972
11973		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11974		msg_info.hdr.nexus = io->io_hdr.nexus;
11975		if (ua_type==CTL_UA_TARG_RESET)
11976			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11977		else
11978			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11979		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11980		msg_info.hdr.original_sc = NULL;
11981		msg_info.hdr.serializing_sc = NULL;
11982		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11983		    (void *)&msg_info, sizeof(msg_info), 0)) {
11984		}
11985	}
11986	retval = 0;
11987
11988	mtx_lock(&ctl_softc->ctl_lock);
11989	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11990		retval += ctl_lun_reset(lun, io, ua_type);
11991	mtx_unlock(&ctl_softc->ctl_lock);
11992
11993	return (retval);
11994}
11995
11996/*
11997 * The LUN should always be set.  The I/O is optional, and is used to
11998 * distinguish between I/Os sent by this initiator, and by other
11999 * initiators.  We set unit attention for initiators other than this one.
12000 * SAM-3 is vague on this point.  It does say that a unit attention should
12001 * be established for other initiators when a LUN is reset (see section
12002 * 5.7.3), but it doesn't specifically say that the unit attention should
12003 * be established for this particular initiator when a LUN is reset.  Here
12004 * is the relevant text, from SAM-3 rev 8:
12005 *
12006 * 5.7.2 When a SCSI initiator port aborts its own tasks
12007 *
12008 * When a SCSI initiator port causes its own task(s) to be aborted, no
12009 * notification that the task(s) have been aborted shall be returned to
12010 * the SCSI initiator port other than the completion response for the
12011 * command or task management function action that caused the task(s) to
12012 * be aborted and notification(s) associated with related effects of the
12013 * action (e.g., a reset unit attention condition).
12014 *
12015 * XXX KDM for now, we're setting unit attention for all initiators.
12016 */
12017static int
12018ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12019{
12020	union ctl_io *xio;
12021#if 0
12022	uint32_t initindex;
12023#endif
12024	int i;
12025
12026	mtx_lock(&lun->lun_lock);
12027	/*
12028	 * Run through the OOA queue and abort each I/O.
12029	 */
12030#if 0
12031	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12032#endif
12033	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12034	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12035		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12036	}
12037
12038	/*
12039	 * This version sets unit attention for every
12040	 */
12041#if 0
12042	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12043	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12044		if (initindex == i)
12045			continue;
12046		lun->pending_ua[i] |= ua_type;
12047	}
12048#endif
12049
12050	/*
12051	 * A reset (any kind, really) clears reservations established with
12052	 * RESERVE/RELEASE.  It does not clear reservations established
12053	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12054	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12055	 * reservations made with the RESERVE/RELEASE commands, because
12056	 * those commands are obsolete in SPC-3.
12057	 */
12058	lun->flags &= ~CTL_LUN_RESERVED;
12059
12060	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12061#ifdef CTL_WITH_CA
12062		ctl_clear_mask(lun->have_ca, i);
12063#endif
12064		lun->pending_ua[i] |= ua_type;
12065	}
12066	mtx_unlock(&lun->lun_lock);
12067
12068	return (0);
12069}
12070
12071static void
12072ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12073    int other_sc)
12074{
12075	union ctl_io *xio;
12076
12077	mtx_assert(&lun->lun_lock, MA_OWNED);
12078
12079	/*
12080	 * Run through the OOA queue and attempt to find the given I/O.
12081	 * The target port, initiator ID, tag type and tag number have to
12082	 * match the values that we got from the initiator.  If we have an
12083	 * untagged command to abort, simply abort the first untagged command
12084	 * we come to.  We only allow one untagged command at a time of course.
12085	 */
12086	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12087	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12088
12089		if ((targ_port == UINT32_MAX ||
12090		     targ_port == xio->io_hdr.nexus.targ_port) &&
12091		    (init_id == UINT32_MAX ||
12092		     init_id == xio->io_hdr.nexus.initid.id)) {
12093			if (targ_port != xio->io_hdr.nexus.targ_port ||
12094			    init_id != xio->io_hdr.nexus.initid.id)
12095				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12096			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12097			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12098				union ctl_ha_msg msg_info;
12099
12100				msg_info.hdr.nexus = xio->io_hdr.nexus;
12101				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12102				msg_info.task.tag_num = xio->scsiio.tag_num;
12103				msg_info.task.tag_type = xio->scsiio.tag_type;
12104				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12105				msg_info.hdr.original_sc = NULL;
12106				msg_info.hdr.serializing_sc = NULL;
12107				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12108				    (void *)&msg_info, sizeof(msg_info), 0);
12109			}
12110		}
12111	}
12112}
12113
12114static int
12115ctl_abort_task_set(union ctl_io *io)
12116{
12117	struct ctl_softc *softc = control_softc;
12118	struct ctl_lun *lun;
12119	uint32_t targ_lun;
12120
12121	/*
12122	 * Look up the LUN.
12123	 */
12124	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12125	mtx_lock(&softc->ctl_lock);
12126	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12127		lun = softc->ctl_luns[targ_lun];
12128	else {
12129		mtx_unlock(&softc->ctl_lock);
12130		return (1);
12131	}
12132
12133	mtx_lock(&lun->lun_lock);
12134	mtx_unlock(&softc->ctl_lock);
12135	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12136		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12137		    io->io_hdr.nexus.initid.id,
12138		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12139	} else { /* CTL_TASK_CLEAR_TASK_SET */
12140		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12141		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12142	}
12143	mtx_unlock(&lun->lun_lock);
12144	return (0);
12145}
12146
12147static int
12148ctl_i_t_nexus_reset(union ctl_io *io)
12149{
12150	struct ctl_softc *softc = control_softc;
12151	struct ctl_lun *lun;
12152	uint32_t initindex, residx;
12153
12154	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12155	residx = ctl_get_resindex(&io->io_hdr.nexus);
12156	mtx_lock(&softc->ctl_lock);
12157	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12158		mtx_lock(&lun->lun_lock);
12159		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12160		    io->io_hdr.nexus.initid.id,
12161		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12162#ifdef CTL_WITH_CA
12163		ctl_clear_mask(lun->have_ca, initindex);
12164#endif
12165		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12166			lun->flags &= ~CTL_LUN_RESERVED;
12167		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12168		mtx_unlock(&lun->lun_lock);
12169	}
12170	mtx_unlock(&softc->ctl_lock);
12171	return (0);
12172}
12173
12174static int
12175ctl_abort_task(union ctl_io *io)
12176{
12177	union ctl_io *xio;
12178	struct ctl_lun *lun;
12179	struct ctl_softc *ctl_softc;
12180#if 0
12181	struct sbuf sb;
12182	char printbuf[128];
12183#endif
12184	int found;
12185	uint32_t targ_lun;
12186
12187	ctl_softc = control_softc;
12188	found = 0;
12189
12190	/*
12191	 * Look up the LUN.
12192	 */
12193	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12194	mtx_lock(&ctl_softc->ctl_lock);
12195	if ((targ_lun < CTL_MAX_LUNS)
12196	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12197		lun = ctl_softc->ctl_luns[targ_lun];
12198	else {
12199		mtx_unlock(&ctl_softc->ctl_lock);
12200		return (1);
12201	}
12202
12203#if 0
12204	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12205	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12206#endif
12207
12208	mtx_lock(&lun->lun_lock);
12209	mtx_unlock(&ctl_softc->ctl_lock);
12210	/*
12211	 * Run through the OOA queue and attempt to find the given I/O.
12212	 * The target port, initiator ID, tag type and tag number have to
12213	 * match the values that we got from the initiator.  If we have an
12214	 * untagged command to abort, simply abort the first untagged command
12215	 * we come to.  We only allow one untagged command at a time of course.
12216	 */
12217#if 0
12218	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12219#endif
12220	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12221	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12222#if 0
12223		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12224
12225		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12226			    lun->lun, xio->scsiio.tag_num,
12227			    xio->scsiio.tag_type,
12228			    (xio->io_hdr.blocked_links.tqe_prev
12229			    == NULL) ? "" : " BLOCKED",
12230			    (xio->io_hdr.flags &
12231			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12232			    (xio->io_hdr.flags &
12233			    CTL_FLAG_ABORT) ? " ABORT" : "",
12234			    (xio->io_hdr.flags &
12235			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12236		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12237		sbuf_finish(&sb);
12238		printf("%s\n", sbuf_data(&sb));
12239#endif
12240
12241		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12242		 && (xio->io_hdr.nexus.initid.id ==
12243		     io->io_hdr.nexus.initid.id)) {
12244			/*
12245			 * If the abort says that the task is untagged, the
12246			 * task in the queue must be untagged.  Otherwise,
12247			 * we just check to see whether the tag numbers
12248			 * match.  This is because the QLogic firmware
12249			 * doesn't pass back the tag type in an abort
12250			 * request.
12251			 */
12252#if 0
12253			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12254			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12255			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12256#endif
12257			/*
12258			 * XXX KDM we've got problems with FC, because it
12259			 * doesn't send down a tag type with aborts.  So we
12260			 * can only really go by the tag number...
12261			 * This may cause problems with parallel SCSI.
12262			 * Need to figure that out!!
12263			 */
12264			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12265				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12266				found = 1;
12267				if ((io->io_hdr.flags &
12268				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12269				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12270					union ctl_ha_msg msg_info;
12271
12272					io->io_hdr.flags |=
12273					                CTL_FLAG_SENT_2OTHER_SC;
12274					msg_info.hdr.nexus = io->io_hdr.nexus;
12275					msg_info.task.task_action =
12276						CTL_TASK_ABORT_TASK;
12277					msg_info.task.tag_num =
12278						io->taskio.tag_num;
12279					msg_info.task.tag_type =
12280						io->taskio.tag_type;
12281					msg_info.hdr.msg_type =
12282						CTL_MSG_MANAGE_TASKS;
12283					msg_info.hdr.original_sc = NULL;
12284					msg_info.hdr.serializing_sc = NULL;
12285#if 0
12286					printf("Sent Abort to other side\n");
12287#endif
12288					if (CTL_HA_STATUS_SUCCESS !=
12289					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12290		    				(void *)&msg_info,
12291						sizeof(msg_info), 0)) {
12292					}
12293				}
12294#if 0
12295				printf("ctl_abort_task: found I/O to abort\n");
12296#endif
12297				break;
12298			}
12299		}
12300	}
12301	mtx_unlock(&lun->lun_lock);
12302
12303	if (found == 0) {
12304		/*
12305		 * This isn't really an error.  It's entirely possible for
12306		 * the abort and command completion to cross on the wire.
12307		 * This is more of an informative/diagnostic error.
12308		 */
12309#if 0
12310		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12311		       "%d:%d:%d:%d tag %d type %d\n",
12312		       io->io_hdr.nexus.initid.id,
12313		       io->io_hdr.nexus.targ_port,
12314		       io->io_hdr.nexus.targ_target.id,
12315		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12316		       io->taskio.tag_type);
12317#endif
12318	}
12319	return (0);
12320}
12321
12322static void
12323ctl_run_task(union ctl_io *io)
12324{
12325	struct ctl_softc *ctl_softc = control_softc;
12326	int retval = 1;
12327	const char *task_desc;
12328
12329	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12330
12331	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12332	    ("ctl_run_task: Unextected io_type %d\n",
12333	     io->io_hdr.io_type));
12334
12335	task_desc = ctl_scsi_task_string(&io->taskio);
12336	if (task_desc != NULL) {
12337#ifdef NEEDTOPORT
12338		csevent_log(CSC_CTL | CSC_SHELF_SW |
12339			    CTL_TASK_REPORT,
12340			    csevent_LogType_Trace,
12341			    csevent_Severity_Information,
12342			    csevent_AlertLevel_Green,
12343			    csevent_FRU_Firmware,
12344			    csevent_FRU_Unknown,
12345			    "CTL: received task: %s",task_desc);
12346#endif
12347	} else {
12348#ifdef NEEDTOPORT
12349		csevent_log(CSC_CTL | CSC_SHELF_SW |
12350			    CTL_TASK_REPORT,
12351			    csevent_LogType_Trace,
12352			    csevent_Severity_Information,
12353			    csevent_AlertLevel_Green,
12354			    csevent_FRU_Firmware,
12355			    csevent_FRU_Unknown,
12356			    "CTL: received unknown task "
12357			    "type: %d (%#x)",
12358			    io->taskio.task_action,
12359			    io->taskio.task_action);
12360#endif
12361	}
12362	switch (io->taskio.task_action) {
12363	case CTL_TASK_ABORT_TASK:
12364		retval = ctl_abort_task(io);
12365		break;
12366	case CTL_TASK_ABORT_TASK_SET:
12367	case CTL_TASK_CLEAR_TASK_SET:
12368		retval = ctl_abort_task_set(io);
12369		break;
12370	case CTL_TASK_CLEAR_ACA:
12371		break;
12372	case CTL_TASK_I_T_NEXUS_RESET:
12373		retval = ctl_i_t_nexus_reset(io);
12374		break;
12375	case CTL_TASK_LUN_RESET: {
12376		struct ctl_lun *lun;
12377		uint32_t targ_lun;
12378
12379		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12380		mtx_lock(&ctl_softc->ctl_lock);
12381		if ((targ_lun < CTL_MAX_LUNS)
12382		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12383			lun = ctl_softc->ctl_luns[targ_lun];
12384		else {
12385			mtx_unlock(&ctl_softc->ctl_lock);
12386			retval = 1;
12387			break;
12388		}
12389
12390		if (!(io->io_hdr.flags &
12391		    CTL_FLAG_FROM_OTHER_SC)) {
12392			union ctl_ha_msg msg_info;
12393
12394			io->io_hdr.flags |=
12395				CTL_FLAG_SENT_2OTHER_SC;
12396			msg_info.hdr.msg_type =
12397				CTL_MSG_MANAGE_TASKS;
12398			msg_info.hdr.nexus = io->io_hdr.nexus;
12399			msg_info.task.task_action =
12400				CTL_TASK_LUN_RESET;
12401			msg_info.hdr.original_sc = NULL;
12402			msg_info.hdr.serializing_sc = NULL;
12403			if (CTL_HA_STATUS_SUCCESS !=
12404			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12405			    (void *)&msg_info,
12406			    sizeof(msg_info), 0)) {
12407			}
12408		}
12409
12410		retval = ctl_lun_reset(lun, io,
12411				       CTL_UA_LUN_RESET);
12412		mtx_unlock(&ctl_softc->ctl_lock);
12413		break;
12414	}
12415	case CTL_TASK_TARGET_RESET:
12416		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12417		break;
12418	case CTL_TASK_BUS_RESET:
12419		retval = ctl_bus_reset(ctl_softc, io);
12420		break;
12421	case CTL_TASK_PORT_LOGIN:
12422		break;
12423	case CTL_TASK_PORT_LOGOUT:
12424		break;
12425	default:
12426		printf("ctl_run_task: got unknown task management event %d\n",
12427		       io->taskio.task_action);
12428		break;
12429	}
12430	if (retval == 0)
12431		io->io_hdr.status = CTL_SUCCESS;
12432	else
12433		io->io_hdr.status = CTL_ERROR;
12434	ctl_done(io);
12435}
12436
12437/*
12438 * For HA operation.  Handle commands that come in from the other
12439 * controller.
12440 */
12441static void
12442ctl_handle_isc(union ctl_io *io)
12443{
12444	int free_io;
12445	struct ctl_lun *lun;
12446	struct ctl_softc *ctl_softc;
12447	uint32_t targ_lun;
12448
12449	ctl_softc = control_softc;
12450
12451	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12452	lun = ctl_softc->ctl_luns[targ_lun];
12453
12454	switch (io->io_hdr.msg_type) {
12455	case CTL_MSG_SERIALIZE:
12456		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12457		break;
12458	case CTL_MSG_R2R: {
12459		const struct ctl_cmd_entry *entry;
12460
12461		/*
12462		 * This is only used in SER_ONLY mode.
12463		 */
12464		free_io = 0;
12465		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12466		mtx_lock(&lun->lun_lock);
12467		if (ctl_scsiio_lun_check(ctl_softc, lun,
12468		    entry, (struct ctl_scsiio *)io) != 0) {
12469			mtx_unlock(&lun->lun_lock);
12470			ctl_done(io);
12471			break;
12472		}
12473		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12474		mtx_unlock(&lun->lun_lock);
12475		ctl_enqueue_rtr(io);
12476		break;
12477	}
12478	case CTL_MSG_FINISH_IO:
12479		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12480			free_io = 0;
12481			ctl_done(io);
12482		} else {
12483			free_io = 1;
12484			mtx_lock(&lun->lun_lock);
12485			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12486				     ooa_links);
12487			ctl_check_blocked(lun);
12488			mtx_unlock(&lun->lun_lock);
12489		}
12490		break;
12491	case CTL_MSG_PERS_ACTION:
12492		ctl_hndl_per_res_out_on_other_sc(
12493			(union ctl_ha_msg *)&io->presio.pr_msg);
12494		free_io = 1;
12495		break;
12496	case CTL_MSG_BAD_JUJU:
12497		free_io = 0;
12498		ctl_done(io);
12499		break;
12500	case CTL_MSG_DATAMOVE:
12501		/* Only used in XFER mode */
12502		free_io = 0;
12503		ctl_datamove_remote(io);
12504		break;
12505	case CTL_MSG_DATAMOVE_DONE:
12506		/* Only used in XFER mode */
12507		free_io = 0;
12508		io->scsiio.be_move_done(io);
12509		break;
12510	default:
12511		free_io = 1;
12512		printf("%s: Invalid message type %d\n",
12513		       __func__, io->io_hdr.msg_type);
12514		break;
12515	}
12516	if (free_io)
12517		ctl_free_io(io);
12518
12519}
12520
12521
12522/*
12523 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12524 * there is no match.
12525 */
12526static ctl_lun_error_pattern
12527ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12528{
12529	const struct ctl_cmd_entry *entry;
12530	ctl_lun_error_pattern filtered_pattern, pattern;
12531
12532	pattern = desc->error_pattern;
12533
12534	/*
12535	 * XXX KDM we need more data passed into this function to match a
12536	 * custom pattern, and we actually need to implement custom pattern
12537	 * matching.
12538	 */
12539	if (pattern & CTL_LUN_PAT_CMD)
12540		return (CTL_LUN_PAT_CMD);
12541
12542	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12543		return (CTL_LUN_PAT_ANY);
12544
12545	entry = ctl_get_cmd_entry(ctsio, NULL);
12546
12547	filtered_pattern = entry->pattern & pattern;
12548
12549	/*
12550	 * If the user requested specific flags in the pattern (e.g.
12551	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12552	 * flags.
12553	 *
12554	 * If the user did not specify any flags, it doesn't matter whether
12555	 * or not the command supports the flags.
12556	 */
12557	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12558	     (pattern & ~CTL_LUN_PAT_MASK))
12559		return (CTL_LUN_PAT_NONE);
12560
12561	/*
12562	 * If the user asked for a range check, see if the requested LBA
12563	 * range overlaps with this command's LBA range.
12564	 */
12565	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12566		uint64_t lba1;
12567		uint64_t len1;
12568		ctl_action action;
12569		int retval;
12570
12571		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12572		if (retval != 0)
12573			return (CTL_LUN_PAT_NONE);
12574
12575		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12576					      desc->lba_range.len);
12577		/*
12578		 * A "pass" means that the LBA ranges don't overlap, so
12579		 * this doesn't match the user's range criteria.
12580		 */
12581		if (action == CTL_ACTION_PASS)
12582			return (CTL_LUN_PAT_NONE);
12583	}
12584
12585	return (filtered_pattern);
12586}
12587
12588static void
12589ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12590{
12591	struct ctl_error_desc *desc, *desc2;
12592
12593	mtx_assert(&lun->lun_lock, MA_OWNED);
12594
12595	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12596		ctl_lun_error_pattern pattern;
12597		/*
12598		 * Check to see whether this particular command matches
12599		 * the pattern in the descriptor.
12600		 */
12601		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12602		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12603			continue;
12604
12605		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12606		case CTL_LUN_INJ_ABORTED:
12607			ctl_set_aborted(&io->scsiio);
12608			break;
12609		case CTL_LUN_INJ_MEDIUM_ERR:
12610			ctl_set_medium_error(&io->scsiio);
12611			break;
12612		case CTL_LUN_INJ_UA:
12613			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12614			 * OCCURRED */
12615			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12616			break;
12617		case CTL_LUN_INJ_CUSTOM:
12618			/*
12619			 * We're assuming the user knows what he is doing.
12620			 * Just copy the sense information without doing
12621			 * checks.
12622			 */
12623			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12624			      ctl_min(sizeof(desc->custom_sense),
12625				      sizeof(io->scsiio.sense_data)));
12626			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12627			io->scsiio.sense_len = SSD_FULL_SIZE;
12628			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12629			break;
12630		case CTL_LUN_INJ_NONE:
12631		default:
12632			/*
12633			 * If this is an error injection type we don't know
12634			 * about, clear the continuous flag (if it is set)
12635			 * so it will get deleted below.
12636			 */
12637			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12638			break;
12639		}
12640		/*
12641		 * By default, each error injection action is a one-shot
12642		 */
12643		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12644			continue;
12645
12646		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12647
12648		free(desc, M_CTL);
12649	}
12650}
12651
12652#ifdef CTL_IO_DELAY
12653static void
12654ctl_datamove_timer_wakeup(void *arg)
12655{
12656	union ctl_io *io;
12657
12658	io = (union ctl_io *)arg;
12659
12660	ctl_datamove(io);
12661}
12662#endif /* CTL_IO_DELAY */
12663
12664void
12665ctl_datamove(union ctl_io *io)
12666{
12667	void (*fe_datamove)(union ctl_io *io);
12668
12669	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12670
12671	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12672
12673#ifdef CTL_TIME_IO
12674	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12675		char str[256];
12676		char path_str[64];
12677		struct sbuf sb;
12678
12679		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12680		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12681
12682		sbuf_cat(&sb, path_str);
12683		switch (io->io_hdr.io_type) {
12684		case CTL_IO_SCSI:
12685			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12686			sbuf_printf(&sb, "\n");
12687			sbuf_cat(&sb, path_str);
12688			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12689				    io->scsiio.tag_num, io->scsiio.tag_type);
12690			break;
12691		case CTL_IO_TASK:
12692			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12693				    "Tag Type: %d\n", io->taskio.task_action,
12694				    io->taskio.tag_num, io->taskio.tag_type);
12695			break;
12696		default:
12697			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12698			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12699			break;
12700		}
12701		sbuf_cat(&sb, path_str);
12702		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12703			    (intmax_t)time_uptime - io->io_hdr.start_time);
12704		sbuf_finish(&sb);
12705		printf("%s", sbuf_data(&sb));
12706	}
12707#endif /* CTL_TIME_IO */
12708
12709#ifdef CTL_IO_DELAY
12710	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12711		struct ctl_lun *lun;
12712
12713		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12714
12715		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12716	} else {
12717		struct ctl_lun *lun;
12718
12719		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12720		if ((lun != NULL)
12721		 && (lun->delay_info.datamove_delay > 0)) {
12722			struct callout *callout;
12723
12724			callout = (struct callout *)&io->io_hdr.timer_bytes;
12725			callout_init(callout, /*mpsafe*/ 1);
12726			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12727			callout_reset(callout,
12728				      lun->delay_info.datamove_delay * hz,
12729				      ctl_datamove_timer_wakeup, io);
12730			if (lun->delay_info.datamove_type ==
12731			    CTL_DELAY_TYPE_ONESHOT)
12732				lun->delay_info.datamove_delay = 0;
12733			return;
12734		}
12735	}
12736#endif
12737
12738	/*
12739	 * This command has been aborted.  Set the port status, so we fail
12740	 * the data move.
12741	 */
12742	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12743		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12744		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12745		       io->io_hdr.nexus.targ_port,
12746		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12747		       io->io_hdr.nexus.targ_lun);
12748		io->io_hdr.port_status = 31337;
12749		/*
12750		 * Note that the backend, in this case, will get the
12751		 * callback in its context.  In other cases it may get
12752		 * called in the frontend's interrupt thread context.
12753		 */
12754		io->scsiio.be_move_done(io);
12755		return;
12756	}
12757
12758	/*
12759	 * If we're in XFER mode and this I/O is from the other shelf
12760	 * controller, we need to send the DMA to the other side to
12761	 * actually transfer the data to/from the host.  In serialize only
12762	 * mode the transfer happens below CTL and ctl_datamove() is only
12763	 * called on the machine that originally received the I/O.
12764	 */
12765	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12766	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12767		union ctl_ha_msg msg;
12768		uint32_t sg_entries_sent;
12769		int do_sg_copy;
12770		int i;
12771
12772		memset(&msg, 0, sizeof(msg));
12773		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12774		msg.hdr.original_sc = io->io_hdr.original_sc;
12775		msg.hdr.serializing_sc = io;
12776		msg.hdr.nexus = io->io_hdr.nexus;
12777		msg.dt.flags = io->io_hdr.flags;
12778		/*
12779		 * We convert everything into a S/G list here.  We can't
12780		 * pass by reference, only by value between controllers.
12781		 * So we can't pass a pointer to the S/G list, only as many
12782		 * S/G entries as we can fit in here.  If it's possible for
12783		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12784		 * then we need to break this up into multiple transfers.
12785		 */
12786		if (io->scsiio.kern_sg_entries == 0) {
12787			msg.dt.kern_sg_entries = 1;
12788			/*
12789			 * If this is in cached memory, flush the cache
12790			 * before we send the DMA request to the other
12791			 * controller.  We want to do this in either the
12792			 * read or the write case.  The read case is
12793			 * straightforward.  In the write case, we want to
12794			 * make sure nothing is in the local cache that
12795			 * could overwrite the DMAed data.
12796			 */
12797			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12798				/*
12799				 * XXX KDM use bus_dmamap_sync() here.
12800				 */
12801			}
12802
12803			/*
12804			 * Convert to a physical address if this is a
12805			 * virtual address.
12806			 */
12807			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12808				msg.dt.sg_list[0].addr =
12809					io->scsiio.kern_data_ptr;
12810			} else {
12811				/*
12812				 * XXX KDM use busdma here!
12813				 */
12814#if 0
12815				msg.dt.sg_list[0].addr = (void *)
12816					vtophys(io->scsiio.kern_data_ptr);
12817#endif
12818			}
12819
12820			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12821			do_sg_copy = 0;
12822		} else {
12823			struct ctl_sg_entry *sgl;
12824
12825			do_sg_copy = 1;
12826			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12827			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12828			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12829				/*
12830				 * XXX KDM use bus_dmamap_sync() here.
12831				 */
12832			}
12833		}
12834
12835		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12836		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12837		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12838		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12839		msg.dt.sg_sequence = 0;
12840
12841		/*
12842		 * Loop until we've sent all of the S/G entries.  On the
12843		 * other end, we'll recompose these S/G entries into one
12844		 * contiguous list before passing it to the
12845		 */
12846		for (sg_entries_sent = 0; sg_entries_sent <
12847		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12848			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12849				sizeof(msg.dt.sg_list[0])),
12850				msg.dt.kern_sg_entries - sg_entries_sent);
12851
12852			if (do_sg_copy != 0) {
12853				struct ctl_sg_entry *sgl;
12854				int j;
12855
12856				sgl = (struct ctl_sg_entry *)
12857					io->scsiio.kern_data_ptr;
12858				/*
12859				 * If this is in cached memory, flush the cache
12860				 * before we send the DMA request to the other
12861				 * controller.  We want to do this in either
12862				 * the * read or the write case.  The read
12863				 * case is straightforward.  In the write
12864				 * case, we want to make sure nothing is
12865				 * in the local cache that could overwrite
12866				 * the DMAed data.
12867				 */
12868
12869				for (i = sg_entries_sent, j = 0;
12870				     i < msg.dt.cur_sg_entries; i++, j++) {
12871					if ((io->io_hdr.flags &
12872					     CTL_FLAG_NO_DATASYNC) == 0) {
12873						/*
12874						 * XXX KDM use bus_dmamap_sync()
12875						 */
12876					}
12877					if ((io->io_hdr.flags &
12878					     CTL_FLAG_BUS_ADDR) == 0) {
12879						/*
12880						 * XXX KDM use busdma.
12881						 */
12882#if 0
12883						msg.dt.sg_list[j].addr =(void *)
12884						       vtophys(sgl[i].addr);
12885#endif
12886					} else {
12887						msg.dt.sg_list[j].addr =
12888							sgl[i].addr;
12889					}
12890					msg.dt.sg_list[j].len = sgl[i].len;
12891				}
12892			}
12893
12894			sg_entries_sent += msg.dt.cur_sg_entries;
12895			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12896				msg.dt.sg_last = 1;
12897			else
12898				msg.dt.sg_last = 0;
12899
12900			/*
12901			 * XXX KDM drop and reacquire the lock here?
12902			 */
12903			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12904			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12905				/*
12906				 * XXX do something here.
12907				 */
12908			}
12909
12910			msg.dt.sent_sg_entries = sg_entries_sent;
12911		}
12912		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12913		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12914			ctl_failover_io(io, /*have_lock*/ 0);
12915
12916	} else {
12917
12918		/*
12919		 * Lookup the fe_datamove() function for this particular
12920		 * front end.
12921		 */
12922		fe_datamove =
12923		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12924
12925		fe_datamove(io);
12926	}
12927}
12928
12929static void
12930ctl_send_datamove_done(union ctl_io *io, int have_lock)
12931{
12932	union ctl_ha_msg msg;
12933	int isc_status;
12934
12935	memset(&msg, 0, sizeof(msg));
12936
12937	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12938	msg.hdr.original_sc = io;
12939	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12940	msg.hdr.nexus = io->io_hdr.nexus;
12941	msg.hdr.status = io->io_hdr.status;
12942	msg.scsi.tag_num = io->scsiio.tag_num;
12943	msg.scsi.tag_type = io->scsiio.tag_type;
12944	msg.scsi.scsi_status = io->scsiio.scsi_status;
12945	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12946	       sizeof(io->scsiio.sense_data));
12947	msg.scsi.sense_len = io->scsiio.sense_len;
12948	msg.scsi.sense_residual = io->scsiio.sense_residual;
12949	msg.scsi.fetd_status = io->io_hdr.port_status;
12950	msg.scsi.residual = io->scsiio.residual;
12951	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12952
12953	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12954		ctl_failover_io(io, /*have_lock*/ have_lock);
12955		return;
12956	}
12957
12958	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12959	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12960		/* XXX do something if this fails */
12961	}
12962
12963}
12964
12965/*
12966 * The DMA to the remote side is done, now we need to tell the other side
12967 * we're done so it can continue with its data movement.
12968 */
12969static void
12970ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12971{
12972	union ctl_io *io;
12973
12974	io = rq->context;
12975
12976	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12977		printf("%s: ISC DMA write failed with error %d", __func__,
12978		       rq->ret);
12979		ctl_set_internal_failure(&io->scsiio,
12980					 /*sks_valid*/ 1,
12981					 /*retry_count*/ rq->ret);
12982	}
12983
12984	ctl_dt_req_free(rq);
12985
12986	/*
12987	 * In this case, we had to malloc the memory locally.  Free it.
12988	 */
12989	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12990		int i;
12991		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12992			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12993	}
12994	/*
12995	 * The data is in local and remote memory, so now we need to send
12996	 * status (good or back) back to the other side.
12997	 */
12998	ctl_send_datamove_done(io, /*have_lock*/ 0);
12999}
13000
13001/*
13002 * We've moved the data from the host/controller into local memory.  Now we
13003 * need to push it over to the remote controller's memory.
13004 */
13005static int
13006ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13007{
13008	int retval;
13009
13010	retval = 0;
13011
13012	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13013					  ctl_datamove_remote_write_cb);
13014
13015	return (retval);
13016}
13017
13018static void
13019ctl_datamove_remote_write(union ctl_io *io)
13020{
13021	int retval;
13022	void (*fe_datamove)(union ctl_io *io);
13023
13024	/*
13025	 * - Get the data from the host/HBA into local memory.
13026	 * - DMA memory from the local controller to the remote controller.
13027	 * - Send status back to the remote controller.
13028	 */
13029
13030	retval = ctl_datamove_remote_sgl_setup(io);
13031	if (retval != 0)
13032		return;
13033
13034	/* Switch the pointer over so the FETD knows what to do */
13035	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13036
13037	/*
13038	 * Use a custom move done callback, since we need to send completion
13039	 * back to the other controller, not to the backend on this side.
13040	 */
13041	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13042
13043	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13044
13045	fe_datamove(io);
13046
13047	return;
13048
13049}
13050
13051static int
13052ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13053{
13054#if 0
13055	char str[256];
13056	char path_str[64];
13057	struct sbuf sb;
13058#endif
13059
13060	/*
13061	 * In this case, we had to malloc the memory locally.  Free it.
13062	 */
13063	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13064		int i;
13065		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13066			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13067	}
13068
13069#if 0
13070	scsi_path_string(io, path_str, sizeof(path_str));
13071	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13072	sbuf_cat(&sb, path_str);
13073	scsi_command_string(&io->scsiio, NULL, &sb);
13074	sbuf_printf(&sb, "\n");
13075	sbuf_cat(&sb, path_str);
13076	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13077		    io->scsiio.tag_num, io->scsiio.tag_type);
13078	sbuf_cat(&sb, path_str);
13079	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13080		    io->io_hdr.flags, io->io_hdr.status);
13081	sbuf_finish(&sb);
13082	printk("%s", sbuf_data(&sb));
13083#endif
13084
13085
13086	/*
13087	 * The read is done, now we need to send status (good or bad) back
13088	 * to the other side.
13089	 */
13090	ctl_send_datamove_done(io, /*have_lock*/ 0);
13091
13092	return (0);
13093}
13094
13095static void
13096ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13097{
13098	union ctl_io *io;
13099	void (*fe_datamove)(union ctl_io *io);
13100
13101	io = rq->context;
13102
13103	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13104		printf("%s: ISC DMA read failed with error %d", __func__,
13105		       rq->ret);
13106		ctl_set_internal_failure(&io->scsiio,
13107					 /*sks_valid*/ 1,
13108					 /*retry_count*/ rq->ret);
13109	}
13110
13111	ctl_dt_req_free(rq);
13112
13113	/* Switch the pointer over so the FETD knows what to do */
13114	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13115
13116	/*
13117	 * Use a custom move done callback, since we need to send completion
13118	 * back to the other controller, not to the backend on this side.
13119	 */
13120	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13121
13122	/* XXX KDM add checks like the ones in ctl_datamove? */
13123
13124	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13125
13126	fe_datamove(io);
13127}
13128
13129static int
13130ctl_datamove_remote_sgl_setup(union ctl_io *io)
13131{
13132	struct ctl_sg_entry *local_sglist, *remote_sglist;
13133	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13134	struct ctl_softc *softc;
13135	int retval;
13136	int i;
13137
13138	retval = 0;
13139	softc = control_softc;
13140
13141	local_sglist = io->io_hdr.local_sglist;
13142	local_dma_sglist = io->io_hdr.local_dma_sglist;
13143	remote_sglist = io->io_hdr.remote_sglist;
13144	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13145
13146	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13147		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13148			local_sglist[i].len = remote_sglist[i].len;
13149
13150			/*
13151			 * XXX Detect the situation where the RS-level I/O
13152			 * redirector on the other side has already read the
13153			 * data off of the AOR RS on this side, and
13154			 * transferred it to remote (mirror) memory on the
13155			 * other side.  Since we already have the data in
13156			 * memory here, we just need to use it.
13157			 *
13158			 * XXX KDM this can probably be removed once we
13159			 * get the cache device code in and take the
13160			 * current AOR implementation out.
13161			 */
13162#ifdef NEEDTOPORT
13163			if ((remote_sglist[i].addr >=
13164			     (void *)vtophys(softc->mirr->addr))
13165			 && (remote_sglist[i].addr <
13166			     ((void *)vtophys(softc->mirr->addr) +
13167			     CacheMirrorOffset))) {
13168				local_sglist[i].addr = remote_sglist[i].addr -
13169					CacheMirrorOffset;
13170				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13171				     CTL_FLAG_DATA_IN)
13172					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13173			} else {
13174				local_sglist[i].addr = remote_sglist[i].addr +
13175					CacheMirrorOffset;
13176			}
13177#endif
13178#if 0
13179			printf("%s: local %p, remote %p, len %d\n",
13180			       __func__, local_sglist[i].addr,
13181			       remote_sglist[i].addr, local_sglist[i].len);
13182#endif
13183		}
13184	} else {
13185		uint32_t len_to_go;
13186
13187		/*
13188		 * In this case, we don't have automatically allocated
13189		 * memory for this I/O on this controller.  This typically
13190		 * happens with internal CTL I/O -- e.g. inquiry, mode
13191		 * sense, etc.  Anything coming from RAIDCore will have
13192		 * a mirror area available.
13193		 */
13194		len_to_go = io->scsiio.kern_data_len;
13195
13196		/*
13197		 * Clear the no datasync flag, we have to use malloced
13198		 * buffers.
13199		 */
13200		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13201
13202		/*
13203		 * The difficult thing here is that the size of the various
13204		 * S/G segments may be different than the size from the
13205		 * remote controller.  That'll make it harder when DMAing
13206		 * the data back to the other side.
13207		 */
13208		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13209		     sizeof(io->io_hdr.remote_sglist[0])) &&
13210		     (len_to_go > 0); i++) {
13211			local_sglist[i].len = ctl_min(len_to_go, 131072);
13212			CTL_SIZE_8B(local_dma_sglist[i].len,
13213				    local_sglist[i].len);
13214			local_sglist[i].addr =
13215				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13216
13217			local_dma_sglist[i].addr = local_sglist[i].addr;
13218
13219			if (local_sglist[i].addr == NULL) {
13220				int j;
13221
13222				printf("malloc failed for %zd bytes!",
13223				       local_dma_sglist[i].len);
13224				for (j = 0; j < i; j++) {
13225					free(local_sglist[j].addr, M_CTL);
13226				}
13227				ctl_set_internal_failure(&io->scsiio,
13228							 /*sks_valid*/ 1,
13229							 /*retry_count*/ 4857);
13230				retval = 1;
13231				goto bailout_error;
13232
13233			}
13234			/* XXX KDM do we need a sync here? */
13235
13236			len_to_go -= local_sglist[i].len;
13237		}
13238		/*
13239		 * Reset the number of S/G entries accordingly.  The
13240		 * original number of S/G entries is available in
13241		 * rem_sg_entries.
13242		 */
13243		io->scsiio.kern_sg_entries = i;
13244
13245#if 0
13246		printf("%s: kern_sg_entries = %d\n", __func__,
13247		       io->scsiio.kern_sg_entries);
13248		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13249			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13250			       local_sglist[i].addr, local_sglist[i].len,
13251			       local_dma_sglist[i].len);
13252#endif
13253	}
13254
13255
13256	return (retval);
13257
13258bailout_error:
13259
13260	ctl_send_datamove_done(io, /*have_lock*/ 0);
13261
13262	return (retval);
13263}
13264
13265static int
13266ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13267			 ctl_ha_dt_cb callback)
13268{
13269	struct ctl_ha_dt_req *rq;
13270	struct ctl_sg_entry *remote_sglist, *local_sglist;
13271	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13272	uint32_t local_used, remote_used, total_used;
13273	int retval;
13274	int i, j;
13275
13276	retval = 0;
13277
13278	rq = ctl_dt_req_alloc();
13279
13280	/*
13281	 * If we failed to allocate the request, and if the DMA didn't fail
13282	 * anyway, set busy status.  This is just a resource allocation
13283	 * failure.
13284	 */
13285	if ((rq == NULL)
13286	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13287		ctl_set_busy(&io->scsiio);
13288
13289	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13290
13291		if (rq != NULL)
13292			ctl_dt_req_free(rq);
13293
13294		/*
13295		 * The data move failed.  We need to return status back
13296		 * to the other controller.  No point in trying to DMA
13297		 * data to the remote controller.
13298		 */
13299
13300		ctl_send_datamove_done(io, /*have_lock*/ 0);
13301
13302		retval = 1;
13303
13304		goto bailout;
13305	}
13306
13307	local_sglist = io->io_hdr.local_sglist;
13308	local_dma_sglist = io->io_hdr.local_dma_sglist;
13309	remote_sglist = io->io_hdr.remote_sglist;
13310	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13311	local_used = 0;
13312	remote_used = 0;
13313	total_used = 0;
13314
13315	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13316		rq->ret = CTL_HA_STATUS_SUCCESS;
13317		rq->context = io;
13318		callback(rq);
13319		goto bailout;
13320	}
13321
13322	/*
13323	 * Pull/push the data over the wire from/to the other controller.
13324	 * This takes into account the possibility that the local and
13325	 * remote sglists may not be identical in terms of the size of
13326	 * the elements and the number of elements.
13327	 *
13328	 * One fundamental assumption here is that the length allocated for
13329	 * both the local and remote sglists is identical.  Otherwise, we've
13330	 * essentially got a coding error of some sort.
13331	 */
13332	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13333		int isc_ret;
13334		uint32_t cur_len, dma_length;
13335		uint8_t *tmp_ptr;
13336
13337		rq->id = CTL_HA_DATA_CTL;
13338		rq->command = command;
13339		rq->context = io;
13340
13341		/*
13342		 * Both pointers should be aligned.  But it is possible
13343		 * that the allocation length is not.  They should both
13344		 * also have enough slack left over at the end, though,
13345		 * to round up to the next 8 byte boundary.
13346		 */
13347		cur_len = ctl_min(local_sglist[i].len - local_used,
13348				  remote_sglist[j].len - remote_used);
13349
13350		/*
13351		 * In this case, we have a size issue and need to decrease
13352		 * the size, except in the case where we actually have less
13353		 * than 8 bytes left.  In that case, we need to increase
13354		 * the DMA length to get the last bit.
13355		 */
13356		if ((cur_len & 0x7) != 0) {
13357			if (cur_len > 0x7) {
13358				cur_len = cur_len - (cur_len & 0x7);
13359				dma_length = cur_len;
13360			} else {
13361				CTL_SIZE_8B(dma_length, cur_len);
13362			}
13363
13364		} else
13365			dma_length = cur_len;
13366
13367		/*
13368		 * If we had to allocate memory for this I/O, instead of using
13369		 * the non-cached mirror memory, we'll need to flush the cache
13370		 * before trying to DMA to the other controller.
13371		 *
13372		 * We could end up doing this multiple times for the same
13373		 * segment if we have a larger local segment than remote
13374		 * segment.  That shouldn't be an issue.
13375		 */
13376		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13377			/*
13378			 * XXX KDM use bus_dmamap_sync() here.
13379			 */
13380		}
13381
13382		rq->size = dma_length;
13383
13384		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13385		tmp_ptr += local_used;
13386
13387		/* Use physical addresses when talking to ISC hardware */
13388		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13389			/* XXX KDM use busdma */
13390#if 0
13391			rq->local = vtophys(tmp_ptr);
13392#endif
13393		} else
13394			rq->local = tmp_ptr;
13395
13396		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13397		tmp_ptr += remote_used;
13398		rq->remote = tmp_ptr;
13399
13400		rq->callback = NULL;
13401
13402		local_used += cur_len;
13403		if (local_used >= local_sglist[i].len) {
13404			i++;
13405			local_used = 0;
13406		}
13407
13408		remote_used += cur_len;
13409		if (remote_used >= remote_sglist[j].len) {
13410			j++;
13411			remote_used = 0;
13412		}
13413		total_used += cur_len;
13414
13415		if (total_used >= io->scsiio.kern_data_len)
13416			rq->callback = callback;
13417
13418		if ((rq->size & 0x7) != 0) {
13419			printf("%s: warning: size %d is not on 8b boundary\n",
13420			       __func__, rq->size);
13421		}
13422		if (((uintptr_t)rq->local & 0x7) != 0) {
13423			printf("%s: warning: local %p not on 8b boundary\n",
13424			       __func__, rq->local);
13425		}
13426		if (((uintptr_t)rq->remote & 0x7) != 0) {
13427			printf("%s: warning: remote %p not on 8b boundary\n",
13428			       __func__, rq->local);
13429		}
13430#if 0
13431		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13432		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13433		       rq->local, rq->remote, rq->size);
13434#endif
13435
13436		isc_ret = ctl_dt_single(rq);
13437		if (isc_ret == CTL_HA_STATUS_WAIT)
13438			continue;
13439
13440		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13441			rq->ret = CTL_HA_STATUS_SUCCESS;
13442		} else {
13443			rq->ret = isc_ret;
13444		}
13445		callback(rq);
13446		goto bailout;
13447	}
13448
13449bailout:
13450	return (retval);
13451
13452}
13453
13454static void
13455ctl_datamove_remote_read(union ctl_io *io)
13456{
13457	int retval;
13458	int i;
13459
13460	/*
13461	 * This will send an error to the other controller in the case of a
13462	 * failure.
13463	 */
13464	retval = ctl_datamove_remote_sgl_setup(io);
13465	if (retval != 0)
13466		return;
13467
13468	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13469					  ctl_datamove_remote_read_cb);
13470	if ((retval != 0)
13471	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13472		/*
13473		 * Make sure we free memory if there was an error..  The
13474		 * ctl_datamove_remote_xfer() function will send the
13475		 * datamove done message, or call the callback with an
13476		 * error if there is a problem.
13477		 */
13478		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13479			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13480	}
13481
13482	return;
13483}
13484
13485/*
13486 * Process a datamove request from the other controller.  This is used for
13487 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13488 * first.  Once that is complete, the data gets DMAed into the remote
13489 * controller's memory.  For reads, we DMA from the remote controller's
13490 * memory into our memory first, and then move it out to the FETD.
13491 */
13492static void
13493ctl_datamove_remote(union ctl_io *io)
13494{
13495	struct ctl_softc *softc;
13496
13497	softc = control_softc;
13498
13499	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13500
13501	/*
13502	 * Note that we look for an aborted I/O here, but don't do some of
13503	 * the other checks that ctl_datamove() normally does.
13504	 * We don't need to run the datamove delay code, since that should
13505	 * have been done if need be on the other controller.
13506	 */
13507	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13508		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13509		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13510		       io->io_hdr.nexus.targ_port,
13511		       io->io_hdr.nexus.targ_target.id,
13512		       io->io_hdr.nexus.targ_lun);
13513		io->io_hdr.port_status = 31338;
13514		ctl_send_datamove_done(io, /*have_lock*/ 0);
13515		return;
13516	}
13517
13518	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13519		ctl_datamove_remote_write(io);
13520	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13521		ctl_datamove_remote_read(io);
13522	} else {
13523		union ctl_ha_msg msg;
13524		struct scsi_sense_data *sense;
13525		uint8_t sks[3];
13526		int retry_count;
13527
13528		memset(&msg, 0, sizeof(msg));
13529
13530		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13531		msg.hdr.status = CTL_SCSI_ERROR;
13532		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13533
13534		retry_count = 4243;
13535
13536		sense = &msg.scsi.sense_data;
13537		sks[0] = SSD_SCS_VALID;
13538		sks[1] = (retry_count >> 8) & 0xff;
13539		sks[2] = retry_count & 0xff;
13540
13541		/* "Internal target failure" */
13542		scsi_set_sense_data(sense,
13543				    /*sense_format*/ SSD_TYPE_NONE,
13544				    /*current_error*/ 1,
13545				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13546				    /*asc*/ 0x44,
13547				    /*ascq*/ 0x00,
13548				    /*type*/ SSD_ELEM_SKS,
13549				    /*size*/ sizeof(sks),
13550				    /*data*/ sks,
13551				    SSD_ELEM_NONE);
13552
13553		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13554		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13555			ctl_failover_io(io, /*have_lock*/ 1);
13556			return;
13557		}
13558
13559		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13560		    CTL_HA_STATUS_SUCCESS) {
13561			/* XXX KDM what to do if this fails? */
13562		}
13563		return;
13564	}
13565
13566}
13567
13568static int
13569ctl_process_done(union ctl_io *io)
13570{
13571	struct ctl_lun *lun;
13572	struct ctl_softc *ctl_softc;
13573	void (*fe_done)(union ctl_io *io);
13574	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13575
13576	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13577
13578	fe_done =
13579	    control_softc->ctl_ports[targ_port]->fe_done;
13580
13581#ifdef CTL_TIME_IO
13582	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13583		char str[256];
13584		char path_str[64];
13585		struct sbuf sb;
13586
13587		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13588		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13589
13590		sbuf_cat(&sb, path_str);
13591		switch (io->io_hdr.io_type) {
13592		case CTL_IO_SCSI:
13593			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13594			sbuf_printf(&sb, "\n");
13595			sbuf_cat(&sb, path_str);
13596			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13597				    io->scsiio.tag_num, io->scsiio.tag_type);
13598			break;
13599		case CTL_IO_TASK:
13600			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13601				    "Tag Type: %d\n", io->taskio.task_action,
13602				    io->taskio.tag_num, io->taskio.tag_type);
13603			break;
13604		default:
13605			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13606			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13607			break;
13608		}
13609		sbuf_cat(&sb, path_str);
13610		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13611			    (intmax_t)time_uptime - io->io_hdr.start_time);
13612		sbuf_finish(&sb);
13613		printf("%s", sbuf_data(&sb));
13614	}
13615#endif /* CTL_TIME_IO */
13616
13617	switch (io->io_hdr.io_type) {
13618	case CTL_IO_SCSI:
13619		break;
13620	case CTL_IO_TASK:
13621		if (bootverbose || verbose > 0)
13622			ctl_io_error_print(io, NULL);
13623		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13624			ctl_free_io(io);
13625		else
13626			fe_done(io);
13627		return (CTL_RETVAL_COMPLETE);
13628		break;
13629	default:
13630		printf("ctl_process_done: invalid io type %d\n",
13631		       io->io_hdr.io_type);
13632		panic("ctl_process_done: invalid io type %d\n",
13633		      io->io_hdr.io_type);
13634		break; /* NOTREACHED */
13635	}
13636
13637	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13638	if (lun == NULL) {
13639		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13640				 io->io_hdr.nexus.targ_mapped_lun));
13641		fe_done(io);
13642		goto bailout;
13643	}
13644	ctl_softc = lun->ctl_softc;
13645
13646	mtx_lock(&lun->lun_lock);
13647
13648	/*
13649	 * Check to see if we have any errors to inject here.  We only
13650	 * inject errors for commands that don't already have errors set.
13651	 */
13652	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13653	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13654		ctl_inject_error(lun, io);
13655
13656	/*
13657	 * XXX KDM how do we treat commands that aren't completed
13658	 * successfully?
13659	 *
13660	 * XXX KDM should we also track I/O latency?
13661	 */
13662	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13663	    io->io_hdr.io_type == CTL_IO_SCSI) {
13664#ifdef CTL_TIME_IO
13665		struct bintime cur_bt;
13666#endif
13667		int type;
13668
13669		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13670		    CTL_FLAG_DATA_IN)
13671			type = CTL_STATS_READ;
13672		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13673		    CTL_FLAG_DATA_OUT)
13674			type = CTL_STATS_WRITE;
13675		else
13676			type = CTL_STATS_NO_IO;
13677
13678		lun->stats.ports[targ_port].bytes[type] +=
13679		    io->scsiio.kern_total_len;
13680		lun->stats.ports[targ_port].operations[type]++;
13681#ifdef CTL_TIME_IO
13682		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13683		   &io->io_hdr.dma_bt);
13684		lun->stats.ports[targ_port].num_dmas[type] +=
13685		    io->io_hdr.num_dmas;
13686		getbintime(&cur_bt);
13687		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13688		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13689#endif
13690	}
13691
13692	/*
13693	 * Remove this from the OOA queue.
13694	 */
13695	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13696
13697	/*
13698	 * Run through the blocked queue on this LUN and see if anything
13699	 * has become unblocked, now that this transaction is done.
13700	 */
13701	ctl_check_blocked(lun);
13702
13703	/*
13704	 * If the LUN has been invalidated, free it if there is nothing
13705	 * left on its OOA queue.
13706	 */
13707	if ((lun->flags & CTL_LUN_INVALID)
13708	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13709		mtx_unlock(&lun->lun_lock);
13710		mtx_lock(&ctl_softc->ctl_lock);
13711		ctl_free_lun(lun);
13712		mtx_unlock(&ctl_softc->ctl_lock);
13713	} else
13714		mtx_unlock(&lun->lun_lock);
13715
13716	/*
13717	 * If this command has been aborted, make sure we set the status
13718	 * properly.  The FETD is responsible for freeing the I/O and doing
13719	 * whatever it needs to do to clean up its state.
13720	 */
13721	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13722		ctl_set_task_aborted(&io->scsiio);
13723
13724	/*
13725	 * We print out status for every task management command.  For SCSI
13726	 * commands, we filter out any unit attention errors; they happen
13727	 * on every boot, and would clutter up the log.  Note:  task
13728	 * management commands aren't printed here, they are printed above,
13729	 * since they should never even make it down here.
13730	 */
13731	switch (io->io_hdr.io_type) {
13732	case CTL_IO_SCSI: {
13733		int error_code, sense_key, asc, ascq;
13734
13735		sense_key = 0;
13736
13737		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13738		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13739			/*
13740			 * Since this is just for printing, no need to
13741			 * show errors here.
13742			 */
13743			scsi_extract_sense_len(&io->scsiio.sense_data,
13744					       io->scsiio.sense_len,
13745					       &error_code,
13746					       &sense_key,
13747					       &asc,
13748					       &ascq,
13749					       /*show_errors*/ 0);
13750		}
13751
13752		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13753		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13754		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13755		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13756
13757			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13758				ctl_softc->skipped_prints++;
13759			} else {
13760				uint32_t skipped_prints;
13761
13762				skipped_prints = ctl_softc->skipped_prints;
13763
13764				ctl_softc->skipped_prints = 0;
13765				ctl_softc->last_print_jiffies = time_uptime;
13766
13767				if (skipped_prints > 0) {
13768#ifdef NEEDTOPORT
13769					csevent_log(CSC_CTL | CSC_SHELF_SW |
13770					    CTL_ERROR_REPORT,
13771					    csevent_LogType_Trace,
13772					    csevent_Severity_Information,
13773					    csevent_AlertLevel_Green,
13774					    csevent_FRU_Firmware,
13775					    csevent_FRU_Unknown,
13776					    "High CTL error volume, %d prints "
13777					    "skipped", skipped_prints);
13778#endif
13779				}
13780				if (bootverbose || verbose > 0)
13781					ctl_io_error_print(io, NULL);
13782			}
13783		}
13784		break;
13785	}
13786	case CTL_IO_TASK:
13787		if (bootverbose || verbose > 0)
13788			ctl_io_error_print(io, NULL);
13789		break;
13790	default:
13791		break;
13792	}
13793
13794	/*
13795	 * Tell the FETD or the other shelf controller we're done with this
13796	 * command.  Note that only SCSI commands get to this point.  Task
13797	 * management commands are completed above.
13798	 *
13799	 * We only send status to the other controller if we're in XFER
13800	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13801	 * received the I/O (from CTL's perspective), and so the status is
13802	 * generated there.
13803	 *
13804	 * XXX KDM if we hold the lock here, we could cause a deadlock
13805	 * if the frontend comes back in in this context to queue
13806	 * something.
13807	 */
13808	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13809	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13810		union ctl_ha_msg msg;
13811
13812		memset(&msg, 0, sizeof(msg));
13813		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13814		msg.hdr.original_sc = io->io_hdr.original_sc;
13815		msg.hdr.nexus = io->io_hdr.nexus;
13816		msg.hdr.status = io->io_hdr.status;
13817		msg.scsi.scsi_status = io->scsiio.scsi_status;
13818		msg.scsi.tag_num = io->scsiio.tag_num;
13819		msg.scsi.tag_type = io->scsiio.tag_type;
13820		msg.scsi.sense_len = io->scsiio.sense_len;
13821		msg.scsi.sense_residual = io->scsiio.sense_residual;
13822		msg.scsi.residual = io->scsiio.residual;
13823		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13824		       sizeof(io->scsiio.sense_data));
13825		/*
13826		 * We copy this whether or not this is an I/O-related
13827		 * command.  Otherwise, we'd have to go and check to see
13828		 * whether it's a read/write command, and it really isn't
13829		 * worth it.
13830		 */
13831		memcpy(&msg.scsi.lbalen,
13832		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13833		       sizeof(msg.scsi.lbalen));
13834
13835		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13836				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13837			/* XXX do something here */
13838		}
13839
13840		ctl_free_io(io);
13841	} else
13842		fe_done(io);
13843
13844bailout:
13845
13846	return (CTL_RETVAL_COMPLETE);
13847}
13848
13849#ifdef CTL_WITH_CA
13850/*
13851 * Front end should call this if it doesn't do autosense.  When the request
13852 * sense comes back in from the initiator, we'll dequeue this and send it.
13853 */
13854int
13855ctl_queue_sense(union ctl_io *io)
13856{
13857	struct ctl_lun *lun;
13858	struct ctl_softc *ctl_softc;
13859	uint32_t initidx, targ_lun;
13860
13861	ctl_softc = control_softc;
13862
13863	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13864
13865	/*
13866	 * LUN lookup will likely move to the ctl_work_thread() once we
13867	 * have our new queueing infrastructure (that doesn't put things on
13868	 * a per-LUN queue initially).  That is so that we can handle
13869	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13870	 * can't deal with that right now.
13871	 */
13872	mtx_lock(&ctl_softc->ctl_lock);
13873
13874	/*
13875	 * If we don't have a LUN for this, just toss the sense
13876	 * information.
13877	 */
13878	targ_lun = io->io_hdr.nexus.targ_lun;
13879	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13880	if ((targ_lun < CTL_MAX_LUNS)
13881	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13882		lun = ctl_softc->ctl_luns[targ_lun];
13883	else
13884		goto bailout;
13885
13886	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13887
13888	mtx_lock(&lun->lun_lock);
13889	/*
13890	 * Already have CA set for this LUN...toss the sense information.
13891	 */
13892	if (ctl_is_set(lun->have_ca, initidx)) {
13893		mtx_unlock(&lun->lun_lock);
13894		goto bailout;
13895	}
13896
13897	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13898	       ctl_min(sizeof(lun->pending_sense[initidx]),
13899	       sizeof(io->scsiio.sense_data)));
13900	ctl_set_mask(lun->have_ca, initidx);
13901	mtx_unlock(&lun->lun_lock);
13902
13903bailout:
13904	mtx_unlock(&ctl_softc->ctl_lock);
13905
13906	ctl_free_io(io);
13907
13908	return (CTL_RETVAL_COMPLETE);
13909}
13910#endif
13911
13912/*
13913 * Primary command inlet from frontend ports.  All SCSI and task I/O
13914 * requests must go through this function.
13915 */
13916int
13917ctl_queue(union ctl_io *io)
13918{
13919	struct ctl_softc *ctl_softc;
13920
13921	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13922
13923	ctl_softc = control_softc;
13924
13925#ifdef CTL_TIME_IO
13926	io->io_hdr.start_time = time_uptime;
13927	getbintime(&io->io_hdr.start_bt);
13928#endif /* CTL_TIME_IO */
13929
13930	/* Map FE-specific LUN ID into global one. */
13931	io->io_hdr.nexus.targ_mapped_lun =
13932	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13933
13934	switch (io->io_hdr.io_type) {
13935	case CTL_IO_SCSI:
13936	case CTL_IO_TASK:
13937		ctl_enqueue_incoming(io);
13938		break;
13939	default:
13940		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13941		return (EINVAL);
13942	}
13943
13944	return (CTL_RETVAL_COMPLETE);
13945}
13946
13947#ifdef CTL_IO_DELAY
13948static void
13949ctl_done_timer_wakeup(void *arg)
13950{
13951	union ctl_io *io;
13952
13953	io = (union ctl_io *)arg;
13954	ctl_done(io);
13955}
13956#endif /* CTL_IO_DELAY */
13957
13958void
13959ctl_done(union ctl_io *io)
13960{
13961	struct ctl_softc *ctl_softc;
13962
13963	ctl_softc = control_softc;
13964
13965	/*
13966	 * Enable this to catch duplicate completion issues.
13967	 */
13968#if 0
13969	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13970		printf("%s: type %d msg %d cdb %x iptl: "
13971		       "%d:%d:%d:%d tag 0x%04x "
13972		       "flag %#x status %x\n",
13973			__func__,
13974			io->io_hdr.io_type,
13975			io->io_hdr.msg_type,
13976			io->scsiio.cdb[0],
13977			io->io_hdr.nexus.initid.id,
13978			io->io_hdr.nexus.targ_port,
13979			io->io_hdr.nexus.targ_target.id,
13980			io->io_hdr.nexus.targ_lun,
13981			(io->io_hdr.io_type ==
13982			CTL_IO_TASK) ?
13983			io->taskio.tag_num :
13984			io->scsiio.tag_num,
13985		        io->io_hdr.flags,
13986			io->io_hdr.status);
13987	} else
13988		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13989#endif
13990
13991	/*
13992	 * This is an internal copy of an I/O, and should not go through
13993	 * the normal done processing logic.
13994	 */
13995	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13996		return;
13997
13998	/*
13999	 * We need to send a msg to the serializing shelf to finish the IO
14000	 * as well.  We don't send a finish message to the other shelf if
14001	 * this is a task management command.  Task management commands
14002	 * aren't serialized in the OOA queue, but rather just executed on
14003	 * both shelf controllers for commands that originated on that
14004	 * controller.
14005	 */
14006	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14007	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14008		union ctl_ha_msg msg_io;
14009
14010		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14011		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14012		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14013		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14014		}
14015		/* continue on to finish IO */
14016	}
14017#ifdef CTL_IO_DELAY
14018	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14019		struct ctl_lun *lun;
14020
14021		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14022
14023		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14024	} else {
14025		struct ctl_lun *lun;
14026
14027		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14028
14029		if ((lun != NULL)
14030		 && (lun->delay_info.done_delay > 0)) {
14031			struct callout *callout;
14032
14033			callout = (struct callout *)&io->io_hdr.timer_bytes;
14034			callout_init(callout, /*mpsafe*/ 1);
14035			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14036			callout_reset(callout,
14037				      lun->delay_info.done_delay * hz,
14038				      ctl_done_timer_wakeup, io);
14039			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14040				lun->delay_info.done_delay = 0;
14041			return;
14042		}
14043	}
14044#endif /* CTL_IO_DELAY */
14045
14046	ctl_enqueue_done(io);
14047}
14048
14049int
14050ctl_isc(struct ctl_scsiio *ctsio)
14051{
14052	struct ctl_lun *lun;
14053	int retval;
14054
14055	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14056
14057	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14058
14059	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14060
14061	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14062
14063	return (retval);
14064}
14065
14066
14067static void
14068ctl_work_thread(void *arg)
14069{
14070	struct ctl_thread *thr = (struct ctl_thread *)arg;
14071	struct ctl_softc *softc = thr->ctl_softc;
14072	union ctl_io *io;
14073	int retval;
14074
14075	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14076
14077	for (;;) {
14078		retval = 0;
14079
14080		/*
14081		 * We handle the queues in this order:
14082		 * - ISC
14083		 * - done queue (to free up resources, unblock other commands)
14084		 * - RtR queue
14085		 * - incoming queue
14086		 *
14087		 * If those queues are empty, we break out of the loop and
14088		 * go to sleep.
14089		 */
14090		mtx_lock(&thr->queue_lock);
14091		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14092		if (io != NULL) {
14093			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14094			mtx_unlock(&thr->queue_lock);
14095			ctl_handle_isc(io);
14096			continue;
14097		}
14098		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14099		if (io != NULL) {
14100			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14101			/* clear any blocked commands, call fe_done */
14102			mtx_unlock(&thr->queue_lock);
14103			retval = ctl_process_done(io);
14104			continue;
14105		}
14106		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14107		if (io != NULL) {
14108			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14109			mtx_unlock(&thr->queue_lock);
14110			if (io->io_hdr.io_type == CTL_IO_TASK)
14111				ctl_run_task(io);
14112			else
14113				ctl_scsiio_precheck(softc, &io->scsiio);
14114			continue;
14115		}
14116		if (!ctl_pause_rtr) {
14117			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14118			if (io != NULL) {
14119				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14120				mtx_unlock(&thr->queue_lock);
14121				retval = ctl_scsiio(&io->scsiio);
14122				if (retval != CTL_RETVAL_COMPLETE)
14123					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14124				continue;
14125			}
14126		}
14127
14128		/* Sleep until we have something to do. */
14129		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14130	}
14131}
14132
14133static void
14134ctl_lun_thread(void *arg)
14135{
14136	struct ctl_softc *softc = (struct ctl_softc *)arg;
14137	struct ctl_be_lun *be_lun;
14138	int retval;
14139
14140	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14141
14142	for (;;) {
14143		retval = 0;
14144		mtx_lock(&softc->ctl_lock);
14145		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14146		if (be_lun != NULL) {
14147			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14148			mtx_unlock(&softc->ctl_lock);
14149			ctl_create_lun(be_lun);
14150			continue;
14151		}
14152
14153		/* Sleep until we have something to do. */
14154		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14155		    PDROP | PRIBIO, "-", 0);
14156	}
14157}
14158
14159static void
14160ctl_enqueue_incoming(union ctl_io *io)
14161{
14162	struct ctl_softc *softc = control_softc;
14163	struct ctl_thread *thr;
14164	u_int idx;
14165
14166	idx = (io->io_hdr.nexus.targ_port * 127 +
14167	       io->io_hdr.nexus.initid.id) % worker_threads;
14168	thr = &softc->threads[idx];
14169	mtx_lock(&thr->queue_lock);
14170	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14171	mtx_unlock(&thr->queue_lock);
14172	wakeup(thr);
14173}
14174
14175static void
14176ctl_enqueue_rtr(union ctl_io *io)
14177{
14178	struct ctl_softc *softc = control_softc;
14179	struct ctl_thread *thr;
14180
14181	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14182	mtx_lock(&thr->queue_lock);
14183	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14184	mtx_unlock(&thr->queue_lock);
14185	wakeup(thr);
14186}
14187
14188static void
14189ctl_enqueue_done(union ctl_io *io)
14190{
14191	struct ctl_softc *softc = control_softc;
14192	struct ctl_thread *thr;
14193
14194	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14195	mtx_lock(&thr->queue_lock);
14196	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14197	mtx_unlock(&thr->queue_lock);
14198	wakeup(thr);
14199}
14200
14201static void
14202ctl_enqueue_isc(union ctl_io *io)
14203{
14204	struct ctl_softc *softc = control_softc;
14205	struct ctl_thread *thr;
14206
14207	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14208	mtx_lock(&thr->queue_lock);
14209	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14210	mtx_unlock(&thr->queue_lock);
14211	wakeup(thr);
14212}
14213
14214/* Initialization and failover */
14215
14216void
14217ctl_init_isc_msg(void)
14218{
14219	printf("CTL: Still calling this thing\n");
14220}
14221
14222/*
14223 * Init component
14224 * 	Initializes component into configuration defined by bootMode
14225 *	(see hasc-sv.c)
14226 *  	returns hasc_Status:
14227 * 		OK
14228 *		ERROR - fatal error
14229 */
14230static ctl_ha_comp_status
14231ctl_isc_init(struct ctl_ha_component *c)
14232{
14233	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14234
14235	c->status = ret;
14236	return ret;
14237}
14238
14239/* Start component
14240 * 	Starts component in state requested. If component starts successfully,
14241 *	it must set its own state to the requestrd state
14242 *	When requested state is HASC_STATE_HA, the component may refine it
14243 * 	by adding _SLAVE or _MASTER flags.
14244 *	Currently allowed state transitions are:
14245 *	UNKNOWN->HA		- initial startup
14246 *	UNKNOWN->SINGLE - initial startup when no parter detected
14247 *	HA->SINGLE		- failover
14248 * returns ctl_ha_comp_status:
14249 * 		OK	- component successfully started in requested state
14250 *		FAILED  - could not start the requested state, failover may
14251 * 			  be possible
14252 *		ERROR	- fatal error detected, no future startup possible
14253 */
14254static ctl_ha_comp_status
14255ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14256{
14257	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14258
14259	printf("%s: go\n", __func__);
14260
14261	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14262	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14263		ctl_is_single = 0;
14264		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14265		    != CTL_HA_STATUS_SUCCESS) {
14266			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14267			ret = CTL_HA_COMP_STATUS_ERROR;
14268		}
14269	} else if (CTL_HA_STATE_IS_HA(c->state)
14270		&& CTL_HA_STATE_IS_SINGLE(state)){
14271		// HA->SINGLE transition
14272	        ctl_failover();
14273		ctl_is_single = 1;
14274	} else {
14275		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14276		       c->state, state);
14277		ret = CTL_HA_COMP_STATUS_ERROR;
14278	}
14279	if (CTL_HA_STATE_IS_SINGLE(state))
14280		ctl_is_single = 1;
14281
14282	c->state = state;
14283	c->status = ret;
14284	return ret;
14285}
14286
14287/*
14288 * Quiesce component
14289 * The component must clear any error conditions (set status to OK) and
14290 * prepare itself to another Start call
14291 * returns ctl_ha_comp_status:
14292 * 	OK
14293 *	ERROR
14294 */
14295static ctl_ha_comp_status
14296ctl_isc_quiesce(struct ctl_ha_component *c)
14297{
14298	int ret = CTL_HA_COMP_STATUS_OK;
14299
14300	ctl_pause_rtr = 1;
14301	c->status = ret;
14302	return ret;
14303}
14304
14305struct ctl_ha_component ctl_ha_component_ctlisc =
14306{
14307	.name = "CTL ISC",
14308	.state = CTL_HA_STATE_UNKNOWN,
14309	.init = ctl_isc_init,
14310	.start = ctl_isc_start,
14311	.quiesce = ctl_isc_quiesce
14312};
14313
14314/*
14315 *  vim: ts=8
14316 */
14317