ctl.c revision 272617
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: stable/10/sys/cam/ctl/ctl.c 272617 2014-10-06 12:36:42Z 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*/0,
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*/0,
296	/*eca_and_aen*/0,
297	/*flags4*/0,
298	/*aen_holdoff_period*/{0, 0},
299	/*busy_timeout_period*/{0, 0},
300	/*extended_selftest_completion_time*/{0, 0}
301};
302
303
304/*
305 * XXX KDM move these into the softc.
306 */
307static int rcv_sync_msg;
308static int persis_offset;
309static uint8_t ctl_pause_rtr;
310static int     ctl_is_single = 1;
311static int     index_to_aps_page;
312
313SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314static int worker_threads = -1;
315TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
316SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
317    &worker_threads, 1, "Number of worker threads");
318static int verbose = 0;
319TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
320SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
321    &verbose, 0, "Show SCSI errors returned to initiator");
322
323/*
324 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
325 * Mode Page Policy (0x87),
326 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
327 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
328 */
329#define SCSI_EVPD_NUM_SUPPORTED_PAGES	9
330
331static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
332				  int param);
333static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
334static int ctl_init(void);
335void ctl_shutdown(void);
336static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
337static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
338static void ctl_ioctl_online(void *arg);
339static void ctl_ioctl_offline(void *arg);
340static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
341static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
342static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
343static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
344static int ctl_ioctl_submit_wait(union ctl_io *io);
345static void ctl_ioctl_datamove(union ctl_io *io);
346static void ctl_ioctl_done(union ctl_io *io);
347static void ctl_ioctl_hard_startstop_callback(void *arg,
348					      struct cfi_metatask *metatask);
349static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
350static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
351			      struct ctl_ooa *ooa_hdr,
352			      struct ctl_ooa_entry *kern_entries);
353static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
354		     struct thread *td);
355static uint32_t ctl_map_lun(int port_num, uint32_t lun);
356static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
357#ifdef unused
358static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
359				   uint32_t targ_target, uint32_t targ_lun,
360				   int can_wait);
361static void ctl_kfree_io(union ctl_io *io);
362#endif /* unused */
363static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
364			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
365static int ctl_free_lun(struct ctl_lun *lun);
366static void ctl_create_lun(struct ctl_be_lun *be_lun);
367/**
368static void ctl_failover_change_pages(struct ctl_softc *softc,
369				      struct ctl_scsiio *ctsio, int master);
370**/
371
372static int ctl_do_mode_select(union ctl_io *io);
373static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
374			   uint64_t res_key, uint64_t sa_res_key,
375			   uint8_t type, uint32_t residx,
376			   struct ctl_scsiio *ctsio,
377			   struct scsi_per_res_out *cdb,
378			   struct scsi_per_res_out_parms* param);
379static void ctl_pro_preempt_other(struct ctl_lun *lun,
380				  union ctl_ha_msg *msg);
381static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
382static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
383static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
385static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
386static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
387					 int alloc_len);
388static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
389					 int alloc_len);
390static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
391static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
392static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
393static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
394static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
395static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
396static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
397					 union ctl_io *ooa_io);
398static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
399				union ctl_io *starting_io);
400static int ctl_check_blocked(struct ctl_lun *lun);
401static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
402				struct ctl_lun *lun,
403				const struct ctl_cmd_entry *entry,
404				struct ctl_scsiio *ctsio);
405//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
406static void ctl_failover(void);
407static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
408			       struct ctl_scsiio *ctsio);
409static int ctl_scsiio(struct ctl_scsiio *ctsio);
410
411static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
412static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
413			    ctl_ua_type ua_type);
414static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
415			 ctl_ua_type ua_type);
416static int ctl_abort_task(union ctl_io *io);
417static int ctl_abort_task_set(union ctl_io *io);
418static int ctl_i_t_nexus_reset(union ctl_io *io);
419static void ctl_run_task(union ctl_io *io);
420#ifdef CTL_IO_DELAY
421static void ctl_datamove_timer_wakeup(void *arg);
422static void ctl_done_timer_wakeup(void *arg);
423#endif /* CTL_IO_DELAY */
424
425static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
426static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
427static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
428static void ctl_datamove_remote_write(union ctl_io *io);
429static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
430static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
431static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
432static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
433				    ctl_ha_dt_cb callback);
434static void ctl_datamove_remote_read(union ctl_io *io);
435static void ctl_datamove_remote(union ctl_io *io);
436static int ctl_process_done(union ctl_io *io);
437static void ctl_lun_thread(void *arg);
438static void ctl_work_thread(void *arg);
439static void ctl_enqueue_incoming(union ctl_io *io);
440static void ctl_enqueue_rtr(union ctl_io *io);
441static void ctl_enqueue_done(union ctl_io *io);
442static void ctl_enqueue_isc(union ctl_io *io);
443static const struct ctl_cmd_entry *
444    ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
445static const struct ctl_cmd_entry *
446    ctl_validate_command(struct ctl_scsiio *ctsio);
447static int ctl_cmd_applicable(uint8_t lun_type,
448    const struct ctl_cmd_entry *entry);
449
450/*
451 * Load the serialization table.  This isn't very pretty, but is probably
452 * the easiest way to do it.
453 */
454#include "ctl_ser_table.c"
455
456/*
457 * We only need to define open, close and ioctl routines for this driver.
458 */
459static struct cdevsw ctl_cdevsw = {
460	.d_version =	D_VERSION,
461	.d_flags =	0,
462	.d_open =	ctl_open,
463	.d_close =	ctl_close,
464	.d_ioctl =	ctl_ioctl,
465	.d_name =	"ctl",
466};
467
468
469MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
470MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
471
472static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
473
474static moduledata_t ctl_moduledata = {
475	"ctl",
476	ctl_module_event_handler,
477	NULL
478};
479
480DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
481MODULE_VERSION(ctl, 1);
482
483static struct ctl_frontend ioctl_frontend =
484{
485	.name = "ioctl",
486};
487
488static void
489ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
490			    union ctl_ha_msg *msg_info)
491{
492	struct ctl_scsiio *ctsio;
493
494	if (msg_info->hdr.original_sc == NULL) {
495		printf("%s: original_sc == NULL!\n", __func__);
496		/* XXX KDM now what? */
497		return;
498	}
499
500	ctsio = &msg_info->hdr.original_sc->scsiio;
501	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
502	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
503	ctsio->io_hdr.status = msg_info->hdr.status;
504	ctsio->scsi_status = msg_info->scsi.scsi_status;
505	ctsio->sense_len = msg_info->scsi.sense_len;
506	ctsio->sense_residual = msg_info->scsi.sense_residual;
507	ctsio->residual = msg_info->scsi.residual;
508	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
509	       sizeof(ctsio->sense_data));
510	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
511	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
512	ctl_enqueue_isc((union ctl_io *)ctsio);
513}
514
515static void
516ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
517				union ctl_ha_msg *msg_info)
518{
519	struct ctl_scsiio *ctsio;
520
521	if (msg_info->hdr.serializing_sc == NULL) {
522		printf("%s: serializing_sc == NULL!\n", __func__);
523		/* XXX KDM now what? */
524		return;
525	}
526
527	ctsio = &msg_info->hdr.serializing_sc->scsiio;
528#if 0
529	/*
530	 * Attempt to catch the situation where an I/O has
531	 * been freed, and we're using it again.
532	 */
533	if (ctsio->io_hdr.io_type == 0xff) {
534		union ctl_io *tmp_io;
535		tmp_io = (union ctl_io *)ctsio;
536		printf("%s: %p use after free!\n", __func__,
537		       ctsio);
538		printf("%s: type %d msg %d cdb %x iptl: "
539		       "%d:%d:%d:%d tag 0x%04x "
540		       "flag %#x status %x\n",
541			__func__,
542			tmp_io->io_hdr.io_type,
543			tmp_io->io_hdr.msg_type,
544			tmp_io->scsiio.cdb[0],
545			tmp_io->io_hdr.nexus.initid.id,
546			tmp_io->io_hdr.nexus.targ_port,
547			tmp_io->io_hdr.nexus.targ_target.id,
548			tmp_io->io_hdr.nexus.targ_lun,
549			(tmp_io->io_hdr.io_type ==
550			CTL_IO_TASK) ?
551			tmp_io->taskio.tag_num :
552			tmp_io->scsiio.tag_num,
553		        tmp_io->io_hdr.flags,
554			tmp_io->io_hdr.status);
555	}
556#endif
557	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
558	ctl_enqueue_isc((union ctl_io *)ctsio);
559}
560
561/*
562 * ISC (Inter Shelf Communication) event handler.  Events from the HA
563 * subsystem come in here.
564 */
565static void
566ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
567{
568	struct ctl_softc *ctl_softc;
569	union ctl_io *io;
570	struct ctl_prio *presio;
571	ctl_ha_status isc_status;
572
573	ctl_softc = control_softc;
574	io = NULL;
575
576
577#if 0
578	printf("CTL: Isc Msg event %d\n", event);
579#endif
580	if (event == CTL_HA_EVT_MSG_RECV) {
581		union ctl_ha_msg msg_info;
582
583		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
584					     sizeof(msg_info), /*wait*/ 0);
585#if 0
586		printf("CTL: msg_type %d\n", msg_info.msg_type);
587#endif
588		if (isc_status != 0) {
589			printf("Error receiving message, status = %d\n",
590			       isc_status);
591			return;
592		}
593
594		switch (msg_info.hdr.msg_type) {
595		case CTL_MSG_SERIALIZE:
596#if 0
597			printf("Serialize\n");
598#endif
599			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
600			if (io == NULL) {
601				printf("ctl_isc_event_handler: can't allocate "
602				       "ctl_io!\n");
603				/* Bad Juju */
604				/* Need to set busy and send msg back */
605				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
606				msg_info.hdr.status = CTL_SCSI_ERROR;
607				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
608				msg_info.scsi.sense_len = 0;
609			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
610				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
611				}
612				goto bailout;
613			}
614			ctl_zero_io(io);
615			// populate ctsio from msg_info
616			io->io_hdr.io_type = CTL_IO_SCSI;
617			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
618			io->io_hdr.original_sc = msg_info.hdr.original_sc;
619#if 0
620			printf("pOrig %x\n", (int)msg_info.original_sc);
621#endif
622			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
623					    CTL_FLAG_IO_ACTIVE;
624			/*
625			 * If we're in serialization-only mode, we don't
626			 * want to go through full done processing.  Thus
627			 * the COPY flag.
628			 *
629			 * XXX KDM add another flag that is more specific.
630			 */
631			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
632				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
633			io->io_hdr.nexus = msg_info.hdr.nexus;
634#if 0
635			printf("targ %d, port %d, iid %d, lun %d\n",
636			       io->io_hdr.nexus.targ_target.id,
637			       io->io_hdr.nexus.targ_port,
638			       io->io_hdr.nexus.initid.id,
639			       io->io_hdr.nexus.targ_lun);
640#endif
641			io->scsiio.tag_num = msg_info.scsi.tag_num;
642			io->scsiio.tag_type = msg_info.scsi.tag_type;
643			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
644			       CTL_MAX_CDBLEN);
645			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
646				const struct ctl_cmd_entry *entry;
647
648				entry = ctl_get_cmd_entry(&io->scsiio);
649				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
650				io->io_hdr.flags |=
651					entry->flags & CTL_FLAG_DATA_MASK;
652			}
653			ctl_enqueue_isc(io);
654			break;
655
656		/* Performed on the Originating SC, XFER mode only */
657		case CTL_MSG_DATAMOVE: {
658			struct ctl_sg_entry *sgl;
659			int i, j;
660
661			io = msg_info.hdr.original_sc;
662			if (io == NULL) {
663				printf("%s: original_sc == NULL!\n", __func__);
664				/* XXX KDM do something here */
665				break;
666			}
667			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
668			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
669			/*
670			 * Keep track of this, we need to send it back over
671			 * when the datamove is complete.
672			 */
673			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
674
675			if (msg_info.dt.sg_sequence == 0) {
676				/*
677				 * XXX KDM we use the preallocated S/G list
678				 * here, but we'll need to change this to
679				 * dynamic allocation if we need larger S/G
680				 * lists.
681				 */
682				if (msg_info.dt.kern_sg_entries >
683				    sizeof(io->io_hdr.remote_sglist) /
684				    sizeof(io->io_hdr.remote_sglist[0])) {
685					printf("%s: number of S/G entries "
686					    "needed %u > allocated num %zd\n",
687					    __func__,
688					    msg_info.dt.kern_sg_entries,
689					    sizeof(io->io_hdr.remote_sglist)/
690					    sizeof(io->io_hdr.remote_sglist[0]));
691
692					/*
693					 * XXX KDM send a message back to
694					 * the other side to shut down the
695					 * DMA.  The error will come back
696					 * through via the normal channel.
697					 */
698					break;
699				}
700				sgl = io->io_hdr.remote_sglist;
701				memset(sgl, 0,
702				       sizeof(io->io_hdr.remote_sglist));
703
704				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
705
706				io->scsiio.kern_sg_entries =
707					msg_info.dt.kern_sg_entries;
708				io->scsiio.rem_sg_entries =
709					msg_info.dt.kern_sg_entries;
710				io->scsiio.kern_data_len =
711					msg_info.dt.kern_data_len;
712				io->scsiio.kern_total_len =
713					msg_info.dt.kern_total_len;
714				io->scsiio.kern_data_resid =
715					msg_info.dt.kern_data_resid;
716				io->scsiio.kern_rel_offset =
717					msg_info.dt.kern_rel_offset;
718				/*
719				 * Clear out per-DMA flags.
720				 */
721				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
722				/*
723				 * Add per-DMA flags that are set for this
724				 * particular DMA request.
725				 */
726				io->io_hdr.flags |= msg_info.dt.flags &
727						    CTL_FLAG_RDMA_MASK;
728			} else
729				sgl = (struct ctl_sg_entry *)
730					io->scsiio.kern_data_ptr;
731
732			for (i = msg_info.dt.sent_sg_entries, j = 0;
733			     i < (msg_info.dt.sent_sg_entries +
734			     msg_info.dt.cur_sg_entries); i++, j++) {
735				sgl[i].addr = msg_info.dt.sg_list[j].addr;
736				sgl[i].len = msg_info.dt.sg_list[j].len;
737
738#if 0
739				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
740				       __func__,
741				       msg_info.dt.sg_list[j].addr,
742				       msg_info.dt.sg_list[j].len,
743				       sgl[i].addr, sgl[i].len, j, i);
744#endif
745			}
746#if 0
747			memcpy(&sgl[msg_info.dt.sent_sg_entries],
748			       msg_info.dt.sg_list,
749			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
750#endif
751
752			/*
753			 * If this is the last piece of the I/O, we've got
754			 * the full S/G list.  Queue processing in the thread.
755			 * Otherwise wait for the next piece.
756			 */
757			if (msg_info.dt.sg_last != 0)
758				ctl_enqueue_isc(io);
759			break;
760		}
761		/* Performed on the Serializing (primary) SC, XFER mode only */
762		case CTL_MSG_DATAMOVE_DONE: {
763			if (msg_info.hdr.serializing_sc == NULL) {
764				printf("%s: serializing_sc == NULL!\n",
765				       __func__);
766				/* XXX KDM now what? */
767				break;
768			}
769			/*
770			 * We grab the sense information here in case
771			 * there was a failure, so we can return status
772			 * back to the initiator.
773			 */
774			io = msg_info.hdr.serializing_sc;
775			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
776			io->io_hdr.status = msg_info.hdr.status;
777			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
778			io->scsiio.sense_len = msg_info.scsi.sense_len;
779			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
780			io->io_hdr.port_status = msg_info.scsi.fetd_status;
781			io->scsiio.residual = msg_info.scsi.residual;
782			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
783			       sizeof(io->scsiio.sense_data));
784			ctl_enqueue_isc(io);
785			break;
786		}
787
788		/* Preformed on Originating SC, SER_ONLY mode */
789		case CTL_MSG_R2R:
790			io = msg_info.hdr.original_sc;
791			if (io == NULL) {
792				printf("%s: Major Bummer\n", __func__);
793				return;
794			} else {
795#if 0
796				printf("pOrig %x\n",(int) ctsio);
797#endif
798			}
799			io->io_hdr.msg_type = CTL_MSG_R2R;
800			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
801			ctl_enqueue_isc(io);
802			break;
803
804		/*
805		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
806		 * mode.
807		 * Performed on the Originating (i.e. secondary) SC in XFER
808		 * mode
809		 */
810		case CTL_MSG_FINISH_IO:
811			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
812				ctl_isc_handler_finish_xfer(ctl_softc,
813							    &msg_info);
814			else
815				ctl_isc_handler_finish_ser_only(ctl_softc,
816								&msg_info);
817			break;
818
819		/* Preformed on Originating SC */
820		case CTL_MSG_BAD_JUJU:
821			io = msg_info.hdr.original_sc;
822			if (io == NULL) {
823				printf("%s: Bad JUJU!, original_sc is NULL!\n",
824				       __func__);
825				break;
826			}
827			ctl_copy_sense_data(&msg_info, io);
828			/*
829			 * IO should have already been cleaned up on other
830			 * SC so clear this flag so we won't send a message
831			 * back to finish the IO there.
832			 */
833			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
834			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
835
836			/* io = msg_info.hdr.serializing_sc; */
837			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
838			ctl_enqueue_isc(io);
839			break;
840
841		/* Handle resets sent from the other side */
842		case CTL_MSG_MANAGE_TASKS: {
843			struct ctl_taskio *taskio;
844			taskio = (struct ctl_taskio *)ctl_alloc_io(
845				(void *)ctl_softc->othersc_pool);
846			if (taskio == NULL) {
847				printf("ctl_isc_event_handler: can't allocate "
848				       "ctl_io!\n");
849				/* Bad Juju */
850				/* should I just call the proper reset func
851				   here??? */
852				goto bailout;
853			}
854			ctl_zero_io((union ctl_io *)taskio);
855			taskio->io_hdr.io_type = CTL_IO_TASK;
856			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
857			taskio->io_hdr.nexus = msg_info.hdr.nexus;
858			taskio->task_action = msg_info.task.task_action;
859			taskio->tag_num = msg_info.task.tag_num;
860			taskio->tag_type = msg_info.task.tag_type;
861#ifdef CTL_TIME_IO
862			taskio->io_hdr.start_time = time_uptime;
863			getbintime(&taskio->io_hdr.start_bt);
864#if 0
865			cs_prof_gettime(&taskio->io_hdr.start_ticks);
866#endif
867#endif /* CTL_TIME_IO */
868			ctl_run_task((union ctl_io *)taskio);
869			break;
870		}
871		/* Persistent Reserve action which needs attention */
872		case CTL_MSG_PERS_ACTION:
873			presio = (struct ctl_prio *)ctl_alloc_io(
874				(void *)ctl_softc->othersc_pool);
875			if (presio == NULL) {
876				printf("ctl_isc_event_handler: can't allocate "
877				       "ctl_io!\n");
878				/* Bad Juju */
879				/* Need to set busy and send msg back */
880				goto bailout;
881			}
882			ctl_zero_io((union ctl_io *)presio);
883			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
884			presio->pr_msg = msg_info.pr;
885			ctl_enqueue_isc((union ctl_io *)presio);
886			break;
887		case CTL_MSG_SYNC_FE:
888			rcv_sync_msg = 1;
889			break;
890		case CTL_MSG_APS_LOCK: {
891			// It's quicker to execute this then to
892			// queue it.
893			struct ctl_lun *lun;
894			struct ctl_page_index *page_index;
895			struct copan_aps_subpage *current_sp;
896			uint32_t targ_lun;
897
898			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
899			lun = ctl_softc->ctl_luns[targ_lun];
900			mtx_lock(&lun->lun_lock);
901			page_index = &lun->mode_pages.index[index_to_aps_page];
902			current_sp = (struct copan_aps_subpage *)
903				     (page_index->page_data +
904				     (page_index->page_len * CTL_PAGE_CURRENT));
905
906			current_sp->lock_active = msg_info.aps.lock_flag;
907			mtx_unlock(&lun->lun_lock);
908		        break;
909		}
910		default:
911		        printf("How did I get here?\n");
912		}
913	} else if (event == CTL_HA_EVT_MSG_SENT) {
914		if (param != CTL_HA_STATUS_SUCCESS) {
915			printf("Bad status from ctl_ha_msg_send status %d\n",
916			       param);
917		}
918		return;
919	} else if (event == CTL_HA_EVT_DISCONNECT) {
920		printf("CTL: Got a disconnect from Isc\n");
921		return;
922	} else {
923		printf("ctl_isc_event_handler: Unknown event %d\n", event);
924		return;
925	}
926
927bailout:
928	return;
929}
930
931static void
932ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
933{
934	struct scsi_sense_data *sense;
935
936	sense = &dest->scsiio.sense_data;
937	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
938	dest->scsiio.scsi_status = src->scsi.scsi_status;
939	dest->scsiio.sense_len = src->scsi.sense_len;
940	dest->io_hdr.status = src->hdr.status;
941}
942
943static int
944ctl_init(void)
945{
946	struct ctl_softc *softc;
947	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
948	struct ctl_port *port;
949        uint8_t sc_id =0;
950	int i, error, retval;
951	//int isc_retval;
952
953	retval = 0;
954	ctl_pause_rtr = 0;
955        rcv_sync_msg = 0;
956
957	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
958			       M_WAITOK | M_ZERO);
959	softc = control_softc;
960
961	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
962			      "cam/ctl");
963
964	softc->dev->si_drv1 = softc;
965
966	/*
967	 * By default, return a "bad LUN" peripheral qualifier for unknown
968	 * LUNs.  The user can override this default using the tunable or
969	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
970	 */
971	softc->inquiry_pq_no_lun = 1;
972	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
973			  &softc->inquiry_pq_no_lun);
974	sysctl_ctx_init(&softc->sysctl_ctx);
975	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
976		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
977		CTLFLAG_RD, 0, "CAM Target Layer");
978
979	if (softc->sysctl_tree == NULL) {
980		printf("%s: unable to allocate sysctl tree\n", __func__);
981		destroy_dev(softc->dev);
982		free(control_softc, M_DEVBUF);
983		control_softc = NULL;
984		return (ENOMEM);
985	}
986
987	SYSCTL_ADD_INT(&softc->sysctl_ctx,
988		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
989		       "inquiry_pq_no_lun", CTLFLAG_RW,
990		       &softc->inquiry_pq_no_lun, 0,
991		       "Report no lun possible for invalid LUNs");
992
993	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
994	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
995	softc->open_count = 0;
996
997	/*
998	 * Default to actually sending a SYNCHRONIZE CACHE command down to
999	 * the drive.
1000	 */
1001	softc->flags = CTL_FLAG_REAL_SYNC;
1002
1003	/*
1004	 * In Copan's HA scheme, the "master" and "slave" roles are
1005	 * figured out through the slot the controller is in.  Although it
1006	 * is an active/active system, someone has to be in charge.
1007 	 */
1008#ifdef NEEDTOPORT
1009        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1010#endif
1011
1012        if (sc_id == 0) {
1013		softc->flags |= CTL_FLAG_MASTER_SHELF;
1014		persis_offset = 0;
1015	} else
1016		persis_offset = CTL_MAX_INITIATORS;
1017
1018	/*
1019	 * XXX KDM need to figure out where we want to get our target ID
1020	 * and WWID.  Is it different on each port?
1021	 */
1022	softc->target.id = 0;
1023	softc->target.wwid[0] = 0x12345678;
1024	softc->target.wwid[1] = 0x87654321;
1025	STAILQ_INIT(&softc->lun_list);
1026	STAILQ_INIT(&softc->pending_lun_queue);
1027	STAILQ_INIT(&softc->fe_list);
1028	STAILQ_INIT(&softc->port_list);
1029	STAILQ_INIT(&softc->be_list);
1030	STAILQ_INIT(&softc->io_pools);
1031	ctl_tpc_init(softc);
1032
1033	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1034			    &internal_pool)!= 0){
1035		printf("ctl: can't allocate %d entry internal pool, "
1036		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1037		return (ENOMEM);
1038	}
1039
1040	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1041			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1042		printf("ctl: can't allocate %d entry emergency pool, "
1043		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1044		ctl_pool_free(internal_pool);
1045		return (ENOMEM);
1046	}
1047
1048	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1049	                    &other_pool) != 0)
1050	{
1051		printf("ctl: can't allocate %d entry other SC pool, "
1052		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1053		ctl_pool_free(internal_pool);
1054		ctl_pool_free(emergency_pool);
1055		return (ENOMEM);
1056	}
1057
1058	softc->internal_pool = internal_pool;
1059	softc->emergency_pool = emergency_pool;
1060	softc->othersc_pool = other_pool;
1061
1062	if (worker_threads <= 0)
1063		worker_threads = max(1, mp_ncpus / 4);
1064	if (worker_threads > CTL_MAX_THREADS)
1065		worker_threads = CTL_MAX_THREADS;
1066
1067	for (i = 0; i < worker_threads; i++) {
1068		struct ctl_thread *thr = &softc->threads[i];
1069
1070		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1071		thr->ctl_softc = softc;
1072		STAILQ_INIT(&thr->incoming_queue);
1073		STAILQ_INIT(&thr->rtr_queue);
1074		STAILQ_INIT(&thr->done_queue);
1075		STAILQ_INIT(&thr->isc_queue);
1076
1077		error = kproc_kthread_add(ctl_work_thread, thr,
1078		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1079		if (error != 0) {
1080			printf("error creating CTL work thread!\n");
1081			ctl_pool_free(internal_pool);
1082			ctl_pool_free(emergency_pool);
1083			ctl_pool_free(other_pool);
1084			return (error);
1085		}
1086	}
1087	error = kproc_kthread_add(ctl_lun_thread, softc,
1088	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1089	if (error != 0) {
1090		printf("error creating CTL lun thread!\n");
1091		ctl_pool_free(internal_pool);
1092		ctl_pool_free(emergency_pool);
1093		ctl_pool_free(other_pool);
1094		return (error);
1095	}
1096	if (bootverbose)
1097		printf("ctl: CAM Target Layer loaded\n");
1098
1099	/*
1100	 * Initialize the ioctl front end.
1101	 */
1102	ctl_frontend_register(&ioctl_frontend);
1103	port = &softc->ioctl_info.port;
1104	port->frontend = &ioctl_frontend;
1105	sprintf(softc->ioctl_info.port_name, "ioctl");
1106	port->port_type = CTL_PORT_IOCTL;
1107	port->num_requested_ctl_io = 100;
1108	port->port_name = softc->ioctl_info.port_name;
1109	port->port_online = ctl_ioctl_online;
1110	port->port_offline = ctl_ioctl_offline;
1111	port->onoff_arg = &softc->ioctl_info;
1112	port->lun_enable = ctl_ioctl_lun_enable;
1113	port->lun_disable = ctl_ioctl_lun_disable;
1114	port->targ_lun_arg = &softc->ioctl_info;
1115	port->fe_datamove = ctl_ioctl_datamove;
1116	port->fe_done = ctl_ioctl_done;
1117	port->max_targets = 15;
1118	port->max_target_id = 15;
1119
1120	if (ctl_port_register(&softc->ioctl_info.port,
1121	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1122		printf("ctl: ioctl front end registration failed, will "
1123		       "continue anyway\n");
1124	}
1125
1126#ifdef CTL_IO_DELAY
1127	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1128		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1129		       sizeof(struct callout), CTL_TIMER_BYTES);
1130		return (EINVAL);
1131	}
1132#endif /* CTL_IO_DELAY */
1133
1134	return (0);
1135}
1136
1137void
1138ctl_shutdown(void)
1139{
1140	struct ctl_softc *softc;
1141	struct ctl_lun *lun, *next_lun;
1142	struct ctl_io_pool *pool;
1143
1144	softc = (struct ctl_softc *)control_softc;
1145
1146	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1147		printf("ctl: ioctl front end deregistration failed\n");
1148
1149	mtx_lock(&softc->ctl_lock);
1150
1151	/*
1152	 * Free up each LUN.
1153	 */
1154	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1155		next_lun = STAILQ_NEXT(lun, links);
1156		ctl_free_lun(lun);
1157	}
1158
1159	mtx_unlock(&softc->ctl_lock);
1160
1161	ctl_frontend_deregister(&ioctl_frontend);
1162
1163	/*
1164	 * This will rip the rug out from under any FETDs or anyone else
1165	 * that has a pool allocated.  Since we increment our module
1166	 * refcount any time someone outside the main CTL module allocates
1167	 * a pool, we shouldn't have any problems here.  The user won't be
1168	 * able to unload the CTL module until client modules have
1169	 * successfully unloaded.
1170	 */
1171	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1172		ctl_pool_free(pool);
1173
1174#if 0
1175	ctl_shutdown_thread(softc->work_thread);
1176	mtx_destroy(&softc->queue_lock);
1177#endif
1178
1179	ctl_tpc_shutdown(softc);
1180	mtx_destroy(&softc->pool_lock);
1181	mtx_destroy(&softc->ctl_lock);
1182
1183	destroy_dev(softc->dev);
1184
1185	sysctl_ctx_free(&softc->sysctl_ctx);
1186
1187	free(control_softc, M_DEVBUF);
1188	control_softc = NULL;
1189
1190	if (bootverbose)
1191		printf("ctl: CAM Target Layer unloaded\n");
1192}
1193
1194static int
1195ctl_module_event_handler(module_t mod, int what, void *arg)
1196{
1197
1198	switch (what) {
1199	case MOD_LOAD:
1200		return (ctl_init());
1201	case MOD_UNLOAD:
1202		return (EBUSY);
1203	default:
1204		return (EOPNOTSUPP);
1205	}
1206}
1207
1208/*
1209 * XXX KDM should we do some access checks here?  Bump a reference count to
1210 * prevent a CTL module from being unloaded while someone has it open?
1211 */
1212static int
1213ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1214{
1215	return (0);
1216}
1217
1218static int
1219ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1220{
1221	return (0);
1222}
1223
1224int
1225ctl_port_enable(ctl_port_type port_type)
1226{
1227	struct ctl_softc *softc;
1228	struct ctl_port *port;
1229
1230	if (ctl_is_single == 0) {
1231		union ctl_ha_msg msg_info;
1232		int isc_retval;
1233
1234#if 0
1235		printf("%s: HA mode, synchronizing frontend enable\n",
1236		        __func__);
1237#endif
1238		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1239	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1240		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1241			printf("Sync msg send error retval %d\n", isc_retval);
1242		}
1243		if (!rcv_sync_msg) {
1244			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1245			        sizeof(msg_info), 1);
1246		}
1247#if 0
1248        	printf("CTL:Frontend Enable\n");
1249	} else {
1250		printf("%s: single mode, skipping frontend synchronization\n",
1251		        __func__);
1252#endif
1253	}
1254
1255	softc = control_softc;
1256
1257	STAILQ_FOREACH(port, &softc->port_list, links) {
1258		if (port_type & port->port_type)
1259		{
1260#if 0
1261			printf("port %d\n", port->targ_port);
1262#endif
1263			ctl_port_online(port);
1264		}
1265	}
1266
1267	return (0);
1268}
1269
1270int
1271ctl_port_disable(ctl_port_type port_type)
1272{
1273	struct ctl_softc *softc;
1274	struct ctl_port *port;
1275
1276	softc = control_softc;
1277
1278	STAILQ_FOREACH(port, &softc->port_list, links) {
1279		if (port_type & port->port_type)
1280			ctl_port_offline(port);
1281	}
1282
1283	return (0);
1284}
1285
1286/*
1287 * Returns 0 for success, 1 for failure.
1288 * Currently the only failure mode is if there aren't enough entries
1289 * allocated.  So, in case of a failure, look at num_entries_dropped,
1290 * reallocate and try again.
1291 */
1292int
1293ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1294	      int *num_entries_filled, int *num_entries_dropped,
1295	      ctl_port_type port_type, int no_virtual)
1296{
1297	struct ctl_softc *softc;
1298	struct ctl_port *port;
1299	int entries_dropped, entries_filled;
1300	int retval;
1301	int i;
1302
1303	softc = control_softc;
1304
1305	retval = 0;
1306	entries_filled = 0;
1307	entries_dropped = 0;
1308
1309	i = 0;
1310	mtx_lock(&softc->ctl_lock);
1311	STAILQ_FOREACH(port, &softc->port_list, links) {
1312		struct ctl_port_entry *entry;
1313
1314		if ((port->port_type & port_type) == 0)
1315			continue;
1316
1317		if ((no_virtual != 0)
1318		 && (port->virtual_port != 0))
1319			continue;
1320
1321		if (entries_filled >= num_entries_alloced) {
1322			entries_dropped++;
1323			continue;
1324		}
1325		entry = &entries[i];
1326
1327		entry->port_type = port->port_type;
1328		strlcpy(entry->port_name, port->port_name,
1329			sizeof(entry->port_name));
1330		entry->physical_port = port->physical_port;
1331		entry->virtual_port = port->virtual_port;
1332		entry->wwnn = port->wwnn;
1333		entry->wwpn = port->wwpn;
1334
1335		i++;
1336		entries_filled++;
1337	}
1338
1339	mtx_unlock(&softc->ctl_lock);
1340
1341	if (entries_dropped > 0)
1342		retval = 1;
1343
1344	*num_entries_dropped = entries_dropped;
1345	*num_entries_filled = entries_filled;
1346
1347	return (retval);
1348}
1349
1350static void
1351ctl_ioctl_online(void *arg)
1352{
1353	struct ctl_ioctl_info *ioctl_info;
1354
1355	ioctl_info = (struct ctl_ioctl_info *)arg;
1356
1357	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1358}
1359
1360static void
1361ctl_ioctl_offline(void *arg)
1362{
1363	struct ctl_ioctl_info *ioctl_info;
1364
1365	ioctl_info = (struct ctl_ioctl_info *)arg;
1366
1367	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1368}
1369
1370/*
1371 * Remove an initiator by port number and initiator ID.
1372 * Returns 0 for success, -1 for failure.
1373 */
1374int
1375ctl_remove_initiator(struct ctl_port *port, int iid)
1376{
1377	struct ctl_softc *softc = control_softc;
1378
1379	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1380
1381	if (iid > CTL_MAX_INIT_PER_PORT) {
1382		printf("%s: initiator ID %u > maximun %u!\n",
1383		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1384		return (-1);
1385	}
1386
1387	mtx_lock(&softc->ctl_lock);
1388	port->wwpn_iid[iid].in_use--;
1389	port->wwpn_iid[iid].last_use = time_uptime;
1390	mtx_unlock(&softc->ctl_lock);
1391
1392	return (0);
1393}
1394
1395/*
1396 * Add an initiator to the initiator map.
1397 * Returns iid for success, < 0 for failure.
1398 */
1399int
1400ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1401{
1402	struct ctl_softc *softc = control_softc;
1403	time_t best_time;
1404	int i, best;
1405
1406	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1407
1408	if (iid >= CTL_MAX_INIT_PER_PORT) {
1409		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1410		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1411		free(name, M_CTL);
1412		return (-1);
1413	}
1414
1415	mtx_lock(&softc->ctl_lock);
1416
1417	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1418		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1419			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1420				iid = i;
1421				break;
1422			}
1423			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1424			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1425				iid = i;
1426				break;
1427			}
1428		}
1429	}
1430
1431	if (iid < 0) {
1432		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1433			if (port->wwpn_iid[i].in_use == 0 &&
1434			    port->wwpn_iid[i].wwpn == 0 &&
1435			    port->wwpn_iid[i].name == NULL) {
1436				iid = i;
1437				break;
1438			}
1439		}
1440	}
1441
1442	if (iid < 0) {
1443		best = -1;
1444		best_time = INT32_MAX;
1445		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1446			if (port->wwpn_iid[i].in_use == 0) {
1447				if (port->wwpn_iid[i].last_use < best_time) {
1448					best = i;
1449					best_time = port->wwpn_iid[i].last_use;
1450				}
1451			}
1452		}
1453		iid = best;
1454	}
1455
1456	if (iid < 0) {
1457		mtx_unlock(&softc->ctl_lock);
1458		free(name, M_CTL);
1459		return (-2);
1460	}
1461
1462	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1463		/*
1464		 * This is not an error yet.
1465		 */
1466		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1467#if 0
1468			printf("%s: port %d iid %u WWPN %#jx arrived"
1469			    " again\n", __func__, port->targ_port,
1470			    iid, (uintmax_t)wwpn);
1471#endif
1472			goto take;
1473		}
1474		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1475		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1476#if 0
1477			printf("%s: port %d iid %u name '%s' arrived"
1478			    " again\n", __func__, port->targ_port,
1479			    iid, name);
1480#endif
1481			goto take;
1482		}
1483
1484		/*
1485		 * This is an error, but what do we do about it?  The
1486		 * driver is telling us we have a new WWPN for this
1487		 * initiator ID, so we pretty much need to use it.
1488		 */
1489		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1490		    " but WWPN %#jx '%s' is still at that address\n",
1491		    __func__, port->targ_port, iid, wwpn, name,
1492		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1493		    port->wwpn_iid[iid].name);
1494
1495		/*
1496		 * XXX KDM clear have_ca and ua_pending on each LUN for
1497		 * this initiator.
1498		 */
1499	}
1500take:
1501	free(port->wwpn_iid[iid].name, M_CTL);
1502	port->wwpn_iid[iid].name = name;
1503	port->wwpn_iid[iid].wwpn = wwpn;
1504	port->wwpn_iid[iid].in_use++;
1505	mtx_unlock(&softc->ctl_lock);
1506
1507	return (iid);
1508}
1509
1510static int
1511ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1512{
1513	int len;
1514
1515	switch (port->port_type) {
1516	case CTL_PORT_FC:
1517	{
1518		struct scsi_transportid_fcp *id =
1519		    (struct scsi_transportid_fcp *)buf;
1520		if (port->wwpn_iid[iid].wwpn == 0)
1521			return (0);
1522		memset(id, 0, sizeof(*id));
1523		id->format_protocol = SCSI_PROTO_FC;
1524		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1525		return (sizeof(*id));
1526	}
1527	case CTL_PORT_ISCSI:
1528	{
1529		struct scsi_transportid_iscsi_port *id =
1530		    (struct scsi_transportid_iscsi_port *)buf;
1531		if (port->wwpn_iid[iid].name == NULL)
1532			return (0);
1533		memset(id, 0, 256);
1534		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1535		    SCSI_PROTO_ISCSI;
1536		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1537		len = roundup2(min(len, 252), 4);
1538		scsi_ulto2b(len, id->additional_length);
1539		return (sizeof(*id) + len);
1540	}
1541	case CTL_PORT_SAS:
1542	{
1543		struct scsi_transportid_sas *id =
1544		    (struct scsi_transportid_sas *)buf;
1545		if (port->wwpn_iid[iid].wwpn == 0)
1546			return (0);
1547		memset(id, 0, sizeof(*id));
1548		id->format_protocol = SCSI_PROTO_SAS;
1549		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1550		return (sizeof(*id));
1551	}
1552	default:
1553	{
1554		struct scsi_transportid_spi *id =
1555		    (struct scsi_transportid_spi *)buf;
1556		memset(id, 0, sizeof(*id));
1557		id->format_protocol = SCSI_PROTO_SPI;
1558		scsi_ulto2b(iid, id->scsi_addr);
1559		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1560		return (sizeof(*id));
1561	}
1562	}
1563}
1564
1565static int
1566ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1567{
1568	return (0);
1569}
1570
1571static int
1572ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1573{
1574	return (0);
1575}
1576
1577/*
1578 * Data movement routine for the CTL ioctl frontend port.
1579 */
1580static int
1581ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1582{
1583	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1584	struct ctl_sg_entry ext_entry, kern_entry;
1585	int ext_sglen, ext_sg_entries, kern_sg_entries;
1586	int ext_sg_start, ext_offset;
1587	int len_to_copy, len_copied;
1588	int kern_watermark, ext_watermark;
1589	int ext_sglist_malloced;
1590	int i, j;
1591
1592	ext_sglist_malloced = 0;
1593	ext_sg_start = 0;
1594	ext_offset = 0;
1595
1596	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1597
1598	/*
1599	 * If this flag is set, fake the data transfer.
1600	 */
1601	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1602		ctsio->ext_data_filled = ctsio->ext_data_len;
1603		goto bailout;
1604	}
1605
1606	/*
1607	 * To simplify things here, if we have a single buffer, stick it in
1608	 * a S/G entry and just make it a single entry S/G list.
1609	 */
1610	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1611		int len_seen;
1612
1613		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1614
1615		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1616							   M_WAITOK);
1617		ext_sglist_malloced = 1;
1618		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1619				   ext_sglen) != 0) {
1620			ctl_set_internal_failure(ctsio,
1621						 /*sks_valid*/ 0,
1622						 /*retry_count*/ 0);
1623			goto bailout;
1624		}
1625		ext_sg_entries = ctsio->ext_sg_entries;
1626		len_seen = 0;
1627		for (i = 0; i < ext_sg_entries; i++) {
1628			if ((len_seen + ext_sglist[i].len) >=
1629			     ctsio->ext_data_filled) {
1630				ext_sg_start = i;
1631				ext_offset = ctsio->ext_data_filled - len_seen;
1632				break;
1633			}
1634			len_seen += ext_sglist[i].len;
1635		}
1636	} else {
1637		ext_sglist = &ext_entry;
1638		ext_sglist->addr = ctsio->ext_data_ptr;
1639		ext_sglist->len = ctsio->ext_data_len;
1640		ext_sg_entries = 1;
1641		ext_sg_start = 0;
1642		ext_offset = ctsio->ext_data_filled;
1643	}
1644
1645	if (ctsio->kern_sg_entries > 0) {
1646		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1647		kern_sg_entries = ctsio->kern_sg_entries;
1648	} else {
1649		kern_sglist = &kern_entry;
1650		kern_sglist->addr = ctsio->kern_data_ptr;
1651		kern_sglist->len = ctsio->kern_data_len;
1652		kern_sg_entries = 1;
1653	}
1654
1655
1656	kern_watermark = 0;
1657	ext_watermark = ext_offset;
1658	len_copied = 0;
1659	for (i = ext_sg_start, j = 0;
1660	     i < ext_sg_entries && j < kern_sg_entries;) {
1661		uint8_t *ext_ptr, *kern_ptr;
1662
1663		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1664				      kern_sglist[j].len - kern_watermark);
1665
1666		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1667		ext_ptr = ext_ptr + ext_watermark;
1668		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1669			/*
1670			 * XXX KDM fix this!
1671			 */
1672			panic("need to implement bus address support");
1673#if 0
1674			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1675#endif
1676		} else
1677			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1678		kern_ptr = kern_ptr + kern_watermark;
1679
1680		kern_watermark += len_to_copy;
1681		ext_watermark += len_to_copy;
1682
1683		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1684		     CTL_FLAG_DATA_IN) {
1685			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1686					 "bytes to user\n", len_to_copy));
1687			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1688					 "to %p\n", kern_ptr, ext_ptr));
1689			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1690				ctl_set_internal_failure(ctsio,
1691							 /*sks_valid*/ 0,
1692							 /*retry_count*/ 0);
1693				goto bailout;
1694			}
1695		} else {
1696			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1697					 "bytes from user\n", len_to_copy));
1698			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1699					 "to %p\n", ext_ptr, kern_ptr));
1700			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1701				ctl_set_internal_failure(ctsio,
1702							 /*sks_valid*/ 0,
1703							 /*retry_count*/0);
1704				goto bailout;
1705			}
1706		}
1707
1708		len_copied += len_to_copy;
1709
1710		if (ext_sglist[i].len == ext_watermark) {
1711			i++;
1712			ext_watermark = 0;
1713		}
1714
1715		if (kern_sglist[j].len == kern_watermark) {
1716			j++;
1717			kern_watermark = 0;
1718		}
1719	}
1720
1721	ctsio->ext_data_filled += len_copied;
1722
1723	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1724			 "kern_sg_entries: %d\n", ext_sg_entries,
1725			 kern_sg_entries));
1726	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1727			 "kern_data_len = %d\n", ctsio->ext_data_len,
1728			 ctsio->kern_data_len));
1729
1730
1731	/* XXX KDM set residual?? */
1732bailout:
1733
1734	if (ext_sglist_malloced != 0)
1735		free(ext_sglist, M_CTL);
1736
1737	return (CTL_RETVAL_COMPLETE);
1738}
1739
1740/*
1741 * Serialize a command that went down the "wrong" side, and so was sent to
1742 * this controller for execution.  The logic is a little different than the
1743 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1744 * sent back to the other side, but in the success case, we execute the
1745 * command on this side (XFER mode) or tell the other side to execute it
1746 * (SER_ONLY mode).
1747 */
1748static int
1749ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1750{
1751	struct ctl_softc *ctl_softc;
1752	union ctl_ha_msg msg_info;
1753	struct ctl_lun *lun;
1754	int retval = 0;
1755	uint32_t targ_lun;
1756
1757	ctl_softc = control_softc;
1758
1759	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1760	lun = ctl_softc->ctl_luns[targ_lun];
1761	if (lun==NULL)
1762	{
1763		/*
1764		 * Why isn't LUN defined? The other side wouldn't
1765		 * send a cmd if the LUN is undefined.
1766		 */
1767		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1768
1769		/* "Logical unit not supported" */
1770		ctl_set_sense_data(&msg_info.scsi.sense_data,
1771				   lun,
1772				   /*sense_format*/SSD_TYPE_NONE,
1773				   /*current_error*/ 1,
1774				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1775				   /*asc*/ 0x25,
1776				   /*ascq*/ 0x00,
1777				   SSD_ELEM_NONE);
1778
1779		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1780		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1781		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1782		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1783		msg_info.hdr.serializing_sc = NULL;
1784		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1785	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1786				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1787		}
1788		return(1);
1789
1790	}
1791
1792	mtx_lock(&lun->lun_lock);
1793    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1794
1795	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1796		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1797		 ooa_links))) {
1798	case CTL_ACTION_BLOCK:
1799		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1800		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1801				  blocked_links);
1802		break;
1803	case CTL_ACTION_PASS:
1804	case CTL_ACTION_SKIP:
1805		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1806			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1807			ctl_enqueue_rtr((union ctl_io *)ctsio);
1808		} else {
1809
1810			/* send msg back to other side */
1811			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1812			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1813			msg_info.hdr.msg_type = CTL_MSG_R2R;
1814#if 0
1815			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1816#endif
1817		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1818			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1819			}
1820		}
1821		break;
1822	case CTL_ACTION_OVERLAP:
1823		/* OVERLAPPED COMMANDS ATTEMPTED */
1824		ctl_set_sense_data(&msg_info.scsi.sense_data,
1825				   lun,
1826				   /*sense_format*/SSD_TYPE_NONE,
1827				   /*current_error*/ 1,
1828				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1829				   /*asc*/ 0x4E,
1830				   /*ascq*/ 0x00,
1831				   SSD_ELEM_NONE);
1832
1833		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1834		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1835		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1836		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1837		msg_info.hdr.serializing_sc = NULL;
1838		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1839#if 0
1840		printf("BAD JUJU:Major Bummer Overlap\n");
1841#endif
1842		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1843		retval = 1;
1844		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1845		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1846		}
1847		break;
1848	case CTL_ACTION_OVERLAP_TAG:
1849		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1850		ctl_set_sense_data(&msg_info.scsi.sense_data,
1851				   lun,
1852				   /*sense_format*/SSD_TYPE_NONE,
1853				   /*current_error*/ 1,
1854				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1855				   /*asc*/ 0x4D,
1856				   /*ascq*/ ctsio->tag_num & 0xff,
1857				   SSD_ELEM_NONE);
1858
1859		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1860		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1861		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1862		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1863		msg_info.hdr.serializing_sc = NULL;
1864		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1865#if 0
1866		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1867#endif
1868		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1869		retval = 1;
1870		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1871		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1872		}
1873		break;
1874	case CTL_ACTION_ERROR:
1875	default:
1876		/* "Internal target failure" */
1877		ctl_set_sense_data(&msg_info.scsi.sense_data,
1878				   lun,
1879				   /*sense_format*/SSD_TYPE_NONE,
1880				   /*current_error*/ 1,
1881				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1882				   /*asc*/ 0x44,
1883				   /*ascq*/ 0x00,
1884				   SSD_ELEM_NONE);
1885
1886		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1887		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1888		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1889		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1890		msg_info.hdr.serializing_sc = NULL;
1891		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1892#if 0
1893		printf("BAD JUJU:Major Bummer HW Error\n");
1894#endif
1895		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1896		retval = 1;
1897		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1898		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1899		}
1900		break;
1901	}
1902	mtx_unlock(&lun->lun_lock);
1903	return (retval);
1904}
1905
1906static int
1907ctl_ioctl_submit_wait(union ctl_io *io)
1908{
1909	struct ctl_fe_ioctl_params params;
1910	ctl_fe_ioctl_state last_state;
1911	int done, retval;
1912
1913	retval = 0;
1914
1915	bzero(&params, sizeof(params));
1916
1917	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1918	cv_init(&params.sem, "ctlioccv");
1919	params.state = CTL_IOCTL_INPROG;
1920	last_state = params.state;
1921
1922	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1923
1924	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1925
1926	/* This shouldn't happen */
1927	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1928		return (retval);
1929
1930	done = 0;
1931
1932	do {
1933		mtx_lock(&params.ioctl_mtx);
1934		/*
1935		 * Check the state here, and don't sleep if the state has
1936		 * already changed (i.e. wakeup has already occured, but we
1937		 * weren't waiting yet).
1938		 */
1939		if (params.state == last_state) {
1940			/* XXX KDM cv_wait_sig instead? */
1941			cv_wait(&params.sem, &params.ioctl_mtx);
1942		}
1943		last_state = params.state;
1944
1945		switch (params.state) {
1946		case CTL_IOCTL_INPROG:
1947			/* Why did we wake up? */
1948			/* XXX KDM error here? */
1949			mtx_unlock(&params.ioctl_mtx);
1950			break;
1951		case CTL_IOCTL_DATAMOVE:
1952			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1953
1954			/*
1955			 * change last_state back to INPROG to avoid
1956			 * deadlock on subsequent data moves.
1957			 */
1958			params.state = last_state = CTL_IOCTL_INPROG;
1959
1960			mtx_unlock(&params.ioctl_mtx);
1961			ctl_ioctl_do_datamove(&io->scsiio);
1962			/*
1963			 * Note that in some cases, most notably writes,
1964			 * this will queue the I/O and call us back later.
1965			 * In other cases, generally reads, this routine
1966			 * will immediately call back and wake us up,
1967			 * probably using our own context.
1968			 */
1969			io->scsiio.be_move_done(io);
1970			break;
1971		case CTL_IOCTL_DONE:
1972			mtx_unlock(&params.ioctl_mtx);
1973			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1974			done = 1;
1975			break;
1976		default:
1977			mtx_unlock(&params.ioctl_mtx);
1978			/* XXX KDM error here? */
1979			break;
1980		}
1981	} while (done == 0);
1982
1983	mtx_destroy(&params.ioctl_mtx);
1984	cv_destroy(&params.sem);
1985
1986	return (CTL_RETVAL_COMPLETE);
1987}
1988
1989static void
1990ctl_ioctl_datamove(union ctl_io *io)
1991{
1992	struct ctl_fe_ioctl_params *params;
1993
1994	params = (struct ctl_fe_ioctl_params *)
1995		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1996
1997	mtx_lock(&params->ioctl_mtx);
1998	params->state = CTL_IOCTL_DATAMOVE;
1999	cv_broadcast(&params->sem);
2000	mtx_unlock(&params->ioctl_mtx);
2001}
2002
2003static void
2004ctl_ioctl_done(union ctl_io *io)
2005{
2006	struct ctl_fe_ioctl_params *params;
2007
2008	params = (struct ctl_fe_ioctl_params *)
2009		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2010
2011	mtx_lock(&params->ioctl_mtx);
2012	params->state = CTL_IOCTL_DONE;
2013	cv_broadcast(&params->sem);
2014	mtx_unlock(&params->ioctl_mtx);
2015}
2016
2017static void
2018ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2019{
2020	struct ctl_fe_ioctl_startstop_info *sd_info;
2021
2022	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2023
2024	sd_info->hs_info.status = metatask->status;
2025	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2026	sd_info->hs_info.luns_complete =
2027		metatask->taskinfo.startstop.luns_complete;
2028	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2029
2030	cv_broadcast(&sd_info->sem);
2031}
2032
2033static void
2034ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2035{
2036	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2037
2038	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2039
2040	mtx_lock(fe_bbr_info->lock);
2041	fe_bbr_info->bbr_info->status = metatask->status;
2042	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2043	fe_bbr_info->wakeup_done = 1;
2044	mtx_unlock(fe_bbr_info->lock);
2045
2046	cv_broadcast(&fe_bbr_info->sem);
2047}
2048
2049/*
2050 * Returns 0 for success, errno for failure.
2051 */
2052static int
2053ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2054		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2055{
2056	union ctl_io *io;
2057	int retval;
2058
2059	retval = 0;
2060
2061	mtx_lock(&lun->lun_lock);
2062	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2063	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2064	     ooa_links)) {
2065		struct ctl_ooa_entry *entry;
2066
2067		/*
2068		 * If we've got more than we can fit, just count the
2069		 * remaining entries.
2070		 */
2071		if (*cur_fill_num >= ooa_hdr->alloc_num)
2072			continue;
2073
2074		entry = &kern_entries[*cur_fill_num];
2075
2076		entry->tag_num = io->scsiio.tag_num;
2077		entry->lun_num = lun->lun;
2078#ifdef CTL_TIME_IO
2079		entry->start_bt = io->io_hdr.start_bt;
2080#endif
2081		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2082		entry->cdb_len = io->scsiio.cdb_len;
2083		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2084			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2085
2086		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2087			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2088
2089		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2090			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2091
2092		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2093			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2094
2095		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2096			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2097	}
2098	mtx_unlock(&lun->lun_lock);
2099
2100	return (retval);
2101}
2102
2103static void *
2104ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2105		 size_t error_str_len)
2106{
2107	void *kptr;
2108
2109	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2110
2111	if (copyin(user_addr, kptr, len) != 0) {
2112		snprintf(error_str, error_str_len, "Error copying %d bytes "
2113			 "from user address %p to kernel address %p", len,
2114			 user_addr, kptr);
2115		free(kptr, M_CTL);
2116		return (NULL);
2117	}
2118
2119	return (kptr);
2120}
2121
2122static void
2123ctl_free_args(int num_args, struct ctl_be_arg *args)
2124{
2125	int i;
2126
2127	if (args == NULL)
2128		return;
2129
2130	for (i = 0; i < num_args; i++) {
2131		free(args[i].kname, M_CTL);
2132		free(args[i].kvalue, M_CTL);
2133	}
2134
2135	free(args, M_CTL);
2136}
2137
2138static struct ctl_be_arg *
2139ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2140		char *error_str, size_t error_str_len)
2141{
2142	struct ctl_be_arg *args;
2143	int i;
2144
2145	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2146				error_str, error_str_len);
2147
2148	if (args == NULL)
2149		goto bailout;
2150
2151	for (i = 0; i < num_args; i++) {
2152		args[i].kname = NULL;
2153		args[i].kvalue = NULL;
2154	}
2155
2156	for (i = 0; i < num_args; i++) {
2157		uint8_t *tmpptr;
2158
2159		args[i].kname = ctl_copyin_alloc(args[i].name,
2160			args[i].namelen, error_str, error_str_len);
2161		if (args[i].kname == NULL)
2162			goto bailout;
2163
2164		if (args[i].kname[args[i].namelen - 1] != '\0') {
2165			snprintf(error_str, error_str_len, "Argument %d "
2166				 "name is not NUL-terminated", i);
2167			goto bailout;
2168		}
2169
2170		if (args[i].flags & CTL_BEARG_RD) {
2171			tmpptr = ctl_copyin_alloc(args[i].value,
2172				args[i].vallen, error_str, error_str_len);
2173			if (tmpptr == NULL)
2174				goto bailout;
2175			if ((args[i].flags & CTL_BEARG_ASCII)
2176			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2177				snprintf(error_str, error_str_len, "Argument "
2178				    "%d value is not NUL-terminated", i);
2179				goto bailout;
2180			}
2181			args[i].kvalue = tmpptr;
2182		} else {
2183			args[i].kvalue = malloc(args[i].vallen,
2184			    M_CTL, M_WAITOK | M_ZERO);
2185		}
2186	}
2187
2188	return (args);
2189bailout:
2190
2191	ctl_free_args(num_args, args);
2192
2193	return (NULL);
2194}
2195
2196static void
2197ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2198{
2199	int i;
2200
2201	for (i = 0; i < num_args; i++) {
2202		if (args[i].flags & CTL_BEARG_WR)
2203			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2204	}
2205}
2206
2207/*
2208 * Escape characters that are illegal or not recommended in XML.
2209 */
2210int
2211ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2212{
2213	int retval;
2214
2215	retval = 0;
2216
2217	for (; *str; str++) {
2218		switch (*str) {
2219		case '&':
2220			retval = sbuf_printf(sb, "&amp;");
2221			break;
2222		case '>':
2223			retval = sbuf_printf(sb, "&gt;");
2224			break;
2225		case '<':
2226			retval = sbuf_printf(sb, "&lt;");
2227			break;
2228		default:
2229			retval = sbuf_putc(sb, *str);
2230			break;
2231		}
2232
2233		if (retval != 0)
2234			break;
2235
2236	}
2237
2238	return (retval);
2239}
2240
2241static int
2242ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2243	  struct thread *td)
2244{
2245	struct ctl_softc *softc;
2246	int retval;
2247
2248	softc = control_softc;
2249
2250	retval = 0;
2251
2252	switch (cmd) {
2253	case CTL_IO: {
2254		union ctl_io *io;
2255		void *pool_tmp;
2256
2257		/*
2258		 * If we haven't been "enabled", don't allow any SCSI I/O
2259		 * to this FETD.
2260		 */
2261		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2262			retval = EPERM;
2263			break;
2264		}
2265
2266		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2267		if (io == NULL) {
2268			printf("ctl_ioctl: can't allocate ctl_io!\n");
2269			retval = ENOSPC;
2270			break;
2271		}
2272
2273		/*
2274		 * Need to save the pool reference so it doesn't get
2275		 * spammed by the user's ctl_io.
2276		 */
2277		pool_tmp = io->io_hdr.pool;
2278
2279		memcpy(io, (void *)addr, sizeof(*io));
2280
2281		io->io_hdr.pool = pool_tmp;
2282		/*
2283		 * No status yet, so make sure the status is set properly.
2284		 */
2285		io->io_hdr.status = CTL_STATUS_NONE;
2286
2287		/*
2288		 * The user sets the initiator ID, target and LUN IDs.
2289		 */
2290		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2291		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2292		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2293		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2294			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2295
2296		retval = ctl_ioctl_submit_wait(io);
2297
2298		if (retval != 0) {
2299			ctl_free_io(io);
2300			break;
2301		}
2302
2303		memcpy((void *)addr, io, sizeof(*io));
2304
2305		/* return this to our pool */
2306		ctl_free_io(io);
2307
2308		break;
2309	}
2310	case CTL_ENABLE_PORT:
2311	case CTL_DISABLE_PORT:
2312	case CTL_SET_PORT_WWNS: {
2313		struct ctl_port *port;
2314		struct ctl_port_entry *entry;
2315
2316		entry = (struct ctl_port_entry *)addr;
2317
2318		mtx_lock(&softc->ctl_lock);
2319		STAILQ_FOREACH(port, &softc->port_list, links) {
2320			int action, done;
2321
2322			action = 0;
2323			done = 0;
2324
2325			if ((entry->port_type == CTL_PORT_NONE)
2326			 && (entry->targ_port == port->targ_port)) {
2327				/*
2328				 * If the user only wants to enable or
2329				 * disable or set WWNs on a specific port,
2330				 * do the operation and we're done.
2331				 */
2332				action = 1;
2333				done = 1;
2334			} else if (entry->port_type & port->port_type) {
2335				/*
2336				 * Compare the user's type mask with the
2337				 * particular frontend type to see if we
2338				 * have a match.
2339				 */
2340				action = 1;
2341				done = 0;
2342
2343				/*
2344				 * Make sure the user isn't trying to set
2345				 * WWNs on multiple ports at the same time.
2346				 */
2347				if (cmd == CTL_SET_PORT_WWNS) {
2348					printf("%s: Can't set WWNs on "
2349					       "multiple ports\n", __func__);
2350					retval = EINVAL;
2351					break;
2352				}
2353			}
2354			if (action != 0) {
2355				/*
2356				 * XXX KDM we have to drop the lock here,
2357				 * because the online/offline operations
2358				 * can potentially block.  We need to
2359				 * reference count the frontends so they
2360				 * can't go away,
2361				 */
2362				mtx_unlock(&softc->ctl_lock);
2363
2364				if (cmd == CTL_ENABLE_PORT) {
2365					struct ctl_lun *lun;
2366
2367					STAILQ_FOREACH(lun, &softc->lun_list,
2368						       links) {
2369						port->lun_enable(port->targ_lun_arg,
2370						    lun->target,
2371						    lun->lun);
2372					}
2373
2374					ctl_port_online(port);
2375				} else if (cmd == CTL_DISABLE_PORT) {
2376					struct ctl_lun *lun;
2377
2378					ctl_port_offline(port);
2379
2380					STAILQ_FOREACH(lun, &softc->lun_list,
2381						       links) {
2382						port->lun_disable(
2383						    port->targ_lun_arg,
2384						    lun->target,
2385						    lun->lun);
2386					}
2387				}
2388
2389				mtx_lock(&softc->ctl_lock);
2390
2391				if (cmd == CTL_SET_PORT_WWNS)
2392					ctl_port_set_wwns(port,
2393					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2394					    1 : 0, entry->wwnn,
2395					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2396					    1 : 0, entry->wwpn);
2397			}
2398			if (done != 0)
2399				break;
2400		}
2401		mtx_unlock(&softc->ctl_lock);
2402		break;
2403	}
2404	case CTL_GET_PORT_LIST: {
2405		struct ctl_port *port;
2406		struct ctl_port_list *list;
2407		int i;
2408
2409		list = (struct ctl_port_list *)addr;
2410
2411		if (list->alloc_len != (list->alloc_num *
2412		    sizeof(struct ctl_port_entry))) {
2413			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2414			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2415			       "%zu\n", __func__, list->alloc_len,
2416			       list->alloc_num, sizeof(struct ctl_port_entry));
2417			retval = EINVAL;
2418			break;
2419		}
2420		list->fill_len = 0;
2421		list->fill_num = 0;
2422		list->dropped_num = 0;
2423		i = 0;
2424		mtx_lock(&softc->ctl_lock);
2425		STAILQ_FOREACH(port, &softc->port_list, links) {
2426			struct ctl_port_entry entry, *list_entry;
2427
2428			if (list->fill_num >= list->alloc_num) {
2429				list->dropped_num++;
2430				continue;
2431			}
2432
2433			entry.port_type = port->port_type;
2434			strlcpy(entry.port_name, port->port_name,
2435				sizeof(entry.port_name));
2436			entry.targ_port = port->targ_port;
2437			entry.physical_port = port->physical_port;
2438			entry.virtual_port = port->virtual_port;
2439			entry.wwnn = port->wwnn;
2440			entry.wwpn = port->wwpn;
2441			if (port->status & CTL_PORT_STATUS_ONLINE)
2442				entry.online = 1;
2443			else
2444				entry.online = 0;
2445
2446			list_entry = &list->entries[i];
2447
2448			retval = copyout(&entry, list_entry, sizeof(entry));
2449			if (retval != 0) {
2450				printf("%s: CTL_GET_PORT_LIST: copyout "
2451				       "returned %d\n", __func__, retval);
2452				break;
2453			}
2454			i++;
2455			list->fill_num++;
2456			list->fill_len += sizeof(entry);
2457		}
2458		mtx_unlock(&softc->ctl_lock);
2459
2460		/*
2461		 * If this is non-zero, we had a copyout fault, so there's
2462		 * probably no point in attempting to set the status inside
2463		 * the structure.
2464		 */
2465		if (retval != 0)
2466			break;
2467
2468		if (list->dropped_num > 0)
2469			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2470		else
2471			list->status = CTL_PORT_LIST_OK;
2472		break;
2473	}
2474	case CTL_DUMP_OOA: {
2475		struct ctl_lun *lun;
2476		union ctl_io *io;
2477		char printbuf[128];
2478		struct sbuf sb;
2479
2480		mtx_lock(&softc->ctl_lock);
2481		printf("Dumping OOA queues:\n");
2482		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2483			mtx_lock(&lun->lun_lock);
2484			for (io = (union ctl_io *)TAILQ_FIRST(
2485			     &lun->ooa_queue); io != NULL;
2486			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2487			     ooa_links)) {
2488				sbuf_new(&sb, printbuf, sizeof(printbuf),
2489					 SBUF_FIXEDLEN);
2490				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2491					    (intmax_t)lun->lun,
2492					    io->scsiio.tag_num,
2493					    (io->io_hdr.flags &
2494					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2495					    (io->io_hdr.flags &
2496					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2497					    (io->io_hdr.flags &
2498					    CTL_FLAG_ABORT) ? " ABORT" : "",
2499			                    (io->io_hdr.flags &
2500		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2501				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2502				sbuf_finish(&sb);
2503				printf("%s\n", sbuf_data(&sb));
2504			}
2505			mtx_unlock(&lun->lun_lock);
2506		}
2507		printf("OOA queues dump done\n");
2508		mtx_unlock(&softc->ctl_lock);
2509		break;
2510	}
2511	case CTL_GET_OOA: {
2512		struct ctl_lun *lun;
2513		struct ctl_ooa *ooa_hdr;
2514		struct ctl_ooa_entry *entries;
2515		uint32_t cur_fill_num;
2516
2517		ooa_hdr = (struct ctl_ooa *)addr;
2518
2519		if ((ooa_hdr->alloc_len == 0)
2520		 || (ooa_hdr->alloc_num == 0)) {
2521			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2522			       "must be non-zero\n", __func__,
2523			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2524			retval = EINVAL;
2525			break;
2526		}
2527
2528		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2529		    sizeof(struct ctl_ooa_entry))) {
2530			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2531			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2532			       __func__, ooa_hdr->alloc_len,
2533			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2534			retval = EINVAL;
2535			break;
2536		}
2537
2538		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2539		if (entries == NULL) {
2540			printf("%s: could not allocate %d bytes for OOA "
2541			       "dump\n", __func__, ooa_hdr->alloc_len);
2542			retval = ENOMEM;
2543			break;
2544		}
2545
2546		mtx_lock(&softc->ctl_lock);
2547		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2548		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2549		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2550			mtx_unlock(&softc->ctl_lock);
2551			free(entries, M_CTL);
2552			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2553			       __func__, (uintmax_t)ooa_hdr->lun_num);
2554			retval = EINVAL;
2555			break;
2556		}
2557
2558		cur_fill_num = 0;
2559
2560		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2561			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2562				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2563					ooa_hdr, entries);
2564				if (retval != 0)
2565					break;
2566			}
2567			if (retval != 0) {
2568				mtx_unlock(&softc->ctl_lock);
2569				free(entries, M_CTL);
2570				break;
2571			}
2572		} else {
2573			lun = softc->ctl_luns[ooa_hdr->lun_num];
2574
2575			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2576						    entries);
2577		}
2578		mtx_unlock(&softc->ctl_lock);
2579
2580		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2581		ooa_hdr->fill_len = ooa_hdr->fill_num *
2582			sizeof(struct ctl_ooa_entry);
2583		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2584		if (retval != 0) {
2585			printf("%s: error copying out %d bytes for OOA dump\n",
2586			       __func__, ooa_hdr->fill_len);
2587		}
2588
2589		getbintime(&ooa_hdr->cur_bt);
2590
2591		if (cur_fill_num > ooa_hdr->alloc_num) {
2592			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2593			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2594		} else {
2595			ooa_hdr->dropped_num = 0;
2596			ooa_hdr->status = CTL_OOA_OK;
2597		}
2598
2599		free(entries, M_CTL);
2600		break;
2601	}
2602	case CTL_CHECK_OOA: {
2603		union ctl_io *io;
2604		struct ctl_lun *lun;
2605		struct ctl_ooa_info *ooa_info;
2606
2607
2608		ooa_info = (struct ctl_ooa_info *)addr;
2609
2610		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2611			ooa_info->status = CTL_OOA_INVALID_LUN;
2612			break;
2613		}
2614		mtx_lock(&softc->ctl_lock);
2615		lun = softc->ctl_luns[ooa_info->lun_id];
2616		if (lun == NULL) {
2617			mtx_unlock(&softc->ctl_lock);
2618			ooa_info->status = CTL_OOA_INVALID_LUN;
2619			break;
2620		}
2621		mtx_lock(&lun->lun_lock);
2622		mtx_unlock(&softc->ctl_lock);
2623		ooa_info->num_entries = 0;
2624		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2625		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2626		     &io->io_hdr, ooa_links)) {
2627			ooa_info->num_entries++;
2628		}
2629		mtx_unlock(&lun->lun_lock);
2630
2631		ooa_info->status = CTL_OOA_SUCCESS;
2632
2633		break;
2634	}
2635	case CTL_HARD_START:
2636	case CTL_HARD_STOP: {
2637		struct ctl_fe_ioctl_startstop_info ss_info;
2638		struct cfi_metatask *metatask;
2639		struct mtx hs_mtx;
2640
2641		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2642
2643		cv_init(&ss_info.sem, "hard start/stop cv" );
2644
2645		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2646		if (metatask == NULL) {
2647			retval = ENOMEM;
2648			mtx_destroy(&hs_mtx);
2649			break;
2650		}
2651
2652		if (cmd == CTL_HARD_START)
2653			metatask->tasktype = CFI_TASK_STARTUP;
2654		else
2655			metatask->tasktype = CFI_TASK_SHUTDOWN;
2656
2657		metatask->callback = ctl_ioctl_hard_startstop_callback;
2658		metatask->callback_arg = &ss_info;
2659
2660		cfi_action(metatask);
2661
2662		/* Wait for the callback */
2663		mtx_lock(&hs_mtx);
2664		cv_wait_sig(&ss_info.sem, &hs_mtx);
2665		mtx_unlock(&hs_mtx);
2666
2667		/*
2668		 * All information has been copied from the metatask by the
2669		 * time cv_broadcast() is called, so we free the metatask here.
2670		 */
2671		cfi_free_metatask(metatask);
2672
2673		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2674
2675		mtx_destroy(&hs_mtx);
2676		break;
2677	}
2678	case CTL_BBRREAD: {
2679		struct ctl_bbrread_info *bbr_info;
2680		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2681		struct mtx bbr_mtx;
2682		struct cfi_metatask *metatask;
2683
2684		bbr_info = (struct ctl_bbrread_info *)addr;
2685
2686		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2687
2688		bzero(&bbr_mtx, sizeof(bbr_mtx));
2689		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2690
2691		fe_bbr_info.bbr_info = bbr_info;
2692		fe_bbr_info.lock = &bbr_mtx;
2693
2694		cv_init(&fe_bbr_info.sem, "BBR read cv");
2695		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2696
2697		if (metatask == NULL) {
2698			mtx_destroy(&bbr_mtx);
2699			cv_destroy(&fe_bbr_info.sem);
2700			retval = ENOMEM;
2701			break;
2702		}
2703		metatask->tasktype = CFI_TASK_BBRREAD;
2704		metatask->callback = ctl_ioctl_bbrread_callback;
2705		metatask->callback_arg = &fe_bbr_info;
2706		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2707		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2708		metatask->taskinfo.bbrread.len = bbr_info->len;
2709
2710		cfi_action(metatask);
2711
2712		mtx_lock(&bbr_mtx);
2713		while (fe_bbr_info.wakeup_done == 0)
2714			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2715		mtx_unlock(&bbr_mtx);
2716
2717		bbr_info->status = metatask->status;
2718		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2719		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2720		memcpy(&bbr_info->sense_data,
2721		       &metatask->taskinfo.bbrread.sense_data,
2722		       ctl_min(sizeof(bbr_info->sense_data),
2723			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2724
2725		cfi_free_metatask(metatask);
2726
2727		mtx_destroy(&bbr_mtx);
2728		cv_destroy(&fe_bbr_info.sem);
2729
2730		break;
2731	}
2732	case CTL_DELAY_IO: {
2733		struct ctl_io_delay_info *delay_info;
2734#ifdef CTL_IO_DELAY
2735		struct ctl_lun *lun;
2736#endif /* CTL_IO_DELAY */
2737
2738		delay_info = (struct ctl_io_delay_info *)addr;
2739
2740#ifdef CTL_IO_DELAY
2741		mtx_lock(&softc->ctl_lock);
2742
2743		if ((delay_info->lun_id > CTL_MAX_LUNS)
2744		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2745			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2746		} else {
2747			lun = softc->ctl_luns[delay_info->lun_id];
2748			mtx_lock(&lun->lun_lock);
2749
2750			delay_info->status = CTL_DELAY_STATUS_OK;
2751
2752			switch (delay_info->delay_type) {
2753			case CTL_DELAY_TYPE_CONT:
2754				break;
2755			case CTL_DELAY_TYPE_ONESHOT:
2756				break;
2757			default:
2758				delay_info->status =
2759					CTL_DELAY_STATUS_INVALID_TYPE;
2760				break;
2761			}
2762
2763			switch (delay_info->delay_loc) {
2764			case CTL_DELAY_LOC_DATAMOVE:
2765				lun->delay_info.datamove_type =
2766					delay_info->delay_type;
2767				lun->delay_info.datamove_delay =
2768					delay_info->delay_secs;
2769				break;
2770			case CTL_DELAY_LOC_DONE:
2771				lun->delay_info.done_type =
2772					delay_info->delay_type;
2773				lun->delay_info.done_delay =
2774					delay_info->delay_secs;
2775				break;
2776			default:
2777				delay_info->status =
2778					CTL_DELAY_STATUS_INVALID_LOC;
2779				break;
2780			}
2781			mtx_unlock(&lun->lun_lock);
2782		}
2783
2784		mtx_unlock(&softc->ctl_lock);
2785#else
2786		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2787#endif /* CTL_IO_DELAY */
2788		break;
2789	}
2790	case CTL_REALSYNC_SET: {
2791		int *syncstate;
2792
2793		syncstate = (int *)addr;
2794
2795		mtx_lock(&softc->ctl_lock);
2796		switch (*syncstate) {
2797		case 0:
2798			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2799			break;
2800		case 1:
2801			softc->flags |= CTL_FLAG_REAL_SYNC;
2802			break;
2803		default:
2804			retval = EINVAL;
2805			break;
2806		}
2807		mtx_unlock(&softc->ctl_lock);
2808		break;
2809	}
2810	case CTL_REALSYNC_GET: {
2811		int *syncstate;
2812
2813		syncstate = (int*)addr;
2814
2815		mtx_lock(&softc->ctl_lock);
2816		if (softc->flags & CTL_FLAG_REAL_SYNC)
2817			*syncstate = 1;
2818		else
2819			*syncstate = 0;
2820		mtx_unlock(&softc->ctl_lock);
2821
2822		break;
2823	}
2824	case CTL_SETSYNC:
2825	case CTL_GETSYNC: {
2826		struct ctl_sync_info *sync_info;
2827		struct ctl_lun *lun;
2828
2829		sync_info = (struct ctl_sync_info *)addr;
2830
2831		mtx_lock(&softc->ctl_lock);
2832		lun = softc->ctl_luns[sync_info->lun_id];
2833		if (lun == NULL) {
2834			mtx_unlock(&softc->ctl_lock);
2835			sync_info->status = CTL_GS_SYNC_NO_LUN;
2836		}
2837		/*
2838		 * Get or set the sync interval.  We're not bounds checking
2839		 * in the set case, hopefully the user won't do something
2840		 * silly.
2841		 */
2842		mtx_lock(&lun->lun_lock);
2843		mtx_unlock(&softc->ctl_lock);
2844		if (cmd == CTL_GETSYNC)
2845			sync_info->sync_interval = lun->sync_interval;
2846		else
2847			lun->sync_interval = sync_info->sync_interval;
2848		mtx_unlock(&lun->lun_lock);
2849
2850		sync_info->status = CTL_GS_SYNC_OK;
2851
2852		break;
2853	}
2854	case CTL_GETSTATS: {
2855		struct ctl_stats *stats;
2856		struct ctl_lun *lun;
2857		int i;
2858
2859		stats = (struct ctl_stats *)addr;
2860
2861		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2862		     stats->alloc_len) {
2863			stats->status = CTL_SS_NEED_MORE_SPACE;
2864			stats->num_luns = softc->num_luns;
2865			break;
2866		}
2867		/*
2868		 * XXX KDM no locking here.  If the LUN list changes,
2869		 * things can blow up.
2870		 */
2871		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2872		     i++, lun = STAILQ_NEXT(lun, links)) {
2873			retval = copyout(&lun->stats, &stats->lun_stats[i],
2874					 sizeof(lun->stats));
2875			if (retval != 0)
2876				break;
2877		}
2878		stats->num_luns = softc->num_luns;
2879		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2880				 softc->num_luns;
2881		stats->status = CTL_SS_OK;
2882#ifdef CTL_TIME_IO
2883		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2884#else
2885		stats->flags = CTL_STATS_FLAG_NONE;
2886#endif
2887		getnanouptime(&stats->timestamp);
2888		break;
2889	}
2890	case CTL_ERROR_INJECT: {
2891		struct ctl_error_desc *err_desc, *new_err_desc;
2892		struct ctl_lun *lun;
2893
2894		err_desc = (struct ctl_error_desc *)addr;
2895
2896		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2897				      M_WAITOK | M_ZERO);
2898		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2899
2900		mtx_lock(&softc->ctl_lock);
2901		lun = softc->ctl_luns[err_desc->lun_id];
2902		if (lun == NULL) {
2903			mtx_unlock(&softc->ctl_lock);
2904			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2905			       __func__, (uintmax_t)err_desc->lun_id);
2906			retval = EINVAL;
2907			break;
2908		}
2909		mtx_lock(&lun->lun_lock);
2910		mtx_unlock(&softc->ctl_lock);
2911
2912		/*
2913		 * We could do some checking here to verify the validity
2914		 * of the request, but given the complexity of error
2915		 * injection requests, the checking logic would be fairly
2916		 * complex.
2917		 *
2918		 * For now, if the request is invalid, it just won't get
2919		 * executed and might get deleted.
2920		 */
2921		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2922
2923		/*
2924		 * XXX KDM check to make sure the serial number is unique,
2925		 * in case we somehow manage to wrap.  That shouldn't
2926		 * happen for a very long time, but it's the right thing to
2927		 * do.
2928		 */
2929		new_err_desc->serial = lun->error_serial;
2930		err_desc->serial = lun->error_serial;
2931		lun->error_serial++;
2932
2933		mtx_unlock(&lun->lun_lock);
2934		break;
2935	}
2936	case CTL_ERROR_INJECT_DELETE: {
2937		struct ctl_error_desc *delete_desc, *desc, *desc2;
2938		struct ctl_lun *lun;
2939		int delete_done;
2940
2941		delete_desc = (struct ctl_error_desc *)addr;
2942		delete_done = 0;
2943
2944		mtx_lock(&softc->ctl_lock);
2945		lun = softc->ctl_luns[delete_desc->lun_id];
2946		if (lun == NULL) {
2947			mtx_unlock(&softc->ctl_lock);
2948			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2949			       __func__, (uintmax_t)delete_desc->lun_id);
2950			retval = EINVAL;
2951			break;
2952		}
2953		mtx_lock(&lun->lun_lock);
2954		mtx_unlock(&softc->ctl_lock);
2955		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2956			if (desc->serial != delete_desc->serial)
2957				continue;
2958
2959			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2960				      links);
2961			free(desc, M_CTL);
2962			delete_done = 1;
2963		}
2964		mtx_unlock(&lun->lun_lock);
2965		if (delete_done == 0) {
2966			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2967			       "error serial %ju on LUN %u\n", __func__,
2968			       delete_desc->serial, delete_desc->lun_id);
2969			retval = EINVAL;
2970			break;
2971		}
2972		break;
2973	}
2974	case CTL_DUMP_STRUCTS: {
2975		int i, j, k, idx;
2976		struct ctl_port *port;
2977		struct ctl_frontend *fe;
2978
2979		mtx_lock(&softc->ctl_lock);
2980		printf("CTL Persistent Reservation information start:\n");
2981		for (i = 0; i < CTL_MAX_LUNS; i++) {
2982			struct ctl_lun *lun;
2983
2984			lun = softc->ctl_luns[i];
2985
2986			if ((lun == NULL)
2987			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2988				continue;
2989
2990			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2991				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2992					idx = j * CTL_MAX_INIT_PER_PORT + k;
2993					if (lun->per_res[idx].registered == 0)
2994						continue;
2995					printf("  LUN %d port %d iid %d key "
2996					       "%#jx\n", i, j, k,
2997					       (uintmax_t)scsi_8btou64(
2998					       lun->per_res[idx].res_key.key));
2999				}
3000			}
3001		}
3002		printf("CTL Persistent Reservation information end\n");
3003		printf("CTL Ports:\n");
3004		STAILQ_FOREACH(port, &softc->port_list, links) {
3005			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3006			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3007			       port->frontend->name, port->port_type,
3008			       port->physical_port, port->virtual_port,
3009			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3010			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3011				if (port->wwpn_iid[j].in_use == 0 &&
3012				    port->wwpn_iid[j].wwpn == 0 &&
3013				    port->wwpn_iid[j].name == NULL)
3014					continue;
3015
3016				printf("    iid %u use %d WWPN %#jx '%s'\n",
3017				    j, port->wwpn_iid[j].in_use,
3018				    (uintmax_t)port->wwpn_iid[j].wwpn,
3019				    port->wwpn_iid[j].name);
3020			}
3021		}
3022		printf("CTL Port information end\n");
3023		mtx_unlock(&softc->ctl_lock);
3024		/*
3025		 * XXX KDM calling this without a lock.  We'd likely want
3026		 * to drop the lock before calling the frontend's dump
3027		 * routine anyway.
3028		 */
3029		printf("CTL Frontends:\n");
3030		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3031			printf("  Frontend '%s'\n", fe->name);
3032			if (fe->fe_dump != NULL)
3033				fe->fe_dump();
3034		}
3035		printf("CTL Frontend information end\n");
3036		break;
3037	}
3038	case CTL_LUN_REQ: {
3039		struct ctl_lun_req *lun_req;
3040		struct ctl_backend_driver *backend;
3041
3042		lun_req = (struct ctl_lun_req *)addr;
3043
3044		backend = ctl_backend_find(lun_req->backend);
3045		if (backend == NULL) {
3046			lun_req->status = CTL_LUN_ERROR;
3047			snprintf(lun_req->error_str,
3048				 sizeof(lun_req->error_str),
3049				 "Backend \"%s\" not found.",
3050				 lun_req->backend);
3051			break;
3052		}
3053		if (lun_req->num_be_args > 0) {
3054			lun_req->kern_be_args = ctl_copyin_args(
3055				lun_req->num_be_args,
3056				lun_req->be_args,
3057				lun_req->error_str,
3058				sizeof(lun_req->error_str));
3059			if (lun_req->kern_be_args == NULL) {
3060				lun_req->status = CTL_LUN_ERROR;
3061				break;
3062			}
3063		}
3064
3065		retval = backend->ioctl(dev, cmd, addr, flag, td);
3066
3067		if (lun_req->num_be_args > 0) {
3068			ctl_copyout_args(lun_req->num_be_args,
3069				      lun_req->kern_be_args);
3070			ctl_free_args(lun_req->num_be_args,
3071				      lun_req->kern_be_args);
3072		}
3073		break;
3074	}
3075	case CTL_LUN_LIST: {
3076		struct sbuf *sb;
3077		struct ctl_lun *lun;
3078		struct ctl_lun_list *list;
3079		struct ctl_option *opt;
3080
3081		list = (struct ctl_lun_list *)addr;
3082
3083		/*
3084		 * Allocate a fixed length sbuf here, based on the length
3085		 * of the user's buffer.  We could allocate an auto-extending
3086		 * buffer, and then tell the user how much larger our
3087		 * amount of data is than his buffer, but that presents
3088		 * some problems:
3089		 *
3090		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3091		 *     we can't hold a lock while calling them with an
3092		 *     auto-extending buffer.
3093 		 *
3094		 * 2.  There is not currently a LUN reference counting
3095		 *     mechanism, outside of outstanding transactions on
3096		 *     the LUN's OOA queue.  So a LUN could go away on us
3097		 *     while we're getting the LUN number, backend-specific
3098		 *     information, etc.  Thus, given the way things
3099		 *     currently work, we need to hold the CTL lock while
3100		 *     grabbing LUN information.
3101		 *
3102		 * So, from the user's standpoint, the best thing to do is
3103		 * allocate what he thinks is a reasonable buffer length,
3104		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3105		 * double the buffer length and try again.  (And repeat
3106		 * that until he succeeds.)
3107		 */
3108		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3109		if (sb == NULL) {
3110			list->status = CTL_LUN_LIST_ERROR;
3111			snprintf(list->error_str, sizeof(list->error_str),
3112				 "Unable to allocate %d bytes for LUN list",
3113				 list->alloc_len);
3114			break;
3115		}
3116
3117		sbuf_printf(sb, "<ctllunlist>\n");
3118
3119		mtx_lock(&softc->ctl_lock);
3120		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3121			mtx_lock(&lun->lun_lock);
3122			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3123					     (uintmax_t)lun->lun);
3124
3125			/*
3126			 * Bail out as soon as we see that we've overfilled
3127			 * the buffer.
3128			 */
3129			if (retval != 0)
3130				break;
3131
3132			retval = sbuf_printf(sb, "\t<backend_type>%s"
3133					     "</backend_type>\n",
3134					     (lun->backend == NULL) ?  "none" :
3135					     lun->backend->name);
3136
3137			if (retval != 0)
3138				break;
3139
3140			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3141					     lun->be_lun->lun_type);
3142
3143			if (retval != 0)
3144				break;
3145
3146			if (lun->backend == NULL) {
3147				retval = sbuf_printf(sb, "</lun>\n");
3148				if (retval != 0)
3149					break;
3150				continue;
3151			}
3152
3153			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3154					     (lun->be_lun->maxlba > 0) ?
3155					     lun->be_lun->maxlba + 1 : 0);
3156
3157			if (retval != 0)
3158				break;
3159
3160			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3161					     lun->be_lun->blocksize);
3162
3163			if (retval != 0)
3164				break;
3165
3166			retval = sbuf_printf(sb, "\t<serial_number>");
3167
3168			if (retval != 0)
3169				break;
3170
3171			retval = ctl_sbuf_printf_esc(sb,
3172						     lun->be_lun->serial_num);
3173
3174			if (retval != 0)
3175				break;
3176
3177			retval = sbuf_printf(sb, "</serial_number>\n");
3178
3179			if (retval != 0)
3180				break;
3181
3182			retval = sbuf_printf(sb, "\t<device_id>");
3183
3184			if (retval != 0)
3185				break;
3186
3187			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3188
3189			if (retval != 0)
3190				break;
3191
3192			retval = sbuf_printf(sb, "</device_id>\n");
3193
3194			if (retval != 0)
3195				break;
3196
3197			if (lun->backend->lun_info != NULL) {
3198				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3199				if (retval != 0)
3200					break;
3201			}
3202			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3203				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3204				    opt->name, opt->value, opt->name);
3205				if (retval != 0)
3206					break;
3207			}
3208
3209			retval = sbuf_printf(sb, "</lun>\n");
3210
3211			if (retval != 0)
3212				break;
3213			mtx_unlock(&lun->lun_lock);
3214		}
3215		if (lun != NULL)
3216			mtx_unlock(&lun->lun_lock);
3217		mtx_unlock(&softc->ctl_lock);
3218
3219		if ((retval != 0)
3220		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3221			retval = 0;
3222			sbuf_delete(sb);
3223			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3224			snprintf(list->error_str, sizeof(list->error_str),
3225				 "Out of space, %d bytes is too small",
3226				 list->alloc_len);
3227			break;
3228		}
3229
3230		sbuf_finish(sb);
3231
3232		retval = copyout(sbuf_data(sb), list->lun_xml,
3233				 sbuf_len(sb) + 1);
3234
3235		list->fill_len = sbuf_len(sb) + 1;
3236		list->status = CTL_LUN_LIST_OK;
3237		sbuf_delete(sb);
3238		break;
3239	}
3240	case CTL_ISCSI: {
3241		struct ctl_iscsi *ci;
3242		struct ctl_frontend *fe;
3243
3244		ci = (struct ctl_iscsi *)addr;
3245
3246		fe = ctl_frontend_find("iscsi");
3247		if (fe == NULL) {
3248			ci->status = CTL_ISCSI_ERROR;
3249			snprintf(ci->error_str, sizeof(ci->error_str),
3250			    "Frontend \"iscsi\" not found.");
3251			break;
3252		}
3253
3254		retval = fe->ioctl(dev, cmd, addr, flag, td);
3255		break;
3256	}
3257	case CTL_PORT_REQ: {
3258		struct ctl_req *req;
3259		struct ctl_frontend *fe;
3260
3261		req = (struct ctl_req *)addr;
3262
3263		fe = ctl_frontend_find(req->driver);
3264		if (fe == NULL) {
3265			req->status = CTL_LUN_ERROR;
3266			snprintf(req->error_str, sizeof(req->error_str),
3267			    "Frontend \"%s\" not found.", req->driver);
3268			break;
3269		}
3270		if (req->num_args > 0) {
3271			req->kern_args = ctl_copyin_args(req->num_args,
3272			    req->args, req->error_str, sizeof(req->error_str));
3273			if (req->kern_args == NULL) {
3274				req->status = CTL_LUN_ERROR;
3275				break;
3276			}
3277		}
3278
3279		retval = fe->ioctl(dev, cmd, addr, flag, td);
3280
3281		if (req->num_args > 0) {
3282			ctl_copyout_args(req->num_args, req->kern_args);
3283			ctl_free_args(req->num_args, req->kern_args);
3284		}
3285		break;
3286	}
3287	case CTL_PORT_LIST: {
3288		struct sbuf *sb;
3289		struct ctl_port *port;
3290		struct ctl_lun_list *list;
3291		struct ctl_option *opt;
3292
3293		list = (struct ctl_lun_list *)addr;
3294
3295		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3296		if (sb == NULL) {
3297			list->status = CTL_LUN_LIST_ERROR;
3298			snprintf(list->error_str, sizeof(list->error_str),
3299				 "Unable to allocate %d bytes for LUN list",
3300				 list->alloc_len);
3301			break;
3302		}
3303
3304		sbuf_printf(sb, "<ctlportlist>\n");
3305
3306		mtx_lock(&softc->ctl_lock);
3307		STAILQ_FOREACH(port, &softc->port_list, links) {
3308			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3309					     (uintmax_t)port->targ_port);
3310
3311			/*
3312			 * Bail out as soon as we see that we've overfilled
3313			 * the buffer.
3314			 */
3315			if (retval != 0)
3316				break;
3317
3318			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3319			    "</frontend_type>\n", port->frontend->name);
3320			if (retval != 0)
3321				break;
3322
3323			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3324					     port->port_type);
3325			if (retval != 0)
3326				break;
3327
3328			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3329			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3330			if (retval != 0)
3331				break;
3332
3333			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3334			    port->port_name);
3335			if (retval != 0)
3336				break;
3337
3338			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3339			    port->physical_port);
3340			if (retval != 0)
3341				break;
3342
3343			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3344			    port->virtual_port);
3345			if (retval != 0)
3346				break;
3347
3348			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3349			    (uintmax_t)port->wwnn);
3350			if (retval != 0)
3351				break;
3352
3353			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3354			    (uintmax_t)port->wwpn);
3355			if (retval != 0)
3356				break;
3357
3358			if (port->port_info != NULL) {
3359				retval = port->port_info(port->onoff_arg, sb);
3360				if (retval != 0)
3361					break;
3362			}
3363			STAILQ_FOREACH(opt, &port->options, links) {
3364				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3365				    opt->name, opt->value, opt->name);
3366				if (retval != 0)
3367					break;
3368			}
3369
3370			retval = sbuf_printf(sb, "</targ_port>\n");
3371			if (retval != 0)
3372				break;
3373		}
3374		mtx_unlock(&softc->ctl_lock);
3375
3376		if ((retval != 0)
3377		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3378			retval = 0;
3379			sbuf_delete(sb);
3380			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3381			snprintf(list->error_str, sizeof(list->error_str),
3382				 "Out of space, %d bytes is too small",
3383				 list->alloc_len);
3384			break;
3385		}
3386
3387		sbuf_finish(sb);
3388
3389		retval = copyout(sbuf_data(sb), list->lun_xml,
3390				 sbuf_len(sb) + 1);
3391
3392		list->fill_len = sbuf_len(sb) + 1;
3393		list->status = CTL_LUN_LIST_OK;
3394		sbuf_delete(sb);
3395		break;
3396	}
3397	default: {
3398		/* XXX KDM should we fix this? */
3399#if 0
3400		struct ctl_backend_driver *backend;
3401		unsigned int type;
3402		int found;
3403
3404		found = 0;
3405
3406		/*
3407		 * We encode the backend type as the ioctl type for backend
3408		 * ioctls.  So parse it out here, and then search for a
3409		 * backend of this type.
3410		 */
3411		type = _IOC_TYPE(cmd);
3412
3413		STAILQ_FOREACH(backend, &softc->be_list, links) {
3414			if (backend->type == type) {
3415				found = 1;
3416				break;
3417			}
3418		}
3419		if (found == 0) {
3420			printf("ctl: unknown ioctl command %#lx or backend "
3421			       "%d\n", cmd, type);
3422			retval = EINVAL;
3423			break;
3424		}
3425		retval = backend->ioctl(dev, cmd, addr, flag, td);
3426#endif
3427		retval = ENOTTY;
3428		break;
3429	}
3430	}
3431	return (retval);
3432}
3433
3434uint32_t
3435ctl_get_initindex(struct ctl_nexus *nexus)
3436{
3437	if (nexus->targ_port < CTL_MAX_PORTS)
3438		return (nexus->initid.id +
3439			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3440	else
3441		return (nexus->initid.id +
3442		       ((nexus->targ_port - CTL_MAX_PORTS) *
3443			CTL_MAX_INIT_PER_PORT));
3444}
3445
3446uint32_t
3447ctl_get_resindex(struct ctl_nexus *nexus)
3448{
3449	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3450}
3451
3452uint32_t
3453ctl_port_idx(int port_num)
3454{
3455	if (port_num < CTL_MAX_PORTS)
3456		return(port_num);
3457	else
3458		return(port_num - CTL_MAX_PORTS);
3459}
3460
3461static uint32_t
3462ctl_map_lun(int port_num, uint32_t lun_id)
3463{
3464	struct ctl_port *port;
3465
3466	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3467	if (port == NULL)
3468		return (UINT32_MAX);
3469	if (port->lun_map == NULL)
3470		return (lun_id);
3471	return (port->lun_map(port->targ_lun_arg, lun_id));
3472}
3473
3474static uint32_t
3475ctl_map_lun_back(int port_num, uint32_t lun_id)
3476{
3477	struct ctl_port *port;
3478	uint32_t i;
3479
3480	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3481	if (port->lun_map == NULL)
3482		return (lun_id);
3483	for (i = 0; i < CTL_MAX_LUNS; i++) {
3484		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3485			return (i);
3486	}
3487	return (UINT32_MAX);
3488}
3489
3490/*
3491 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3492 * that are a power of 2.
3493 */
3494int
3495ctl_ffz(uint32_t *mask, uint32_t size)
3496{
3497	uint32_t num_chunks, num_pieces;
3498	int i, j;
3499
3500	num_chunks = (size >> 5);
3501	if (num_chunks == 0)
3502		num_chunks++;
3503	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3504
3505	for (i = 0; i < num_chunks; i++) {
3506		for (j = 0; j < num_pieces; j++) {
3507			if ((mask[i] & (1 << j)) == 0)
3508				return ((i << 5) + j);
3509		}
3510	}
3511
3512	return (-1);
3513}
3514
3515int
3516ctl_set_mask(uint32_t *mask, uint32_t bit)
3517{
3518	uint32_t chunk, piece;
3519
3520	chunk = bit >> 5;
3521	piece = bit % (sizeof(uint32_t) * 8);
3522
3523	if ((mask[chunk] & (1 << piece)) != 0)
3524		return (-1);
3525	else
3526		mask[chunk] |= (1 << piece);
3527
3528	return (0);
3529}
3530
3531int
3532ctl_clear_mask(uint32_t *mask, uint32_t bit)
3533{
3534	uint32_t chunk, piece;
3535
3536	chunk = bit >> 5;
3537	piece = bit % (sizeof(uint32_t) * 8);
3538
3539	if ((mask[chunk] & (1 << piece)) == 0)
3540		return (-1);
3541	else
3542		mask[chunk] &= ~(1 << piece);
3543
3544	return (0);
3545}
3546
3547int
3548ctl_is_set(uint32_t *mask, uint32_t bit)
3549{
3550	uint32_t chunk, piece;
3551
3552	chunk = bit >> 5;
3553	piece = bit % (sizeof(uint32_t) * 8);
3554
3555	if ((mask[chunk] & (1 << piece)) == 0)
3556		return (0);
3557	else
3558		return (1);
3559}
3560
3561#ifdef unused
3562/*
3563 * The bus, target and lun are optional, they can be filled in later.
3564 * can_wait is used to determine whether we can wait on the malloc or not.
3565 */
3566union ctl_io*
3567ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3568	      uint32_t targ_lun, int can_wait)
3569{
3570	union ctl_io *io;
3571
3572	if (can_wait)
3573		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3574	else
3575		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3576
3577	if (io != NULL) {
3578		io->io_hdr.io_type = io_type;
3579		io->io_hdr.targ_port = targ_port;
3580		/*
3581		 * XXX KDM this needs to change/go away.  We need to move
3582		 * to a preallocated pool of ctl_scsiio structures.
3583		 */
3584		io->io_hdr.nexus.targ_target.id = targ_target;
3585		io->io_hdr.nexus.targ_lun = targ_lun;
3586	}
3587
3588	return (io);
3589}
3590
3591void
3592ctl_kfree_io(union ctl_io *io)
3593{
3594	free(io, M_CTL);
3595}
3596#endif /* unused */
3597
3598/*
3599 * ctl_softc, pool_type, total_ctl_io are passed in.
3600 * npool is passed out.
3601 */
3602int
3603ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3604		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3605{
3606	uint32_t i;
3607	union ctl_io *cur_io, *next_io;
3608	struct ctl_io_pool *pool;
3609	int retval;
3610
3611	retval = 0;
3612
3613	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3614					    M_NOWAIT | M_ZERO);
3615	if (pool == NULL) {
3616		retval = ENOMEM;
3617		goto bailout;
3618	}
3619
3620	pool->type = pool_type;
3621	pool->ctl_softc = ctl_softc;
3622
3623	mtx_lock(&ctl_softc->pool_lock);
3624	pool->id = ctl_softc->cur_pool_id++;
3625	mtx_unlock(&ctl_softc->pool_lock);
3626
3627	pool->flags = CTL_POOL_FLAG_NONE;
3628	pool->refcount = 1;		/* Reference for validity. */
3629	STAILQ_INIT(&pool->free_queue);
3630
3631	/*
3632	 * XXX KDM other options here:
3633	 * - allocate a page at a time
3634	 * - allocate one big chunk of memory.
3635	 * Page allocation might work well, but would take a little more
3636	 * tracking.
3637	 */
3638	for (i = 0; i < total_ctl_io; i++) {
3639		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3640						M_NOWAIT);
3641		if (cur_io == NULL) {
3642			retval = ENOMEM;
3643			break;
3644		}
3645		cur_io->io_hdr.pool = pool;
3646		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3647		pool->total_ctl_io++;
3648		pool->free_ctl_io++;
3649	}
3650
3651	if (retval != 0) {
3652		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3653		     cur_io != NULL; cur_io = next_io) {
3654			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3655							      links);
3656			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3657				      ctl_io_hdr, links);
3658			free(cur_io, M_CTLIO);
3659		}
3660
3661		free(pool, M_CTL);
3662		goto bailout;
3663	}
3664	mtx_lock(&ctl_softc->pool_lock);
3665	ctl_softc->num_pools++;
3666	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3667	/*
3668	 * Increment our usage count if this is an external consumer, so we
3669	 * can't get unloaded until the external consumer (most likely a
3670	 * FETD) unloads and frees his pool.
3671	 *
3672	 * XXX KDM will this increment the caller's module use count, or
3673	 * mine?
3674	 */
3675#if 0
3676	if ((pool_type != CTL_POOL_EMERGENCY)
3677	 && (pool_type != CTL_POOL_INTERNAL)
3678	 && (pool_type != CTL_POOL_4OTHERSC))
3679		MOD_INC_USE_COUNT;
3680#endif
3681
3682	mtx_unlock(&ctl_softc->pool_lock);
3683
3684	*npool = pool;
3685
3686bailout:
3687
3688	return (retval);
3689}
3690
3691static int
3692ctl_pool_acquire(struct ctl_io_pool *pool)
3693{
3694
3695	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3696
3697	if (pool->flags & CTL_POOL_FLAG_INVALID)
3698		return (EINVAL);
3699
3700	pool->refcount++;
3701
3702	return (0);
3703}
3704
3705static void
3706ctl_pool_release(struct ctl_io_pool *pool)
3707{
3708	struct ctl_softc *ctl_softc = pool->ctl_softc;
3709	union ctl_io *io;
3710
3711	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3712
3713	if (--pool->refcount != 0)
3714		return;
3715
3716	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3717		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3718			      links);
3719		free(io, M_CTLIO);
3720	}
3721
3722	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3723	ctl_softc->num_pools--;
3724
3725	/*
3726	 * XXX KDM will this decrement the caller's usage count or mine?
3727	 */
3728#if 0
3729	if ((pool->type != CTL_POOL_EMERGENCY)
3730	 && (pool->type != CTL_POOL_INTERNAL)
3731	 && (pool->type != CTL_POOL_4OTHERSC))
3732		MOD_DEC_USE_COUNT;
3733#endif
3734
3735	free(pool, M_CTL);
3736}
3737
3738void
3739ctl_pool_free(struct ctl_io_pool *pool)
3740{
3741	struct ctl_softc *ctl_softc;
3742
3743	if (pool == NULL)
3744		return;
3745
3746	ctl_softc = pool->ctl_softc;
3747	mtx_lock(&ctl_softc->pool_lock);
3748	pool->flags |= CTL_POOL_FLAG_INVALID;
3749	ctl_pool_release(pool);
3750	mtx_unlock(&ctl_softc->pool_lock);
3751}
3752
3753/*
3754 * This routine does not block (except for spinlocks of course).
3755 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3756 * possible.
3757 */
3758union ctl_io *
3759ctl_alloc_io(void *pool_ref)
3760{
3761	union ctl_io *io;
3762	struct ctl_softc *ctl_softc;
3763	struct ctl_io_pool *pool, *npool;
3764	struct ctl_io_pool *emergency_pool;
3765
3766	pool = (struct ctl_io_pool *)pool_ref;
3767
3768	if (pool == NULL) {
3769		printf("%s: pool is NULL\n", __func__);
3770		return (NULL);
3771	}
3772
3773	emergency_pool = NULL;
3774
3775	ctl_softc = pool->ctl_softc;
3776
3777	mtx_lock(&ctl_softc->pool_lock);
3778	/*
3779	 * First, try to get the io structure from the user's pool.
3780	 */
3781	if (ctl_pool_acquire(pool) == 0) {
3782		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3783		if (io != NULL) {
3784			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3785			pool->total_allocated++;
3786			pool->free_ctl_io--;
3787			mtx_unlock(&ctl_softc->pool_lock);
3788			return (io);
3789		} else
3790			ctl_pool_release(pool);
3791	}
3792	/*
3793	 * If he doesn't have any io structures left, search for an
3794	 * emergency pool and grab one from there.
3795	 */
3796	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3797		if (npool->type != CTL_POOL_EMERGENCY)
3798			continue;
3799
3800		if (ctl_pool_acquire(npool) != 0)
3801			continue;
3802
3803		emergency_pool = npool;
3804
3805		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3806		if (io != NULL) {
3807			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3808			npool->total_allocated++;
3809			npool->free_ctl_io--;
3810			mtx_unlock(&ctl_softc->pool_lock);
3811			return (io);
3812		} else
3813			ctl_pool_release(npool);
3814	}
3815
3816	/* Drop the spinlock before we malloc */
3817	mtx_unlock(&ctl_softc->pool_lock);
3818
3819	/*
3820	 * The emergency pool (if it exists) didn't have one, so try an
3821	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3822	 */
3823	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3824	if (io != NULL) {
3825		/*
3826		 * If the emergency pool exists but is empty, add this
3827		 * ctl_io to its list when it gets freed.
3828		 */
3829		if (emergency_pool != NULL) {
3830			mtx_lock(&ctl_softc->pool_lock);
3831			if (ctl_pool_acquire(emergency_pool) == 0) {
3832				io->io_hdr.pool = emergency_pool;
3833				emergency_pool->total_ctl_io++;
3834				/*
3835				 * Need to bump this, otherwise
3836				 * total_allocated and total_freed won't
3837				 * match when we no longer have anything
3838				 * outstanding.
3839				 */
3840				emergency_pool->total_allocated++;
3841			}
3842			mtx_unlock(&ctl_softc->pool_lock);
3843		} else
3844			io->io_hdr.pool = NULL;
3845	}
3846
3847	return (io);
3848}
3849
3850void
3851ctl_free_io(union ctl_io *io)
3852{
3853	if (io == NULL)
3854		return;
3855
3856	/*
3857	 * If this ctl_io has a pool, return it to that pool.
3858	 */
3859	if (io->io_hdr.pool != NULL) {
3860		struct ctl_io_pool *pool;
3861
3862		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3863		mtx_lock(&pool->ctl_softc->pool_lock);
3864		io->io_hdr.io_type = 0xff;
3865		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3866		pool->total_freed++;
3867		pool->free_ctl_io++;
3868		ctl_pool_release(pool);
3869		mtx_unlock(&pool->ctl_softc->pool_lock);
3870	} else {
3871		/*
3872		 * Otherwise, just free it.  We probably malloced it and
3873		 * the emergency pool wasn't available.
3874		 */
3875		free(io, M_CTLIO);
3876	}
3877
3878}
3879
3880void
3881ctl_zero_io(union ctl_io *io)
3882{
3883	void *pool_ref;
3884
3885	if (io == NULL)
3886		return;
3887
3888	/*
3889	 * May need to preserve linked list pointers at some point too.
3890	 */
3891	pool_ref = io->io_hdr.pool;
3892
3893	memset(io, 0, sizeof(*io));
3894
3895	io->io_hdr.pool = pool_ref;
3896}
3897
3898/*
3899 * This routine is currently used for internal copies of ctl_ios that need
3900 * to persist for some reason after we've already returned status to the
3901 * FETD.  (Thus the flag set.)
3902 *
3903 * XXX XXX
3904 * Note that this makes a blind copy of all fields in the ctl_io, except
3905 * for the pool reference.  This includes any memory that has been
3906 * allocated!  That memory will no longer be valid after done has been
3907 * called, so this would be VERY DANGEROUS for command that actually does
3908 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3909 * start and stop commands, which don't transfer any data, so this is not a
3910 * problem.  If it is used for anything else, the caller would also need to
3911 * allocate data buffer space and this routine would need to be modified to
3912 * copy the data buffer(s) as well.
3913 */
3914void
3915ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3916{
3917	void *pool_ref;
3918
3919	if ((src == NULL)
3920	 || (dest == NULL))
3921		return;
3922
3923	/*
3924	 * May need to preserve linked list pointers at some point too.
3925	 */
3926	pool_ref = dest->io_hdr.pool;
3927
3928	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3929
3930	dest->io_hdr.pool = pool_ref;
3931	/*
3932	 * We need to know that this is an internal copy, and doesn't need
3933	 * to get passed back to the FETD that allocated it.
3934	 */
3935	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3936}
3937
3938#ifdef NEEDTOPORT
3939static void
3940ctl_update_power_subpage(struct copan_power_subpage *page)
3941{
3942	int num_luns, num_partitions, config_type;
3943	struct ctl_softc *softc;
3944	cs_BOOL_t aor_present, shelf_50pct_power;
3945	cs_raidset_personality_t rs_type;
3946	int max_active_luns;
3947
3948	softc = control_softc;
3949
3950	/* subtract out the processor LUN */
3951	num_luns = softc->num_luns - 1;
3952	/*
3953	 * Default to 7 LUNs active, which was the only number we allowed
3954	 * in the past.
3955	 */
3956	max_active_luns = 7;
3957
3958	num_partitions = config_GetRsPartitionInfo();
3959	config_type = config_GetConfigType();
3960	shelf_50pct_power = config_GetShelfPowerMode();
3961	aor_present = config_IsAorRsPresent();
3962
3963	rs_type = ddb_GetRsRaidType(1);
3964	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3965	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3966		EPRINT(0, "Unsupported RS type %d!", rs_type);
3967	}
3968
3969
3970	page->total_luns = num_luns;
3971
3972	switch (config_type) {
3973	case 40:
3974		/*
3975		 * In a 40 drive configuration, it doesn't matter what DC
3976		 * cards we have, whether we have AOR enabled or not,
3977		 * partitioning or not, or what type of RAIDset we have.
3978		 * In that scenario, we can power up every LUN we present
3979		 * to the user.
3980		 */
3981		max_active_luns = num_luns;
3982
3983		break;
3984	case 64:
3985		if (shelf_50pct_power == CS_FALSE) {
3986			/* 25% power */
3987			if (aor_present == CS_TRUE) {
3988				if (rs_type ==
3989				     CS_RAIDSET_PERSONALITY_RAID5) {
3990					max_active_luns = 7;
3991				} else if (rs_type ==
3992					 CS_RAIDSET_PERSONALITY_RAID1){
3993					max_active_luns = 14;
3994				} else {
3995					/* XXX KDM now what?? */
3996				}
3997			} else {
3998				if (rs_type ==
3999				     CS_RAIDSET_PERSONALITY_RAID5) {
4000					max_active_luns = 8;
4001				} else if (rs_type ==
4002					 CS_RAIDSET_PERSONALITY_RAID1){
4003					max_active_luns = 16;
4004				} else {
4005					/* XXX KDM now what?? */
4006				}
4007			}
4008		} else {
4009			/* 50% power */
4010			/*
4011			 * With 50% power in a 64 drive configuration, we
4012			 * can power all LUNs we present.
4013			 */
4014			max_active_luns = num_luns;
4015		}
4016		break;
4017	case 112:
4018		if (shelf_50pct_power == CS_FALSE) {
4019			/* 25% power */
4020			if (aor_present == CS_TRUE) {
4021				if (rs_type ==
4022				     CS_RAIDSET_PERSONALITY_RAID5) {
4023					max_active_luns = 7;
4024				} else if (rs_type ==
4025					 CS_RAIDSET_PERSONALITY_RAID1){
4026					max_active_luns = 14;
4027				} else {
4028					/* XXX KDM now what?? */
4029				}
4030			} else {
4031				if (rs_type ==
4032				     CS_RAIDSET_PERSONALITY_RAID5) {
4033					max_active_luns = 8;
4034				} else if (rs_type ==
4035					 CS_RAIDSET_PERSONALITY_RAID1){
4036					max_active_luns = 16;
4037				} else {
4038					/* XXX KDM now what?? */
4039				}
4040			}
4041		} else {
4042			/* 50% power */
4043			if (aor_present == CS_TRUE) {
4044				if (rs_type ==
4045				     CS_RAIDSET_PERSONALITY_RAID5) {
4046					max_active_luns = 14;
4047				} else if (rs_type ==
4048					 CS_RAIDSET_PERSONALITY_RAID1){
4049					/*
4050					 * We're assuming here that disk
4051					 * caching is enabled, and so we're
4052					 * able to power up half of each
4053					 * LUN, and cache all writes.
4054					 */
4055					max_active_luns = num_luns;
4056				} else {
4057					/* XXX KDM now what?? */
4058				}
4059			} else {
4060				if (rs_type ==
4061				     CS_RAIDSET_PERSONALITY_RAID5) {
4062					max_active_luns = 15;
4063				} else if (rs_type ==
4064					 CS_RAIDSET_PERSONALITY_RAID1){
4065					max_active_luns = 30;
4066				} else {
4067					/* XXX KDM now what?? */
4068				}
4069			}
4070		}
4071		break;
4072	default:
4073		/*
4074		 * In this case, we have an unknown configuration, so we
4075		 * just use the default from above.
4076		 */
4077		break;
4078	}
4079
4080	page->max_active_luns = max_active_luns;
4081#if 0
4082	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4083	       page->total_luns, page->max_active_luns);
4084#endif
4085}
4086#endif /* NEEDTOPORT */
4087
4088/*
4089 * This routine could be used in the future to load default and/or saved
4090 * mode page parameters for a particuar lun.
4091 */
4092static int
4093ctl_init_page_index(struct ctl_lun *lun)
4094{
4095	int i;
4096	struct ctl_page_index *page_index;
4097	struct ctl_softc *softc;
4098
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
4248			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4249				panic("invalid subpage value %d",
4250				      page_index->subpage);
4251			/*
4252			 * Defaults should be okay here, no calculations
4253			 * needed.
4254			 */
4255			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4256			       &caching_page_default,
4257			       sizeof(caching_page_default));
4258			memcpy(&lun->mode_pages.caching_page[
4259			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4260			       sizeof(caching_page_changeable));
4261			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4262			       &caching_page_default,
4263			       sizeof(caching_page_default));
4264			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4265			       &caching_page_default,
4266			       sizeof(caching_page_default));
4267			page_index->page_data =
4268				(uint8_t *)lun->mode_pages.caching_page;
4269			break;
4270		}
4271		case SMS_CONTROL_MODE_PAGE: {
4272
4273			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4274				panic("invalid subpage value %d",
4275				      page_index->subpage);
4276
4277			/*
4278			 * Defaults should be okay here, no calculations
4279			 * needed.
4280			 */
4281			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4282			       &control_page_default,
4283			       sizeof(control_page_default));
4284			memcpy(&lun->mode_pages.control_page[
4285			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4286			       sizeof(control_page_changeable));
4287			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4288			       &control_page_default,
4289			       sizeof(control_page_default));
4290			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4291			       &control_page_default,
4292			       sizeof(control_page_default));
4293			page_index->page_data =
4294				(uint8_t *)lun->mode_pages.control_page;
4295			break;
4296
4297		}
4298		case SMS_VENDOR_SPECIFIC_PAGE:{
4299			switch (page_index->subpage) {
4300			case PWR_SUBPAGE_CODE: {
4301				struct copan_power_subpage *current_page,
4302							   *saved_page;
4303
4304				memcpy(&lun->mode_pages.power_subpage[
4305				       CTL_PAGE_CURRENT],
4306				       &power_page_default,
4307				       sizeof(power_page_default));
4308				memcpy(&lun->mode_pages.power_subpage[
4309				       CTL_PAGE_CHANGEABLE],
4310				       &power_page_changeable,
4311				       sizeof(power_page_changeable));
4312				memcpy(&lun->mode_pages.power_subpage[
4313				       CTL_PAGE_DEFAULT],
4314				       &power_page_default,
4315				       sizeof(power_page_default));
4316				memcpy(&lun->mode_pages.power_subpage[
4317				       CTL_PAGE_SAVED],
4318				       &power_page_default,
4319				       sizeof(power_page_default));
4320				page_index->page_data =
4321				    (uint8_t *)lun->mode_pages.power_subpage;
4322
4323				current_page = (struct copan_power_subpage *)
4324					(page_index->page_data +
4325					 (page_index->page_len *
4326					  CTL_PAGE_CURRENT));
4327			        saved_page = (struct copan_power_subpage *)
4328				        (page_index->page_data +
4329					 (page_index->page_len *
4330					  CTL_PAGE_SAVED));
4331				break;
4332			}
4333			case APS_SUBPAGE_CODE: {
4334				struct copan_aps_subpage *current_page,
4335							 *saved_page;
4336
4337				// This gets set multiple times but
4338				// it should always be the same. It's
4339				// only done during init so who cares.
4340				index_to_aps_page = i;
4341
4342				memcpy(&lun->mode_pages.aps_subpage[
4343				       CTL_PAGE_CURRENT],
4344				       &aps_page_default,
4345				       sizeof(aps_page_default));
4346				memcpy(&lun->mode_pages.aps_subpage[
4347				       CTL_PAGE_CHANGEABLE],
4348				       &aps_page_changeable,
4349				       sizeof(aps_page_changeable));
4350				memcpy(&lun->mode_pages.aps_subpage[
4351				       CTL_PAGE_DEFAULT],
4352				       &aps_page_default,
4353				       sizeof(aps_page_default));
4354				memcpy(&lun->mode_pages.aps_subpage[
4355				       CTL_PAGE_SAVED],
4356				       &aps_page_default,
4357				       sizeof(aps_page_default));
4358				page_index->page_data =
4359					(uint8_t *)lun->mode_pages.aps_subpage;
4360
4361				current_page = (struct copan_aps_subpage *)
4362					(page_index->page_data +
4363					 (page_index->page_len *
4364					  CTL_PAGE_CURRENT));
4365				saved_page = (struct copan_aps_subpage *)
4366					(page_index->page_data +
4367					 (page_index->page_len *
4368					  CTL_PAGE_SAVED));
4369				break;
4370			}
4371			case DBGCNF_SUBPAGE_CODE: {
4372				struct copan_debugconf_subpage *current_page,
4373							       *saved_page;
4374
4375				memcpy(&lun->mode_pages.debugconf_subpage[
4376				       CTL_PAGE_CURRENT],
4377				       &debugconf_page_default,
4378				       sizeof(debugconf_page_default));
4379				memcpy(&lun->mode_pages.debugconf_subpage[
4380				       CTL_PAGE_CHANGEABLE],
4381				       &debugconf_page_changeable,
4382				       sizeof(debugconf_page_changeable));
4383				memcpy(&lun->mode_pages.debugconf_subpage[
4384				       CTL_PAGE_DEFAULT],
4385				       &debugconf_page_default,
4386				       sizeof(debugconf_page_default));
4387				memcpy(&lun->mode_pages.debugconf_subpage[
4388				       CTL_PAGE_SAVED],
4389				       &debugconf_page_default,
4390				       sizeof(debugconf_page_default));
4391				page_index->page_data =
4392					(uint8_t *)lun->mode_pages.debugconf_subpage;
4393
4394				current_page = (struct copan_debugconf_subpage *)
4395					(page_index->page_data +
4396					 (page_index->page_len *
4397					  CTL_PAGE_CURRENT));
4398				saved_page = (struct copan_debugconf_subpage *)
4399					(page_index->page_data +
4400					 (page_index->page_len *
4401					  CTL_PAGE_SAVED));
4402				break;
4403			}
4404			default:
4405				panic("invalid subpage value %d",
4406				      page_index->subpage);
4407				break;
4408			}
4409   			break;
4410		}
4411		default:
4412			panic("invalid page value %d",
4413			      page_index->page_code & SMPH_PC_MASK);
4414			break;
4415    	}
4416	}
4417
4418	return (CTL_RETVAL_COMPLETE);
4419}
4420
4421/*
4422 * LUN allocation.
4423 *
4424 * Requirements:
4425 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4426 *   wants us to allocate the LUN and he can block.
4427 * - ctl_softc is always set
4428 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4429 *
4430 * Returns 0 for success, non-zero (errno) for failure.
4431 */
4432static int
4433ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4434	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4435{
4436	struct ctl_lun *nlun, *lun;
4437	struct ctl_port *port;
4438	struct scsi_vpd_id_descriptor *desc;
4439	struct scsi_vpd_id_t10 *t10id;
4440	const char *eui, *naa, *scsiname, *vendor;
4441	int lun_number, i, lun_malloced;
4442	int devidlen, idlen1, idlen2 = 0, len;
4443
4444	if (be_lun == NULL)
4445		return (EINVAL);
4446
4447	/*
4448	 * We currently only support Direct Access or Processor LUN types.
4449	 */
4450	switch (be_lun->lun_type) {
4451	case T_DIRECT:
4452		break;
4453	case T_PROCESSOR:
4454		break;
4455	case T_SEQUENTIAL:
4456	case T_CHANGER:
4457	default:
4458		be_lun->lun_config_status(be_lun->be_lun,
4459					  CTL_LUN_CONFIG_FAILURE);
4460		break;
4461	}
4462	if (ctl_lun == NULL) {
4463		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4464		lun_malloced = 1;
4465	} else {
4466		lun_malloced = 0;
4467		lun = ctl_lun;
4468	}
4469
4470	memset(lun, 0, sizeof(*lun));
4471	if (lun_malloced)
4472		lun->flags = CTL_LUN_MALLOCED;
4473
4474	/* Generate LUN ID. */
4475	devidlen = max(CTL_DEVID_MIN_LEN,
4476	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4477	idlen1 = sizeof(*t10id) + devidlen;
4478	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4479	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4480	if (scsiname != NULL) {
4481		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4482		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4483	}
4484	eui = ctl_get_opt(&be_lun->options, "eui");
4485	if (eui != NULL) {
4486		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4487	}
4488	naa = ctl_get_opt(&be_lun->options, "naa");
4489	if (naa != NULL) {
4490		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4491	}
4492	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4493	    M_CTL, M_WAITOK | M_ZERO);
4494	lun->lun_devid->len = len;
4495	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4496	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4497	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4498	desc->length = idlen1;
4499	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4500	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4501	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4502		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4503	} else {
4504		strncpy(t10id->vendor, vendor,
4505		    min(sizeof(t10id->vendor), strlen(vendor)));
4506	}
4507	strncpy((char *)t10id->vendor_spec_id,
4508	    (char *)be_lun->device_id, devidlen);
4509	if (scsiname != NULL) {
4510		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4511		    desc->length);
4512		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4513		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4514		    SVPD_ID_TYPE_SCSI_NAME;
4515		desc->length = idlen2;
4516		strlcpy(desc->identifier, scsiname, idlen2);
4517	}
4518	if (eui != NULL) {
4519		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4520		    desc->length);
4521		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4522		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4523		    SVPD_ID_TYPE_EUI64;
4524		desc->length = 8;
4525		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4526	}
4527	if (naa != 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_NAA;
4533		desc->length = 8;
4534		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4535	}
4536
4537	mtx_lock(&ctl_softc->ctl_lock);
4538	/*
4539	 * See if the caller requested a particular LUN number.  If so, see
4540	 * if it is available.  Otherwise, allocate the first available LUN.
4541	 */
4542	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4543		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4544		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4545			mtx_unlock(&ctl_softc->ctl_lock);
4546			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4547				printf("ctl: requested LUN ID %d is higher "
4548				       "than CTL_MAX_LUNS - 1 (%d)\n",
4549				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4550			} else {
4551				/*
4552				 * XXX KDM return an error, or just assign
4553				 * another LUN ID in this case??
4554				 */
4555				printf("ctl: requested LUN ID %d is already "
4556				       "in use\n", be_lun->req_lun_id);
4557			}
4558			if (lun->flags & CTL_LUN_MALLOCED)
4559				free(lun, M_CTL);
4560			be_lun->lun_config_status(be_lun->be_lun,
4561						  CTL_LUN_CONFIG_FAILURE);
4562			return (ENOSPC);
4563		}
4564		lun_number = be_lun->req_lun_id;
4565	} else {
4566		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4567		if (lun_number == -1) {
4568			mtx_unlock(&ctl_softc->ctl_lock);
4569			printf("ctl: can't allocate LUN on target %ju, out of "
4570			       "LUNs\n", (uintmax_t)target_id.id);
4571			if (lun->flags & CTL_LUN_MALLOCED)
4572				free(lun, M_CTL);
4573			be_lun->lun_config_status(be_lun->be_lun,
4574						  CTL_LUN_CONFIG_FAILURE);
4575			return (ENOSPC);
4576		}
4577	}
4578	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4579
4580	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4581	lun->target = target_id;
4582	lun->lun = lun_number;
4583	lun->be_lun = be_lun;
4584	/*
4585	 * The processor LUN is always enabled.  Disk LUNs come on line
4586	 * disabled, and must be enabled by the backend.
4587	 */
4588	lun->flags |= CTL_LUN_DISABLED;
4589	lun->backend = be_lun->be;
4590	be_lun->ctl_lun = lun;
4591	be_lun->lun_id = lun_number;
4592	atomic_add_int(&be_lun->be->num_luns, 1);
4593	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4594		lun->flags |= CTL_LUN_STOPPED;
4595
4596	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4597		lun->flags |= CTL_LUN_INOPERABLE;
4598
4599	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4600		lun->flags |= CTL_LUN_PRIMARY_SC;
4601
4602	lun->ctl_softc = ctl_softc;
4603	TAILQ_INIT(&lun->ooa_queue);
4604	TAILQ_INIT(&lun->blocked_queue);
4605	STAILQ_INIT(&lun->error_list);
4606	ctl_tpc_lun_init(lun);
4607
4608	/*
4609	 * Initialize the mode page index.
4610	 */
4611	ctl_init_page_index(lun);
4612
4613	/*
4614	 * Set the poweron UA for all initiators on this LUN only.
4615	 */
4616	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4617		lun->pending_ua[i] = CTL_UA_POWERON;
4618
4619	/*
4620	 * Now, before we insert this lun on the lun list, set the lun
4621	 * inventory changed UA for all other luns.
4622	 */
4623	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4624		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4625			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4626		}
4627	}
4628
4629	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4630
4631	ctl_softc->ctl_luns[lun_number] = lun;
4632
4633	ctl_softc->num_luns++;
4634
4635	/* Setup statistics gathering */
4636	lun->stats.device_type = be_lun->lun_type;
4637	lun->stats.lun_number = lun_number;
4638	if (lun->stats.device_type == T_DIRECT)
4639		lun->stats.blocksize = be_lun->blocksize;
4640	else
4641		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4642	for (i = 0;i < CTL_MAX_PORTS;i++)
4643		lun->stats.ports[i].targ_port = i;
4644
4645	mtx_unlock(&ctl_softc->ctl_lock);
4646
4647	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4648
4649	/*
4650	 * Run through each registered FETD and bring it online if it isn't
4651	 * already.  Enable the target ID if it hasn't been enabled, and
4652	 * enable this particular LUN.
4653	 */
4654	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4655		int retval;
4656
4657		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4658		if (retval != 0) {
4659			printf("ctl_alloc_lun: FETD %s port %d returned error "
4660			       "%d for lun_enable on target %ju lun %d\n",
4661			       port->port_name, port->targ_port, retval,
4662			       (uintmax_t)target_id.id, lun_number);
4663		} else
4664			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4665	}
4666	return (0);
4667}
4668
4669/*
4670 * Delete a LUN.
4671 * Assumptions:
4672 * - LUN has already been marked invalid and any pending I/O has been taken
4673 *   care of.
4674 */
4675static int
4676ctl_free_lun(struct ctl_lun *lun)
4677{
4678	struct ctl_softc *softc;
4679#if 0
4680	struct ctl_port *port;
4681#endif
4682	struct ctl_lun *nlun;
4683	int i;
4684
4685	softc = lun->ctl_softc;
4686
4687	mtx_assert(&softc->ctl_lock, MA_OWNED);
4688
4689	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4690
4691	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4692
4693	softc->ctl_luns[lun->lun] = NULL;
4694
4695	if (!TAILQ_EMPTY(&lun->ooa_queue))
4696		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4697
4698	softc->num_luns--;
4699
4700	/*
4701	 * XXX KDM this scheme only works for a single target/multiple LUN
4702	 * setup.  It needs to be revamped for a multiple target scheme.
4703	 *
4704	 * XXX KDM this results in port->lun_disable() getting called twice,
4705	 * once when ctl_disable_lun() is called, and a second time here.
4706	 * We really need to re-think the LUN disable semantics.  There
4707	 * should probably be several steps/levels to LUN removal:
4708	 *  - disable
4709	 *  - invalidate
4710	 *  - free
4711 	 *
4712	 * Right now we only have a disable method when communicating to
4713	 * the front end ports, at least for individual LUNs.
4714	 */
4715#if 0
4716	STAILQ_FOREACH(port, &softc->port_list, links) {
4717		int retval;
4718
4719		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4720					 lun->lun);
4721		if (retval != 0) {
4722			printf("ctl_free_lun: FETD %s port %d returned error "
4723			       "%d for lun_disable on target %ju lun %jd\n",
4724			       port->port_name, port->targ_port, retval,
4725			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4726		}
4727
4728		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4729			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4730
4731			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4732			if (retval != 0) {
4733				printf("ctl_free_lun: FETD %s port %d "
4734				       "returned error %d for targ_disable on "
4735				       "target %ju\n", port->port_name,
4736				       port->targ_port, retval,
4737				       (uintmax_t)lun->target.id);
4738			} else
4739				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4740
4741			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4742				continue;
4743
4744#if 0
4745			port->port_offline(port->onoff_arg);
4746			port->status &= ~CTL_PORT_STATUS_ONLINE;
4747#endif
4748		}
4749	}
4750#endif
4751
4752	/*
4753	 * Tell the backend to free resources, if this LUN has a backend.
4754	 */
4755	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4756	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4757
4758	ctl_tpc_lun_shutdown(lun);
4759	mtx_destroy(&lun->lun_lock);
4760	free(lun->lun_devid, M_CTL);
4761	if (lun->flags & CTL_LUN_MALLOCED)
4762		free(lun, M_CTL);
4763
4764	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4765		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4766			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4767		}
4768	}
4769
4770	return (0);
4771}
4772
4773static void
4774ctl_create_lun(struct ctl_be_lun *be_lun)
4775{
4776	struct ctl_softc *ctl_softc;
4777
4778	ctl_softc = control_softc;
4779
4780	/*
4781	 * ctl_alloc_lun() should handle all potential failure cases.
4782	 */
4783	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4784}
4785
4786int
4787ctl_add_lun(struct ctl_be_lun *be_lun)
4788{
4789	struct ctl_softc *ctl_softc = control_softc;
4790
4791	mtx_lock(&ctl_softc->ctl_lock);
4792	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4793	mtx_unlock(&ctl_softc->ctl_lock);
4794	wakeup(&ctl_softc->pending_lun_queue);
4795
4796	return (0);
4797}
4798
4799int
4800ctl_enable_lun(struct ctl_be_lun *be_lun)
4801{
4802	struct ctl_softc *ctl_softc;
4803	struct ctl_port *port, *nport;
4804	struct ctl_lun *lun;
4805	int retval;
4806
4807	ctl_softc = control_softc;
4808
4809	lun = (struct ctl_lun *)be_lun->ctl_lun;
4810
4811	mtx_lock(&ctl_softc->ctl_lock);
4812	mtx_lock(&lun->lun_lock);
4813	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4814		/*
4815		 * eh?  Why did we get called if the LUN is already
4816		 * enabled?
4817		 */
4818		mtx_unlock(&lun->lun_lock);
4819		mtx_unlock(&ctl_softc->ctl_lock);
4820		return (0);
4821	}
4822	lun->flags &= ~CTL_LUN_DISABLED;
4823	mtx_unlock(&lun->lun_lock);
4824
4825	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4826		nport = STAILQ_NEXT(port, links);
4827
4828		/*
4829		 * Drop the lock while we call the FETD's enable routine.
4830		 * This can lead to a callback into CTL (at least in the
4831		 * case of the internal initiator frontend.
4832		 */
4833		mtx_unlock(&ctl_softc->ctl_lock);
4834		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4835		mtx_lock(&ctl_softc->ctl_lock);
4836		if (retval != 0) {
4837			printf("%s: FETD %s port %d returned error "
4838			       "%d for lun_enable on target %ju lun %jd\n",
4839			       __func__, port->port_name, port->targ_port, retval,
4840			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4841		}
4842#if 0
4843		 else {
4844            /* NOTE:  TODO:  why does lun enable affect port status? */
4845			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4846		}
4847#endif
4848	}
4849
4850	mtx_unlock(&ctl_softc->ctl_lock);
4851
4852	return (0);
4853}
4854
4855int
4856ctl_disable_lun(struct ctl_be_lun *be_lun)
4857{
4858	struct ctl_softc *ctl_softc;
4859	struct ctl_port *port;
4860	struct ctl_lun *lun;
4861	int retval;
4862
4863	ctl_softc = control_softc;
4864
4865	lun = (struct ctl_lun *)be_lun->ctl_lun;
4866
4867	mtx_lock(&ctl_softc->ctl_lock);
4868	mtx_lock(&lun->lun_lock);
4869	if (lun->flags & CTL_LUN_DISABLED) {
4870		mtx_unlock(&lun->lun_lock);
4871		mtx_unlock(&ctl_softc->ctl_lock);
4872		return (0);
4873	}
4874	lun->flags |= CTL_LUN_DISABLED;
4875	mtx_unlock(&lun->lun_lock);
4876
4877	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4878		mtx_unlock(&ctl_softc->ctl_lock);
4879		/*
4880		 * Drop the lock before we call the frontend's disable
4881		 * routine, to avoid lock order reversals.
4882		 *
4883		 * XXX KDM what happens if the frontend list changes while
4884		 * we're traversing it?  It's unlikely, but should be handled.
4885		 */
4886		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4887					 lun->lun);
4888		mtx_lock(&ctl_softc->ctl_lock);
4889		if (retval != 0) {
4890			printf("ctl_alloc_lun: FETD %s port %d returned error "
4891			       "%d for lun_disable on target %ju lun %jd\n",
4892			       port->port_name, port->targ_port, retval,
4893			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4894		}
4895	}
4896
4897	mtx_unlock(&ctl_softc->ctl_lock);
4898
4899	return (0);
4900}
4901
4902int
4903ctl_start_lun(struct ctl_be_lun *be_lun)
4904{
4905	struct ctl_softc *ctl_softc;
4906	struct ctl_lun *lun;
4907
4908	ctl_softc = control_softc;
4909
4910	lun = (struct ctl_lun *)be_lun->ctl_lun;
4911
4912	mtx_lock(&lun->lun_lock);
4913	lun->flags &= ~CTL_LUN_STOPPED;
4914	mtx_unlock(&lun->lun_lock);
4915
4916	return (0);
4917}
4918
4919int
4920ctl_stop_lun(struct ctl_be_lun *be_lun)
4921{
4922	struct ctl_softc *ctl_softc;
4923	struct ctl_lun *lun;
4924
4925	ctl_softc = control_softc;
4926
4927	lun = (struct ctl_lun *)be_lun->ctl_lun;
4928
4929	mtx_lock(&lun->lun_lock);
4930	lun->flags |= CTL_LUN_STOPPED;
4931	mtx_unlock(&lun->lun_lock);
4932
4933	return (0);
4934}
4935
4936int
4937ctl_lun_offline(struct ctl_be_lun *be_lun)
4938{
4939	struct ctl_softc *ctl_softc;
4940	struct ctl_lun *lun;
4941
4942	ctl_softc = control_softc;
4943
4944	lun = (struct ctl_lun *)be_lun->ctl_lun;
4945
4946	mtx_lock(&lun->lun_lock);
4947	lun->flags |= CTL_LUN_OFFLINE;
4948	mtx_unlock(&lun->lun_lock);
4949
4950	return (0);
4951}
4952
4953int
4954ctl_lun_online(struct ctl_be_lun *be_lun)
4955{
4956	struct ctl_softc *ctl_softc;
4957	struct ctl_lun *lun;
4958
4959	ctl_softc = control_softc;
4960
4961	lun = (struct ctl_lun *)be_lun->ctl_lun;
4962
4963	mtx_lock(&lun->lun_lock);
4964	lun->flags &= ~CTL_LUN_OFFLINE;
4965	mtx_unlock(&lun->lun_lock);
4966
4967	return (0);
4968}
4969
4970int
4971ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4972{
4973	struct ctl_softc *ctl_softc;
4974	struct ctl_lun *lun;
4975
4976	ctl_softc = control_softc;
4977
4978	lun = (struct ctl_lun *)be_lun->ctl_lun;
4979
4980	mtx_lock(&lun->lun_lock);
4981
4982	/*
4983	 * The LUN needs to be disabled before it can be marked invalid.
4984	 */
4985	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4986		mtx_unlock(&lun->lun_lock);
4987		return (-1);
4988	}
4989	/*
4990	 * Mark the LUN invalid.
4991	 */
4992	lun->flags |= CTL_LUN_INVALID;
4993
4994	/*
4995	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4996	 * If we have something in the OOA queue, we'll free it when the
4997	 * last I/O completes.
4998	 */
4999	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5000		mtx_unlock(&lun->lun_lock);
5001		mtx_lock(&ctl_softc->ctl_lock);
5002		ctl_free_lun(lun);
5003		mtx_unlock(&ctl_softc->ctl_lock);
5004	} else
5005		mtx_unlock(&lun->lun_lock);
5006
5007	return (0);
5008}
5009
5010int
5011ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5012{
5013	struct ctl_softc *ctl_softc;
5014	struct ctl_lun *lun;
5015
5016	ctl_softc = control_softc;
5017	lun = (struct ctl_lun *)be_lun->ctl_lun;
5018
5019	mtx_lock(&lun->lun_lock);
5020	lun->flags |= CTL_LUN_INOPERABLE;
5021	mtx_unlock(&lun->lun_lock);
5022
5023	return (0);
5024}
5025
5026int
5027ctl_lun_operable(struct ctl_be_lun *be_lun)
5028{
5029	struct ctl_softc *ctl_softc;
5030	struct ctl_lun *lun;
5031
5032	ctl_softc = control_softc;
5033	lun = (struct ctl_lun *)be_lun->ctl_lun;
5034
5035	mtx_lock(&lun->lun_lock);
5036	lun->flags &= ~CTL_LUN_INOPERABLE;
5037	mtx_unlock(&lun->lun_lock);
5038
5039	return (0);
5040}
5041
5042int
5043ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5044		   int lock)
5045{
5046	struct ctl_softc *softc;
5047	struct ctl_lun *lun;
5048	struct copan_aps_subpage *current_sp;
5049	struct ctl_page_index *page_index;
5050	int i;
5051
5052	softc = control_softc;
5053
5054	mtx_lock(&softc->ctl_lock);
5055
5056	lun = (struct ctl_lun *)be_lun->ctl_lun;
5057	mtx_lock(&lun->lun_lock);
5058
5059	page_index = NULL;
5060	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5061		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5062		     APS_PAGE_CODE)
5063			continue;
5064
5065		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5066			continue;
5067		page_index = &lun->mode_pages.index[i];
5068	}
5069
5070	if (page_index == NULL) {
5071		mtx_unlock(&lun->lun_lock);
5072		mtx_unlock(&softc->ctl_lock);
5073		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5074		       (uintmax_t)lun->lun);
5075		return (1);
5076	}
5077#if 0
5078	if ((softc->aps_locked_lun != 0)
5079	 && (softc->aps_locked_lun != lun->lun)) {
5080		printf("%s: attempt to lock LUN %llu when %llu is already "
5081		       "locked\n");
5082		mtx_unlock(&lun->lun_lock);
5083		mtx_unlock(&softc->ctl_lock);
5084		return (1);
5085	}
5086#endif
5087
5088	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5089		(page_index->page_len * CTL_PAGE_CURRENT));
5090
5091	if (lock != 0) {
5092		current_sp->lock_active = APS_LOCK_ACTIVE;
5093		softc->aps_locked_lun = lun->lun;
5094	} else {
5095		current_sp->lock_active = 0;
5096		softc->aps_locked_lun = 0;
5097	}
5098
5099
5100	/*
5101	 * If we're in HA mode, try to send the lock message to the other
5102	 * side.
5103	 */
5104	if (ctl_is_single == 0) {
5105		int isc_retval;
5106		union ctl_ha_msg lock_msg;
5107
5108		lock_msg.hdr.nexus = *nexus;
5109		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5110		if (lock != 0)
5111			lock_msg.aps.lock_flag = 1;
5112		else
5113			lock_msg.aps.lock_flag = 0;
5114		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5115					 sizeof(lock_msg), 0);
5116		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5117			printf("%s: APS (lock=%d) error returned from "
5118			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5119			mtx_unlock(&lun->lun_lock);
5120			mtx_unlock(&softc->ctl_lock);
5121			return (1);
5122		}
5123	}
5124
5125	mtx_unlock(&lun->lun_lock);
5126	mtx_unlock(&softc->ctl_lock);
5127
5128	return (0);
5129}
5130
5131void
5132ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5133{
5134	struct ctl_lun *lun;
5135	struct ctl_softc *softc;
5136	int i;
5137
5138	softc = control_softc;
5139
5140	lun = (struct ctl_lun *)be_lun->ctl_lun;
5141
5142	mtx_lock(&lun->lun_lock);
5143
5144	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5145		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5146
5147	mtx_unlock(&lun->lun_lock);
5148}
5149
5150/*
5151 * Backend "memory move is complete" callback for requests that never
5152 * make it down to say RAIDCore's configuration code.
5153 */
5154int
5155ctl_config_move_done(union ctl_io *io)
5156{
5157	int retval;
5158
5159	retval = CTL_RETVAL_COMPLETE;
5160
5161
5162	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5163	/*
5164	 * XXX KDM this shouldn't happen, but what if it does?
5165	 */
5166	if (io->io_hdr.io_type != CTL_IO_SCSI)
5167		panic("I/O type isn't CTL_IO_SCSI!");
5168
5169	if ((io->io_hdr.port_status == 0)
5170	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5171	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5172		io->io_hdr.status = CTL_SUCCESS;
5173	else if ((io->io_hdr.port_status != 0)
5174	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5175	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5176		/*
5177		 * For hardware error sense keys, the sense key
5178		 * specific value is defined to be a retry count,
5179		 * but we use it to pass back an internal FETD
5180		 * error code.  XXX KDM  Hopefully the FETD is only
5181		 * using 16 bits for an error code, since that's
5182		 * all the space we have in the sks field.
5183		 */
5184		ctl_set_internal_failure(&io->scsiio,
5185					 /*sks_valid*/ 1,
5186					 /*retry_count*/
5187					 io->io_hdr.port_status);
5188		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5189			free(io->scsiio.kern_data_ptr, M_CTL);
5190		ctl_done(io);
5191		goto bailout;
5192	}
5193
5194	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5195	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5196	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5197		/*
5198		 * XXX KDM just assuming a single pointer here, and not a
5199		 * S/G list.  If we start using S/G lists for config data,
5200		 * we'll need to know how to clean them up here as well.
5201		 */
5202		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5203			free(io->scsiio.kern_data_ptr, M_CTL);
5204		/* Hopefully the user has already set the status... */
5205		ctl_done(io);
5206	} else {
5207		/*
5208		 * XXX KDM now we need to continue data movement.  Some
5209		 * options:
5210		 * - call ctl_scsiio() again?  We don't do this for data
5211		 *   writes, because for those at least we know ahead of
5212		 *   time where the write will go and how long it is.  For
5213		 *   config writes, though, that information is largely
5214		 *   contained within the write itself, thus we need to
5215		 *   parse out the data again.
5216		 *
5217		 * - Call some other function once the data is in?
5218		 */
5219
5220		/*
5221		 * XXX KDM call ctl_scsiio() again for now, and check flag
5222		 * bits to see whether we're allocated or not.
5223		 */
5224		retval = ctl_scsiio(&io->scsiio);
5225	}
5226bailout:
5227	return (retval);
5228}
5229
5230/*
5231 * This gets called by a backend driver when it is done with a
5232 * data_submit method.
5233 */
5234void
5235ctl_data_submit_done(union ctl_io *io)
5236{
5237	/*
5238	 * If the IO_CONT flag is set, we need to call the supplied
5239	 * function to continue processing the I/O, instead of completing
5240	 * the I/O just yet.
5241	 *
5242	 * If there is an error, though, we don't want to keep processing.
5243	 * Instead, just send status back to the initiator.
5244	 */
5245	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5246	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5247	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5248	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5249		io->scsiio.io_cont(io);
5250		return;
5251	}
5252	ctl_done(io);
5253}
5254
5255/*
5256 * This gets called by a backend driver when it is done with a
5257 * configuration write.
5258 */
5259void
5260ctl_config_write_done(union ctl_io *io)
5261{
5262	/*
5263	 * If the IO_CONT flag is set, we need to call the supplied
5264	 * function to continue processing the I/O, instead of completing
5265	 * the I/O just yet.
5266	 *
5267	 * If there is an error, though, we don't want to keep processing.
5268	 * Instead, just send status back to the initiator.
5269	 */
5270	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5271	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5272	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5273		io->scsiio.io_cont(io);
5274		return;
5275	}
5276	/*
5277	 * Since a configuration write can be done for commands that actually
5278	 * have data allocated, like write buffer, and commands that have
5279	 * no data, like start/stop unit, we need to check here.
5280	 */
5281	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5282		free(io->scsiio.kern_data_ptr, M_CTL);
5283	ctl_done(io);
5284}
5285
5286/*
5287 * SCSI release command.
5288 */
5289int
5290ctl_scsi_release(struct ctl_scsiio *ctsio)
5291{
5292	int length, longid, thirdparty_id, resv_id;
5293	struct ctl_softc *ctl_softc;
5294	struct ctl_lun *lun;
5295
5296	length = 0;
5297	resv_id = 0;
5298
5299	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5300
5301	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5302	ctl_softc = control_softc;
5303
5304	switch (ctsio->cdb[0]) {
5305	case RELEASE_10: {
5306		struct scsi_release_10 *cdb;
5307
5308		cdb = (struct scsi_release_10 *)ctsio->cdb;
5309
5310		if (cdb->byte2 & SR10_LONGID)
5311			longid = 1;
5312		else
5313			thirdparty_id = cdb->thirdparty_id;
5314
5315		resv_id = cdb->resv_id;
5316		length = scsi_2btoul(cdb->length);
5317		break;
5318	}
5319	}
5320
5321
5322	/*
5323	 * XXX KDM right now, we only support LUN reservation.  We don't
5324	 * support 3rd party reservations, or extent reservations, which
5325	 * might actually need the parameter list.  If we've gotten this
5326	 * far, we've got a LUN reservation.  Anything else got kicked out
5327	 * above.  So, according to SPC, ignore the length.
5328	 */
5329	length = 0;
5330
5331	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5332	 && (length > 0)) {
5333		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5334		ctsio->kern_data_len = length;
5335		ctsio->kern_total_len = length;
5336		ctsio->kern_data_resid = 0;
5337		ctsio->kern_rel_offset = 0;
5338		ctsio->kern_sg_entries = 0;
5339		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5340		ctsio->be_move_done = ctl_config_move_done;
5341		ctl_datamove((union ctl_io *)ctsio);
5342
5343		return (CTL_RETVAL_COMPLETE);
5344	}
5345
5346	if (length > 0)
5347		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5348
5349	mtx_lock(&lun->lun_lock);
5350
5351	/*
5352	 * According to SPC, it is not an error for an intiator to attempt
5353	 * to release a reservation on a LUN that isn't reserved, or that
5354	 * is reserved by another initiator.  The reservation can only be
5355	 * released, though, by the initiator who made it or by one of
5356	 * several reset type events.
5357	 */
5358	if (lun->flags & CTL_LUN_RESERVED) {
5359		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5360		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5361		 && (ctsio->io_hdr.nexus.targ_target.id ==
5362		     lun->rsv_nexus.targ_target.id)) {
5363			lun->flags &= ~CTL_LUN_RESERVED;
5364		}
5365	}
5366
5367	mtx_unlock(&lun->lun_lock);
5368
5369	ctsio->scsi_status = SCSI_STATUS_OK;
5370	ctsio->io_hdr.status = CTL_SUCCESS;
5371
5372	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5373		free(ctsio->kern_data_ptr, M_CTL);
5374		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5375	}
5376
5377	ctl_done((union ctl_io *)ctsio);
5378	return (CTL_RETVAL_COMPLETE);
5379}
5380
5381int
5382ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5383{
5384	int extent, thirdparty, longid;
5385	int resv_id, length;
5386	uint64_t thirdparty_id;
5387	struct ctl_softc *ctl_softc;
5388	struct ctl_lun *lun;
5389
5390	extent = 0;
5391	thirdparty = 0;
5392	longid = 0;
5393	resv_id = 0;
5394	length = 0;
5395	thirdparty_id = 0;
5396
5397	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5398
5399	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5400	ctl_softc = control_softc;
5401
5402	switch (ctsio->cdb[0]) {
5403	case RESERVE_10: {
5404		struct scsi_reserve_10 *cdb;
5405
5406		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5407
5408		if (cdb->byte2 & SR10_LONGID)
5409			longid = 1;
5410		else
5411			thirdparty_id = cdb->thirdparty_id;
5412
5413		resv_id = cdb->resv_id;
5414		length = scsi_2btoul(cdb->length);
5415		break;
5416	}
5417	}
5418
5419	/*
5420	 * XXX KDM right now, we only support LUN reservation.  We don't
5421	 * support 3rd party reservations, or extent reservations, which
5422	 * might actually need the parameter list.  If we've gotten this
5423	 * far, we've got a LUN reservation.  Anything else got kicked out
5424	 * above.  So, according to SPC, ignore the length.
5425	 */
5426	length = 0;
5427
5428	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5429	 && (length > 0)) {
5430		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5431		ctsio->kern_data_len = length;
5432		ctsio->kern_total_len = length;
5433		ctsio->kern_data_resid = 0;
5434		ctsio->kern_rel_offset = 0;
5435		ctsio->kern_sg_entries = 0;
5436		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5437		ctsio->be_move_done = ctl_config_move_done;
5438		ctl_datamove((union ctl_io *)ctsio);
5439
5440		return (CTL_RETVAL_COMPLETE);
5441	}
5442
5443	if (length > 0)
5444		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5445
5446	mtx_lock(&lun->lun_lock);
5447	if (lun->flags & CTL_LUN_RESERVED) {
5448		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5449		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5450		 || (ctsio->io_hdr.nexus.targ_target.id !=
5451		     lun->rsv_nexus.targ_target.id)) {
5452			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5453			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5454			goto bailout;
5455		}
5456	}
5457
5458	lun->flags |= CTL_LUN_RESERVED;
5459	lun->rsv_nexus = ctsio->io_hdr.nexus;
5460
5461	ctsio->scsi_status = SCSI_STATUS_OK;
5462	ctsio->io_hdr.status = CTL_SUCCESS;
5463
5464bailout:
5465	mtx_unlock(&lun->lun_lock);
5466
5467	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5468		free(ctsio->kern_data_ptr, M_CTL);
5469		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5470	}
5471
5472	ctl_done((union ctl_io *)ctsio);
5473	return (CTL_RETVAL_COMPLETE);
5474}
5475
5476int
5477ctl_start_stop(struct ctl_scsiio *ctsio)
5478{
5479	struct scsi_start_stop_unit *cdb;
5480	struct ctl_lun *lun;
5481	struct ctl_softc *ctl_softc;
5482	int retval;
5483
5484	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5485
5486	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5487	ctl_softc = control_softc;
5488	retval = 0;
5489
5490	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5491
5492	/*
5493	 * XXX KDM
5494	 * We don't support the immediate bit on a stop unit.  In order to
5495	 * do that, we would need to code up a way to know that a stop is
5496	 * pending, and hold off any new commands until it completes, one
5497	 * way or another.  Then we could accept or reject those commands
5498	 * depending on its status.  We would almost need to do the reverse
5499	 * of what we do below for an immediate start -- return the copy of
5500	 * the ctl_io to the FETD with status to send to the host (and to
5501	 * free the copy!) and then free the original I/O once the stop
5502	 * actually completes.  That way, the OOA queue mechanism can work
5503	 * to block commands that shouldn't proceed.  Another alternative
5504	 * would be to put the copy in the queue in place of the original,
5505	 * and return the original back to the caller.  That could be
5506	 * slightly safer..
5507	 */
5508	if ((cdb->byte2 & SSS_IMMED)
5509	 && ((cdb->how & SSS_START) == 0)) {
5510		ctl_set_invalid_field(ctsio,
5511				      /*sks_valid*/ 1,
5512				      /*command*/ 1,
5513				      /*field*/ 1,
5514				      /*bit_valid*/ 1,
5515				      /*bit*/ 0);
5516		ctl_done((union ctl_io *)ctsio);
5517		return (CTL_RETVAL_COMPLETE);
5518	}
5519
5520	if ((lun->flags & CTL_LUN_PR_RESERVED)
5521	 && ((cdb->how & SSS_START)==0)) {
5522		uint32_t residx;
5523
5524		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5525		if (!lun->per_res[residx].registered
5526		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5527
5528			ctl_set_reservation_conflict(ctsio);
5529			ctl_done((union ctl_io *)ctsio);
5530			return (CTL_RETVAL_COMPLETE);
5531		}
5532	}
5533
5534	/*
5535	 * If there is no backend on this device, we can't start or stop
5536	 * it.  In theory we shouldn't get any start/stop commands in the
5537	 * first place at this level if the LUN doesn't have a backend.
5538	 * That should get stopped by the command decode code.
5539	 */
5540	if (lun->backend == NULL) {
5541		ctl_set_invalid_opcode(ctsio);
5542		ctl_done((union ctl_io *)ctsio);
5543		return (CTL_RETVAL_COMPLETE);
5544	}
5545
5546	/*
5547	 * XXX KDM Copan-specific offline behavior.
5548	 * Figure out a reasonable way to port this?
5549	 */
5550#ifdef NEEDTOPORT
5551	mtx_lock(&lun->lun_lock);
5552
5553	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5554	 && (lun->flags & CTL_LUN_OFFLINE)) {
5555		/*
5556		 * If the LUN is offline, and the on/offline bit isn't set,
5557		 * reject the start or stop.  Otherwise, let it through.
5558		 */
5559		mtx_unlock(&lun->lun_lock);
5560		ctl_set_lun_not_ready(ctsio);
5561		ctl_done((union ctl_io *)ctsio);
5562	} else {
5563		mtx_unlock(&lun->lun_lock);
5564#endif /* NEEDTOPORT */
5565		/*
5566		 * This could be a start or a stop when we're online,
5567		 * or a stop/offline or start/online.  A start or stop when
5568		 * we're offline is covered in the case above.
5569		 */
5570		/*
5571		 * In the non-immediate case, we send the request to
5572		 * the backend and return status to the user when
5573		 * it is done.
5574		 *
5575		 * In the immediate case, we allocate a new ctl_io
5576		 * to hold a copy of the request, and send that to
5577		 * the backend.  We then set good status on the
5578		 * user's request and return it immediately.
5579		 */
5580		if (cdb->byte2 & SSS_IMMED) {
5581			union ctl_io *new_io;
5582
5583			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5584			if (new_io == NULL) {
5585				ctl_set_busy(ctsio);
5586				ctl_done((union ctl_io *)ctsio);
5587			} else {
5588				ctl_copy_io((union ctl_io *)ctsio,
5589					    new_io);
5590				retval = lun->backend->config_write(new_io);
5591				ctl_set_success(ctsio);
5592				ctl_done((union ctl_io *)ctsio);
5593			}
5594		} else {
5595			retval = lun->backend->config_write(
5596				(union ctl_io *)ctsio);
5597		}
5598#ifdef NEEDTOPORT
5599	}
5600#endif
5601	return (retval);
5602}
5603
5604/*
5605 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5606 * we don't really do anything with the LBA and length fields if the user
5607 * passes them in.  Instead we'll just flush out the cache for the entire
5608 * LUN.
5609 */
5610int
5611ctl_sync_cache(struct ctl_scsiio *ctsio)
5612{
5613	struct ctl_lun *lun;
5614	struct ctl_softc *ctl_softc;
5615	uint64_t starting_lba;
5616	uint32_t block_count;
5617	int retval;
5618
5619	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5620
5621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622	ctl_softc = control_softc;
5623	retval = 0;
5624
5625	switch (ctsio->cdb[0]) {
5626	case SYNCHRONIZE_CACHE: {
5627		struct scsi_sync_cache *cdb;
5628		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5629
5630		starting_lba = scsi_4btoul(cdb->begin_lba);
5631		block_count = scsi_2btoul(cdb->lb_count);
5632		break;
5633	}
5634	case SYNCHRONIZE_CACHE_16: {
5635		struct scsi_sync_cache_16 *cdb;
5636		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5637
5638		starting_lba = scsi_8btou64(cdb->begin_lba);
5639		block_count = scsi_4btoul(cdb->lb_count);
5640		break;
5641	}
5642	default:
5643		ctl_set_invalid_opcode(ctsio);
5644		ctl_done((union ctl_io *)ctsio);
5645		goto bailout;
5646		break; /* NOTREACHED */
5647	}
5648
5649	/*
5650	 * We check the LBA and length, but don't do anything with them.
5651	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5652	 * get flushed.  This check will just help satisfy anyone who wants
5653	 * to see an error for an out of range LBA.
5654	 */
5655	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5656		ctl_set_lba_out_of_range(ctsio);
5657		ctl_done((union ctl_io *)ctsio);
5658		goto bailout;
5659	}
5660
5661	/*
5662	 * If this LUN has no backend, we can't flush the cache anyway.
5663	 */
5664	if (lun->backend == NULL) {
5665		ctl_set_invalid_opcode(ctsio);
5666		ctl_done((union ctl_io *)ctsio);
5667		goto bailout;
5668	}
5669
5670	/*
5671	 * Check to see whether we're configured to send the SYNCHRONIZE
5672	 * CACHE command directly to the back end.
5673	 */
5674	mtx_lock(&lun->lun_lock);
5675	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5676	 && (++(lun->sync_count) >= lun->sync_interval)) {
5677		lun->sync_count = 0;
5678		mtx_unlock(&lun->lun_lock);
5679		retval = lun->backend->config_write((union ctl_io *)ctsio);
5680	} else {
5681		mtx_unlock(&lun->lun_lock);
5682		ctl_set_success(ctsio);
5683		ctl_done((union ctl_io *)ctsio);
5684	}
5685
5686bailout:
5687
5688	return (retval);
5689}
5690
5691int
5692ctl_format(struct ctl_scsiio *ctsio)
5693{
5694	struct scsi_format *cdb;
5695	struct ctl_lun *lun;
5696	struct ctl_softc *ctl_softc;
5697	int length, defect_list_len;
5698
5699	CTL_DEBUG_PRINT(("ctl_format\n"));
5700
5701	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5702	ctl_softc = control_softc;
5703
5704	cdb = (struct scsi_format *)ctsio->cdb;
5705
5706	length = 0;
5707	if (cdb->byte2 & SF_FMTDATA) {
5708		if (cdb->byte2 & SF_LONGLIST)
5709			length = sizeof(struct scsi_format_header_long);
5710		else
5711			length = sizeof(struct scsi_format_header_short);
5712	}
5713
5714	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5715	 && (length > 0)) {
5716		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5717		ctsio->kern_data_len = length;
5718		ctsio->kern_total_len = length;
5719		ctsio->kern_data_resid = 0;
5720		ctsio->kern_rel_offset = 0;
5721		ctsio->kern_sg_entries = 0;
5722		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5723		ctsio->be_move_done = ctl_config_move_done;
5724		ctl_datamove((union ctl_io *)ctsio);
5725
5726		return (CTL_RETVAL_COMPLETE);
5727	}
5728
5729	defect_list_len = 0;
5730
5731	if (cdb->byte2 & SF_FMTDATA) {
5732		if (cdb->byte2 & SF_LONGLIST) {
5733			struct scsi_format_header_long *header;
5734
5735			header = (struct scsi_format_header_long *)
5736				ctsio->kern_data_ptr;
5737
5738			defect_list_len = scsi_4btoul(header->defect_list_len);
5739			if (defect_list_len != 0) {
5740				ctl_set_invalid_field(ctsio,
5741						      /*sks_valid*/ 1,
5742						      /*command*/ 0,
5743						      /*field*/ 2,
5744						      /*bit_valid*/ 0,
5745						      /*bit*/ 0);
5746				goto bailout;
5747			}
5748		} else {
5749			struct scsi_format_header_short *header;
5750
5751			header = (struct scsi_format_header_short *)
5752				ctsio->kern_data_ptr;
5753
5754			defect_list_len = scsi_2btoul(header->defect_list_len);
5755			if (defect_list_len != 0) {
5756				ctl_set_invalid_field(ctsio,
5757						      /*sks_valid*/ 1,
5758						      /*command*/ 0,
5759						      /*field*/ 2,
5760						      /*bit_valid*/ 0,
5761						      /*bit*/ 0);
5762				goto bailout;
5763			}
5764		}
5765	}
5766
5767	/*
5768	 * The format command will clear out the "Medium format corrupted"
5769	 * status if set by the configuration code.  That status is really
5770	 * just a way to notify the host that we have lost the media, and
5771	 * get them to issue a command that will basically make them think
5772	 * they're blowing away the media.
5773	 */
5774	mtx_lock(&lun->lun_lock);
5775	lun->flags &= ~CTL_LUN_INOPERABLE;
5776	mtx_unlock(&lun->lun_lock);
5777
5778	ctsio->scsi_status = SCSI_STATUS_OK;
5779	ctsio->io_hdr.status = CTL_SUCCESS;
5780bailout:
5781
5782	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5783		free(ctsio->kern_data_ptr, M_CTL);
5784		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5785	}
5786
5787	ctl_done((union ctl_io *)ctsio);
5788	return (CTL_RETVAL_COMPLETE);
5789}
5790
5791int
5792ctl_read_buffer(struct ctl_scsiio *ctsio)
5793{
5794	struct scsi_read_buffer *cdb;
5795	struct ctl_lun *lun;
5796	int buffer_offset, len;
5797	static uint8_t descr[4];
5798	static uint8_t echo_descr[4] = { 0 };
5799
5800	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5801
5802	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5803	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5804
5805	if (lun->flags & CTL_LUN_PR_RESERVED) {
5806		uint32_t residx;
5807
5808		/*
5809		 * XXX KDM need a lock here.
5810		 */
5811		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5812		if ((lun->res_type == SPR_TYPE_EX_AC
5813		  && residx != lun->pr_res_idx)
5814		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5815		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5816		  && !lun->per_res[residx].registered)) {
5817			ctl_set_reservation_conflict(ctsio);
5818			ctl_done((union ctl_io *)ctsio);
5819			return (CTL_RETVAL_COMPLETE);
5820	        }
5821	}
5822
5823	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5824	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5825	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5826		ctl_set_invalid_field(ctsio,
5827				      /*sks_valid*/ 1,
5828				      /*command*/ 1,
5829				      /*field*/ 1,
5830				      /*bit_valid*/ 1,
5831				      /*bit*/ 4);
5832		ctl_done((union ctl_io *)ctsio);
5833		return (CTL_RETVAL_COMPLETE);
5834	}
5835
5836	len = scsi_3btoul(cdb->length);
5837	buffer_offset = scsi_3btoul(cdb->offset);
5838
5839	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5840		ctl_set_invalid_field(ctsio,
5841				      /*sks_valid*/ 1,
5842				      /*command*/ 1,
5843				      /*field*/ 6,
5844				      /*bit_valid*/ 0,
5845				      /*bit*/ 0);
5846		ctl_done((union ctl_io *)ctsio);
5847		return (CTL_RETVAL_COMPLETE);
5848	}
5849
5850	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5851		descr[0] = 0;
5852		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5853		ctsio->kern_data_ptr = descr;
5854		len = min(len, sizeof(descr));
5855	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5856		ctsio->kern_data_ptr = echo_descr;
5857		len = min(len, sizeof(echo_descr));
5858	} else
5859		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5860	ctsio->kern_data_len = len;
5861	ctsio->kern_total_len = len;
5862	ctsio->kern_data_resid = 0;
5863	ctsio->kern_rel_offset = 0;
5864	ctsio->kern_sg_entries = 0;
5865	ctsio->be_move_done = ctl_config_move_done;
5866	ctl_datamove((union ctl_io *)ctsio);
5867
5868	return (CTL_RETVAL_COMPLETE);
5869}
5870
5871int
5872ctl_write_buffer(struct ctl_scsiio *ctsio)
5873{
5874	struct scsi_write_buffer *cdb;
5875	struct ctl_lun *lun;
5876	int buffer_offset, len;
5877
5878	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5879
5880	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5881	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5882
5883	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5884		ctl_set_invalid_field(ctsio,
5885				      /*sks_valid*/ 1,
5886				      /*command*/ 1,
5887				      /*field*/ 1,
5888				      /*bit_valid*/ 1,
5889				      /*bit*/ 4);
5890		ctl_done((union ctl_io *)ctsio);
5891		return (CTL_RETVAL_COMPLETE);
5892	}
5893
5894	len = scsi_3btoul(cdb->length);
5895	buffer_offset = scsi_3btoul(cdb->offset);
5896
5897	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5898		ctl_set_invalid_field(ctsio,
5899				      /*sks_valid*/ 1,
5900				      /*command*/ 1,
5901				      /*field*/ 6,
5902				      /*bit_valid*/ 0,
5903				      /*bit*/ 0);
5904		ctl_done((union ctl_io *)ctsio);
5905		return (CTL_RETVAL_COMPLETE);
5906	}
5907
5908	/*
5909	 * If we've got a kernel request that hasn't been malloced yet,
5910	 * malloc it and tell the caller the data buffer is here.
5911	 */
5912	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5913		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5914		ctsio->kern_data_len = len;
5915		ctsio->kern_total_len = len;
5916		ctsio->kern_data_resid = 0;
5917		ctsio->kern_rel_offset = 0;
5918		ctsio->kern_sg_entries = 0;
5919		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5920		ctsio->be_move_done = ctl_config_move_done;
5921		ctl_datamove((union ctl_io *)ctsio);
5922
5923		return (CTL_RETVAL_COMPLETE);
5924	}
5925
5926	ctl_done((union ctl_io *)ctsio);
5927
5928	return (CTL_RETVAL_COMPLETE);
5929}
5930
5931int
5932ctl_write_same(struct ctl_scsiio *ctsio)
5933{
5934	struct ctl_lun *lun;
5935	struct ctl_lba_len_flags *lbalen;
5936	uint64_t lba;
5937	uint32_t num_blocks;
5938	int len, retval;
5939	uint8_t byte2;
5940
5941	retval = CTL_RETVAL_COMPLETE;
5942
5943	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5944
5945	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5946
5947	switch (ctsio->cdb[0]) {
5948	case WRITE_SAME_10: {
5949		struct scsi_write_same_10 *cdb;
5950
5951		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5952
5953		lba = scsi_4btoul(cdb->addr);
5954		num_blocks = scsi_2btoul(cdb->length);
5955		byte2 = cdb->byte2;
5956		break;
5957	}
5958	case WRITE_SAME_16: {
5959		struct scsi_write_same_16 *cdb;
5960
5961		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5962
5963		lba = scsi_8btou64(cdb->addr);
5964		num_blocks = scsi_4btoul(cdb->length);
5965		byte2 = cdb->byte2;
5966		break;
5967	}
5968	default:
5969		/*
5970		 * We got a command we don't support.  This shouldn't
5971		 * happen, commands should be filtered out above us.
5972		 */
5973		ctl_set_invalid_opcode(ctsio);
5974		ctl_done((union ctl_io *)ctsio);
5975
5976		return (CTL_RETVAL_COMPLETE);
5977		break; /* NOTREACHED */
5978	}
5979
5980	/*
5981	 * The first check is to make sure we're in bounds, the second
5982	 * check is to catch wrap-around problems.  If the lba + num blocks
5983	 * is less than the lba, then we've wrapped around and the block
5984	 * range is invalid anyway.
5985	 */
5986	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5987	 || ((lba + num_blocks) < lba)) {
5988		ctl_set_lba_out_of_range(ctsio);
5989		ctl_done((union ctl_io *)ctsio);
5990		return (CTL_RETVAL_COMPLETE);
5991	}
5992
5993	/* Zero number of blocks means "to the last logical block" */
5994	if (num_blocks == 0) {
5995		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5996			ctl_set_invalid_field(ctsio,
5997					      /*sks_valid*/ 0,
5998					      /*command*/ 1,
5999					      /*field*/ 0,
6000					      /*bit_valid*/ 0,
6001					      /*bit*/ 0);
6002			ctl_done((union ctl_io *)ctsio);
6003			return (CTL_RETVAL_COMPLETE);
6004		}
6005		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6006	}
6007
6008	len = lun->be_lun->blocksize;
6009
6010	/*
6011	 * If we've got a kernel request that hasn't been malloced yet,
6012	 * malloc it and tell the caller the data buffer is here.
6013	 */
6014	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6015		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6016		ctsio->kern_data_len = len;
6017		ctsio->kern_total_len = len;
6018		ctsio->kern_data_resid = 0;
6019		ctsio->kern_rel_offset = 0;
6020		ctsio->kern_sg_entries = 0;
6021		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6022		ctsio->be_move_done = ctl_config_move_done;
6023		ctl_datamove((union ctl_io *)ctsio);
6024
6025		return (CTL_RETVAL_COMPLETE);
6026	}
6027
6028	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6029	lbalen->lba = lba;
6030	lbalen->len = num_blocks;
6031	lbalen->flags = byte2;
6032	retval = lun->backend->config_write((union ctl_io *)ctsio);
6033
6034	return (retval);
6035}
6036
6037int
6038ctl_unmap(struct ctl_scsiio *ctsio)
6039{
6040	struct ctl_lun *lun;
6041	struct scsi_unmap *cdb;
6042	struct ctl_ptr_len_flags *ptrlen;
6043	struct scsi_unmap_header *hdr;
6044	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6045	uint64_t lba;
6046	uint32_t num_blocks;
6047	int len, retval;
6048	uint8_t byte2;
6049
6050	retval = CTL_RETVAL_COMPLETE;
6051
6052	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6053
6054	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6055	cdb = (struct scsi_unmap *)ctsio->cdb;
6056
6057	len = scsi_2btoul(cdb->length);
6058	byte2 = cdb->byte2;
6059
6060	/*
6061	 * If we've got a kernel request that hasn't been malloced yet,
6062	 * malloc it and tell the caller the data buffer is here.
6063	 */
6064	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6065		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6066		ctsio->kern_data_len = len;
6067		ctsio->kern_total_len = len;
6068		ctsio->kern_data_resid = 0;
6069		ctsio->kern_rel_offset = 0;
6070		ctsio->kern_sg_entries = 0;
6071		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6072		ctsio->be_move_done = ctl_config_move_done;
6073		ctl_datamove((union ctl_io *)ctsio);
6074
6075		return (CTL_RETVAL_COMPLETE);
6076	}
6077
6078	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6079	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6080	if (len < sizeof (*hdr) ||
6081	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6082	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6083	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6084		ctl_set_invalid_field(ctsio,
6085				      /*sks_valid*/ 0,
6086				      /*command*/ 0,
6087				      /*field*/ 0,
6088				      /*bit_valid*/ 0,
6089				      /*bit*/ 0);
6090		ctl_done((union ctl_io *)ctsio);
6091		return (CTL_RETVAL_COMPLETE);
6092	}
6093	len = scsi_2btoul(hdr->desc_length);
6094	buf = (struct scsi_unmap_desc *)(hdr + 1);
6095	end = buf + len / sizeof(*buf);
6096
6097	endnz = buf;
6098	for (range = buf; range < end; range++) {
6099		lba = scsi_8btou64(range->lba);
6100		num_blocks = scsi_4btoul(range->length);
6101		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6102		 || ((lba + num_blocks) < lba)) {
6103			ctl_set_lba_out_of_range(ctsio);
6104			ctl_done((union ctl_io *)ctsio);
6105			return (CTL_RETVAL_COMPLETE);
6106		}
6107		if (num_blocks != 0)
6108			endnz = range + 1;
6109	}
6110
6111	/*
6112	 * Block backend can not handle zero last range.
6113	 * Filter it out and return if there is nothing left.
6114	 */
6115	len = (uint8_t *)endnz - (uint8_t *)buf;
6116	if (len == 0) {
6117		ctl_set_success(ctsio);
6118		ctl_done((union ctl_io *)ctsio);
6119		return (CTL_RETVAL_COMPLETE);
6120	}
6121
6122	ptrlen = (struct ctl_ptr_len_flags *)
6123	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6124	ptrlen->ptr = (void *)buf;
6125	ptrlen->len = len;
6126	ptrlen->flags = byte2;
6127
6128	retval = lun->backend->config_write((union ctl_io *)ctsio);
6129	return (retval);
6130}
6131
6132/*
6133 * Note that this function currently doesn't actually do anything inside
6134 * CTL to enforce things if the DQue bit is turned on.
6135 *
6136 * Also note that this function can't be used in the default case, because
6137 * the DQue bit isn't set in the changeable mask for the control mode page
6138 * anyway.  This is just here as an example for how to implement a page
6139 * handler, and a placeholder in case we want to allow the user to turn
6140 * tagged queueing on and off.
6141 *
6142 * The D_SENSE bit handling is functional, however, and will turn
6143 * descriptor sense on and off for a given LUN.
6144 */
6145int
6146ctl_control_page_handler(struct ctl_scsiio *ctsio,
6147			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6148{
6149	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6150	struct ctl_lun *lun;
6151	struct ctl_softc *softc;
6152	int set_ua;
6153	uint32_t initidx;
6154
6155	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6156	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6157	set_ua = 0;
6158
6159	user_cp = (struct scsi_control_page *)page_ptr;
6160	current_cp = (struct scsi_control_page *)
6161		(page_index->page_data + (page_index->page_len *
6162		CTL_PAGE_CURRENT));
6163	saved_cp = (struct scsi_control_page *)
6164		(page_index->page_data + (page_index->page_len *
6165		CTL_PAGE_SAVED));
6166
6167	softc = control_softc;
6168
6169	mtx_lock(&lun->lun_lock);
6170	if (((current_cp->rlec & SCP_DSENSE) == 0)
6171	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6172		/*
6173		 * Descriptor sense is currently turned off and the user
6174		 * wants to turn it on.
6175		 */
6176		current_cp->rlec |= SCP_DSENSE;
6177		saved_cp->rlec |= SCP_DSENSE;
6178		lun->flags |= CTL_LUN_SENSE_DESC;
6179		set_ua = 1;
6180	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6181		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6182		/*
6183		 * Descriptor sense is currently turned on, and the user
6184		 * wants to turn it off.
6185		 */
6186		current_cp->rlec &= ~SCP_DSENSE;
6187		saved_cp->rlec &= ~SCP_DSENSE;
6188		lun->flags &= ~CTL_LUN_SENSE_DESC;
6189		set_ua = 1;
6190	}
6191	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6192		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6193#ifdef NEEDTOPORT
6194			csevent_log(CSC_CTL | CSC_SHELF_SW |
6195				    CTL_UNTAG_TO_UNTAG,
6196				    csevent_LogType_Trace,
6197				    csevent_Severity_Information,
6198				    csevent_AlertLevel_Green,
6199				    csevent_FRU_Firmware,
6200				    csevent_FRU_Unknown,
6201				    "Received untagged to untagged transition");
6202#endif /* NEEDTOPORT */
6203		} else {
6204#ifdef NEEDTOPORT
6205			csevent_log(CSC_CTL | CSC_SHELF_SW |
6206				    CTL_UNTAG_TO_TAG,
6207				    csevent_LogType_ConfigChange,
6208				    csevent_Severity_Information,
6209				    csevent_AlertLevel_Green,
6210				    csevent_FRU_Firmware,
6211				    csevent_FRU_Unknown,
6212				    "Received untagged to tagged "
6213				    "queueing transition");
6214#endif /* NEEDTOPORT */
6215
6216			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6217			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6218			set_ua = 1;
6219		}
6220	} else {
6221		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6222#ifdef NEEDTOPORT
6223			csevent_log(CSC_CTL | CSC_SHELF_SW |
6224				    CTL_TAG_TO_UNTAG,
6225				    csevent_LogType_ConfigChange,
6226				    csevent_Severity_Warning,
6227				    csevent_AlertLevel_Yellow,
6228				    csevent_FRU_Firmware,
6229				    csevent_FRU_Unknown,
6230				    "Received tagged queueing to untagged "
6231				    "transition");
6232#endif /* NEEDTOPORT */
6233
6234			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6235			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6236			set_ua = 1;
6237		} else {
6238#ifdef NEEDTOPORT
6239			csevent_log(CSC_CTL | CSC_SHELF_SW |
6240				    CTL_TAG_TO_TAG,
6241				    csevent_LogType_Trace,
6242				    csevent_Severity_Information,
6243				    csevent_AlertLevel_Green,
6244				    csevent_FRU_Firmware,
6245				    csevent_FRU_Unknown,
6246				    "Received tagged queueing to tagged "
6247				    "queueing transition");
6248#endif /* NEEDTOPORT */
6249		}
6250	}
6251	if (set_ua != 0) {
6252		int i;
6253		/*
6254		 * Let other initiators know that the mode
6255		 * parameters for this LUN have changed.
6256		 */
6257		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6258			if (i == initidx)
6259				continue;
6260
6261			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6262		}
6263	}
6264	mtx_unlock(&lun->lun_lock);
6265
6266	return (0);
6267}
6268
6269int
6270ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6271		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6272{
6273	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6274	struct ctl_lun *lun;
6275	int set_ua;
6276	uint32_t initidx;
6277
6278	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6279	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6280	set_ua = 0;
6281
6282	user_cp = (struct scsi_caching_page *)page_ptr;
6283	current_cp = (struct scsi_caching_page *)
6284		(page_index->page_data + (page_index->page_len *
6285		CTL_PAGE_CURRENT));
6286	saved_cp = (struct scsi_caching_page *)
6287		(page_index->page_data + (page_index->page_len *
6288		CTL_PAGE_SAVED));
6289
6290	mtx_lock(&lun->lun_lock);
6291	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6292	    (user_cp->flags1 & (SCP_WCE | SCP_RCD)))
6293		set_ua = 1;
6294	current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6295	current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6296	saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6297	saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6298	if (set_ua != 0) {
6299		int i;
6300		/*
6301		 * Let other initiators know that the mode
6302		 * parameters for this LUN have changed.
6303		 */
6304		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6305			if (i == initidx)
6306				continue;
6307
6308			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6309		}
6310	}
6311	mtx_unlock(&lun->lun_lock);
6312
6313	return (0);
6314}
6315
6316int
6317ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6318		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6319{
6320	return (0);
6321}
6322
6323int
6324ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6325			   struct ctl_page_index *page_index, int pc)
6326{
6327	struct copan_power_subpage *page;
6328
6329	page = (struct copan_power_subpage *)page_index->page_data +
6330		(page_index->page_len * pc);
6331
6332	switch (pc) {
6333	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6334		/*
6335		 * We don't update the changable bits for this page.
6336		 */
6337		break;
6338	case SMS_PAGE_CTRL_CURRENT >> 6:
6339	case SMS_PAGE_CTRL_DEFAULT >> 6:
6340	case SMS_PAGE_CTRL_SAVED >> 6:
6341#ifdef NEEDTOPORT
6342		ctl_update_power_subpage(page);
6343#endif
6344		break;
6345	default:
6346#ifdef NEEDTOPORT
6347		EPRINT(0, "Invalid PC %d!!", pc);
6348#endif
6349		break;
6350	}
6351	return (0);
6352}
6353
6354
6355int
6356ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6357		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6358{
6359	struct copan_aps_subpage *user_sp;
6360	struct copan_aps_subpage *current_sp;
6361	union ctl_modepage_info *modepage_info;
6362	struct ctl_softc *softc;
6363	struct ctl_lun *lun;
6364	int retval;
6365
6366	retval = CTL_RETVAL_COMPLETE;
6367	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6368		     (page_index->page_len * CTL_PAGE_CURRENT));
6369	softc = control_softc;
6370	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6371
6372	user_sp = (struct copan_aps_subpage *)page_ptr;
6373
6374	modepage_info = (union ctl_modepage_info *)
6375		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6376
6377	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6378	modepage_info->header.subpage = page_index->subpage;
6379	modepage_info->aps.lock_active = user_sp->lock_active;
6380
6381	mtx_lock(&softc->ctl_lock);
6382
6383	/*
6384	 * If there is a request to lock the LUN and another LUN is locked
6385	 * this is an error. If the requested LUN is already locked ignore
6386	 * the request. If no LUN is locked attempt to lock it.
6387	 * if there is a request to unlock the LUN and the LUN is currently
6388	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6389	 * if another LUN is locked or no LUN is locked.
6390	 */
6391	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6392		if (softc->aps_locked_lun == lun->lun) {
6393			/*
6394			 * This LUN is already locked, so we're done.
6395			 */
6396			retval = CTL_RETVAL_COMPLETE;
6397		} else if (softc->aps_locked_lun == 0) {
6398			/*
6399			 * No one has the lock, pass the request to the
6400			 * backend.
6401			 */
6402			retval = lun->backend->config_write(
6403				(union ctl_io *)ctsio);
6404		} else {
6405			/*
6406			 * Someone else has the lock, throw out the request.
6407			 */
6408			ctl_set_already_locked(ctsio);
6409			free(ctsio->kern_data_ptr, M_CTL);
6410			ctl_done((union ctl_io *)ctsio);
6411
6412			/*
6413			 * Set the return value so that ctl_do_mode_select()
6414			 * won't try to complete the command.  We already
6415			 * completed it here.
6416			 */
6417			retval = CTL_RETVAL_ERROR;
6418		}
6419	} else if (softc->aps_locked_lun == lun->lun) {
6420		/*
6421		 * This LUN is locked, so pass the unlock request to the
6422		 * backend.
6423		 */
6424		retval = lun->backend->config_write((union ctl_io *)ctsio);
6425	}
6426	mtx_unlock(&softc->ctl_lock);
6427
6428	return (retval);
6429}
6430
6431int
6432ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6433				struct ctl_page_index *page_index,
6434				uint8_t *page_ptr)
6435{
6436	uint8_t *c;
6437	int i;
6438
6439	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6440	ctl_time_io_secs =
6441		(c[0] << 8) |
6442		(c[1] << 0) |
6443		0;
6444	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6445	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6446	printf("page data:");
6447	for (i=0; i<8; i++)
6448		printf(" %.2x",page_ptr[i]);
6449	printf("\n");
6450	return (0);
6451}
6452
6453int
6454ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6455			       struct ctl_page_index *page_index,
6456			       int pc)
6457{
6458	struct copan_debugconf_subpage *page;
6459
6460	page = (struct copan_debugconf_subpage *)page_index->page_data +
6461		(page_index->page_len * pc);
6462
6463	switch (pc) {
6464	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6465	case SMS_PAGE_CTRL_DEFAULT >> 6:
6466	case SMS_PAGE_CTRL_SAVED >> 6:
6467		/*
6468		 * We don't update the changable or default bits for this page.
6469		 */
6470		break;
6471	case SMS_PAGE_CTRL_CURRENT >> 6:
6472		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6473		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6474		break;
6475	default:
6476#ifdef NEEDTOPORT
6477		EPRINT(0, "Invalid PC %d!!", pc);
6478#endif /* NEEDTOPORT */
6479		break;
6480	}
6481	return (0);
6482}
6483
6484
6485static int
6486ctl_do_mode_select(union ctl_io *io)
6487{
6488	struct scsi_mode_page_header *page_header;
6489	struct ctl_page_index *page_index;
6490	struct ctl_scsiio *ctsio;
6491	int control_dev, page_len;
6492	int page_len_offset, page_len_size;
6493	union ctl_modepage_info *modepage_info;
6494	struct ctl_lun *lun;
6495	int *len_left, *len_used;
6496	int retval, i;
6497
6498	ctsio = &io->scsiio;
6499	page_index = NULL;
6500	page_len = 0;
6501	retval = CTL_RETVAL_COMPLETE;
6502
6503	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6504
6505	if (lun->be_lun->lun_type != T_DIRECT)
6506		control_dev = 1;
6507	else
6508		control_dev = 0;
6509
6510	modepage_info = (union ctl_modepage_info *)
6511		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6512	len_left = &modepage_info->header.len_left;
6513	len_used = &modepage_info->header.len_used;
6514
6515do_next_page:
6516
6517	page_header = (struct scsi_mode_page_header *)
6518		(ctsio->kern_data_ptr + *len_used);
6519
6520	if (*len_left == 0) {
6521		free(ctsio->kern_data_ptr, M_CTL);
6522		ctl_set_success(ctsio);
6523		ctl_done((union ctl_io *)ctsio);
6524		return (CTL_RETVAL_COMPLETE);
6525	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6526
6527		free(ctsio->kern_data_ptr, M_CTL);
6528		ctl_set_param_len_error(ctsio);
6529		ctl_done((union ctl_io *)ctsio);
6530		return (CTL_RETVAL_COMPLETE);
6531
6532	} else if ((page_header->page_code & SMPH_SPF)
6533		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6534
6535		free(ctsio->kern_data_ptr, M_CTL);
6536		ctl_set_param_len_error(ctsio);
6537		ctl_done((union ctl_io *)ctsio);
6538		return (CTL_RETVAL_COMPLETE);
6539	}
6540
6541
6542	/*
6543	 * XXX KDM should we do something with the block descriptor?
6544	 */
6545	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6546
6547		if ((control_dev != 0)
6548		 && (lun->mode_pages.index[i].page_flags &
6549		     CTL_PAGE_FLAG_DISK_ONLY))
6550			continue;
6551
6552		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6553		    (page_header->page_code & SMPH_PC_MASK))
6554			continue;
6555
6556		/*
6557		 * If neither page has a subpage code, then we've got a
6558		 * match.
6559		 */
6560		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6561		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6562			page_index = &lun->mode_pages.index[i];
6563			page_len = page_header->page_length;
6564			break;
6565		}
6566
6567		/*
6568		 * If both pages have subpages, then the subpage numbers
6569		 * have to match.
6570		 */
6571		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6572		  && (page_header->page_code & SMPH_SPF)) {
6573			struct scsi_mode_page_header_sp *sph;
6574
6575			sph = (struct scsi_mode_page_header_sp *)page_header;
6576
6577			if (lun->mode_pages.index[i].subpage ==
6578			    sph->subpage) {
6579				page_index = &lun->mode_pages.index[i];
6580				page_len = scsi_2btoul(sph->page_length);
6581				break;
6582			}
6583		}
6584	}
6585
6586	/*
6587	 * If we couldn't find the page, or if we don't have a mode select
6588	 * handler for it, send back an error to the user.
6589	 */
6590	if ((page_index == NULL)
6591	 || (page_index->select_handler == NULL)) {
6592		ctl_set_invalid_field(ctsio,
6593				      /*sks_valid*/ 1,
6594				      /*command*/ 0,
6595				      /*field*/ *len_used,
6596				      /*bit_valid*/ 0,
6597				      /*bit*/ 0);
6598		free(ctsio->kern_data_ptr, M_CTL);
6599		ctl_done((union ctl_io *)ctsio);
6600		return (CTL_RETVAL_COMPLETE);
6601	}
6602
6603	if (page_index->page_code & SMPH_SPF) {
6604		page_len_offset = 2;
6605		page_len_size = 2;
6606	} else {
6607		page_len_size = 1;
6608		page_len_offset = 1;
6609	}
6610
6611	/*
6612	 * If the length the initiator gives us isn't the one we specify in
6613	 * the mode page header, or if they didn't specify enough data in
6614	 * the CDB to avoid truncating this page, kick out the request.
6615	 */
6616	if ((page_len != (page_index->page_len - page_len_offset -
6617			  page_len_size))
6618	 || (*len_left < page_index->page_len)) {
6619
6620
6621		ctl_set_invalid_field(ctsio,
6622				      /*sks_valid*/ 1,
6623				      /*command*/ 0,
6624				      /*field*/ *len_used + page_len_offset,
6625				      /*bit_valid*/ 0,
6626				      /*bit*/ 0);
6627		free(ctsio->kern_data_ptr, M_CTL);
6628		ctl_done((union ctl_io *)ctsio);
6629		return (CTL_RETVAL_COMPLETE);
6630	}
6631
6632	/*
6633	 * Run through the mode page, checking to make sure that the bits
6634	 * the user changed are actually legal for him to change.
6635	 */
6636	for (i = 0; i < page_index->page_len; i++) {
6637		uint8_t *user_byte, *change_mask, *current_byte;
6638		int bad_bit;
6639		int j;
6640
6641		user_byte = (uint8_t *)page_header + i;
6642		change_mask = page_index->page_data +
6643			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6644		current_byte = page_index->page_data +
6645			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6646
6647		/*
6648		 * Check to see whether the user set any bits in this byte
6649		 * that he is not allowed to set.
6650		 */
6651		if ((*user_byte & ~(*change_mask)) ==
6652		    (*current_byte & ~(*change_mask)))
6653			continue;
6654
6655		/*
6656		 * Go through bit by bit to determine which one is illegal.
6657		 */
6658		bad_bit = 0;
6659		for (j = 7; j >= 0; j--) {
6660			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6661			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6662				bad_bit = i;
6663				break;
6664			}
6665		}
6666		ctl_set_invalid_field(ctsio,
6667				      /*sks_valid*/ 1,
6668				      /*command*/ 0,
6669				      /*field*/ *len_used + i,
6670				      /*bit_valid*/ 1,
6671				      /*bit*/ bad_bit);
6672		free(ctsio->kern_data_ptr, M_CTL);
6673		ctl_done((union ctl_io *)ctsio);
6674		return (CTL_RETVAL_COMPLETE);
6675	}
6676
6677	/*
6678	 * Decrement these before we call the page handler, since we may
6679	 * end up getting called back one way or another before the handler
6680	 * returns to this context.
6681	 */
6682	*len_left -= page_index->page_len;
6683	*len_used += page_index->page_len;
6684
6685	retval = page_index->select_handler(ctsio, page_index,
6686					    (uint8_t *)page_header);
6687
6688	/*
6689	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6690	 * wait until this queued command completes to finish processing
6691	 * the mode page.  If it returns anything other than
6692	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6693	 * already set the sense information, freed the data pointer, and
6694	 * completed the io for us.
6695	 */
6696	if (retval != CTL_RETVAL_COMPLETE)
6697		goto bailout_no_done;
6698
6699	/*
6700	 * If the initiator sent us more than one page, parse the next one.
6701	 */
6702	if (*len_left > 0)
6703		goto do_next_page;
6704
6705	ctl_set_success(ctsio);
6706	free(ctsio->kern_data_ptr, M_CTL);
6707	ctl_done((union ctl_io *)ctsio);
6708
6709bailout_no_done:
6710
6711	return (CTL_RETVAL_COMPLETE);
6712
6713}
6714
6715int
6716ctl_mode_select(struct ctl_scsiio *ctsio)
6717{
6718	int param_len, pf, sp;
6719	int header_size, bd_len;
6720	int len_left, len_used;
6721	struct ctl_page_index *page_index;
6722	struct ctl_lun *lun;
6723	int control_dev, page_len;
6724	union ctl_modepage_info *modepage_info;
6725	int retval;
6726
6727	pf = 0;
6728	sp = 0;
6729	page_len = 0;
6730	len_used = 0;
6731	len_left = 0;
6732	retval = 0;
6733	bd_len = 0;
6734	page_index = NULL;
6735
6736	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6737
6738	if (lun->be_lun->lun_type != T_DIRECT)
6739		control_dev = 1;
6740	else
6741		control_dev = 0;
6742
6743	switch (ctsio->cdb[0]) {
6744	case MODE_SELECT_6: {
6745		struct scsi_mode_select_6 *cdb;
6746
6747		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6748
6749		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6750		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6751
6752		param_len = cdb->length;
6753		header_size = sizeof(struct scsi_mode_header_6);
6754		break;
6755	}
6756	case MODE_SELECT_10: {
6757		struct scsi_mode_select_10 *cdb;
6758
6759		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6760
6761		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6762		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6763
6764		param_len = scsi_2btoul(cdb->length);
6765		header_size = sizeof(struct scsi_mode_header_10);
6766		break;
6767	}
6768	default:
6769		ctl_set_invalid_opcode(ctsio);
6770		ctl_done((union ctl_io *)ctsio);
6771		return (CTL_RETVAL_COMPLETE);
6772		break; /* NOTREACHED */
6773	}
6774
6775	/*
6776	 * From SPC-3:
6777	 * "A parameter list length of zero indicates that the Data-Out Buffer
6778	 * shall be empty. This condition shall not be considered as an error."
6779	 */
6780	if (param_len == 0) {
6781		ctl_set_success(ctsio);
6782		ctl_done((union ctl_io *)ctsio);
6783		return (CTL_RETVAL_COMPLETE);
6784	}
6785
6786	/*
6787	 * Since we'll hit this the first time through, prior to
6788	 * allocation, we don't need to free a data buffer here.
6789	 */
6790	if (param_len < header_size) {
6791		ctl_set_param_len_error(ctsio);
6792		ctl_done((union ctl_io *)ctsio);
6793		return (CTL_RETVAL_COMPLETE);
6794	}
6795
6796	/*
6797	 * Allocate the data buffer and grab the user's data.  In theory,
6798	 * we shouldn't have to sanity check the parameter list length here
6799	 * because the maximum size is 64K.  We should be able to malloc
6800	 * that much without too many problems.
6801	 */
6802	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6803		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6804		ctsio->kern_data_len = param_len;
6805		ctsio->kern_total_len = param_len;
6806		ctsio->kern_data_resid = 0;
6807		ctsio->kern_rel_offset = 0;
6808		ctsio->kern_sg_entries = 0;
6809		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6810		ctsio->be_move_done = ctl_config_move_done;
6811		ctl_datamove((union ctl_io *)ctsio);
6812
6813		return (CTL_RETVAL_COMPLETE);
6814	}
6815
6816	switch (ctsio->cdb[0]) {
6817	case MODE_SELECT_6: {
6818		struct scsi_mode_header_6 *mh6;
6819
6820		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6821		bd_len = mh6->blk_desc_len;
6822		break;
6823	}
6824	case MODE_SELECT_10: {
6825		struct scsi_mode_header_10 *mh10;
6826
6827		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6828		bd_len = scsi_2btoul(mh10->blk_desc_len);
6829		break;
6830	}
6831	default:
6832		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6833		break;
6834	}
6835
6836	if (param_len < (header_size + bd_len)) {
6837		free(ctsio->kern_data_ptr, M_CTL);
6838		ctl_set_param_len_error(ctsio);
6839		ctl_done((union ctl_io *)ctsio);
6840		return (CTL_RETVAL_COMPLETE);
6841	}
6842
6843	/*
6844	 * Set the IO_CONT flag, so that if this I/O gets passed to
6845	 * ctl_config_write_done(), it'll get passed back to
6846	 * ctl_do_mode_select() for further processing, or completion if
6847	 * we're all done.
6848	 */
6849	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6850	ctsio->io_cont = ctl_do_mode_select;
6851
6852	modepage_info = (union ctl_modepage_info *)
6853		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6854
6855	memset(modepage_info, 0, sizeof(*modepage_info));
6856
6857	len_left = param_len - header_size - bd_len;
6858	len_used = header_size + bd_len;
6859
6860	modepage_info->header.len_left = len_left;
6861	modepage_info->header.len_used = len_used;
6862
6863	return (ctl_do_mode_select((union ctl_io *)ctsio));
6864}
6865
6866int
6867ctl_mode_sense(struct ctl_scsiio *ctsio)
6868{
6869	struct ctl_lun *lun;
6870	int pc, page_code, dbd, llba, subpage;
6871	int alloc_len, page_len, header_len, total_len;
6872	struct scsi_mode_block_descr *block_desc;
6873	struct ctl_page_index *page_index;
6874	int control_dev;
6875
6876	dbd = 0;
6877	llba = 0;
6878	block_desc = NULL;
6879	page_index = NULL;
6880
6881	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6882
6883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6884
6885	if (lun->be_lun->lun_type != T_DIRECT)
6886		control_dev = 1;
6887	else
6888		control_dev = 0;
6889
6890	if (lun->flags & CTL_LUN_PR_RESERVED) {
6891		uint32_t residx;
6892
6893		/*
6894		 * XXX KDM need a lock here.
6895		 */
6896		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6897		if ((lun->res_type == SPR_TYPE_EX_AC
6898		  && residx != lun->pr_res_idx)
6899		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6900		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6901		  && !lun->per_res[residx].registered)) {
6902			ctl_set_reservation_conflict(ctsio);
6903			ctl_done((union ctl_io *)ctsio);
6904			return (CTL_RETVAL_COMPLETE);
6905		}
6906	}
6907
6908	switch (ctsio->cdb[0]) {
6909	case MODE_SENSE_6: {
6910		struct scsi_mode_sense_6 *cdb;
6911
6912		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6913
6914		header_len = sizeof(struct scsi_mode_hdr_6);
6915		if (cdb->byte2 & SMS_DBD)
6916			dbd = 1;
6917		else
6918			header_len += sizeof(struct scsi_mode_block_descr);
6919
6920		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6921		page_code = cdb->page & SMS_PAGE_CODE;
6922		subpage = cdb->subpage;
6923		alloc_len = cdb->length;
6924		break;
6925	}
6926	case MODE_SENSE_10: {
6927		struct scsi_mode_sense_10 *cdb;
6928
6929		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6930
6931		header_len = sizeof(struct scsi_mode_hdr_10);
6932
6933		if (cdb->byte2 & SMS_DBD)
6934			dbd = 1;
6935		else
6936			header_len += sizeof(struct scsi_mode_block_descr);
6937		if (cdb->byte2 & SMS10_LLBAA)
6938			llba = 1;
6939		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6940		page_code = cdb->page & SMS_PAGE_CODE;
6941		subpage = cdb->subpage;
6942		alloc_len = scsi_2btoul(cdb->length);
6943		break;
6944	}
6945	default:
6946		ctl_set_invalid_opcode(ctsio);
6947		ctl_done((union ctl_io *)ctsio);
6948		return (CTL_RETVAL_COMPLETE);
6949		break; /* NOTREACHED */
6950	}
6951
6952	/*
6953	 * We have to make a first pass through to calculate the size of
6954	 * the pages that match the user's query.  Then we allocate enough
6955	 * memory to hold it, and actually copy the data into the buffer.
6956	 */
6957	switch (page_code) {
6958	case SMS_ALL_PAGES_PAGE: {
6959		int i;
6960
6961		page_len = 0;
6962
6963		/*
6964		 * At the moment, values other than 0 and 0xff here are
6965		 * reserved according to SPC-3.
6966		 */
6967		if ((subpage != SMS_SUBPAGE_PAGE_0)
6968		 && (subpage != SMS_SUBPAGE_ALL)) {
6969			ctl_set_invalid_field(ctsio,
6970					      /*sks_valid*/ 1,
6971					      /*command*/ 1,
6972					      /*field*/ 3,
6973					      /*bit_valid*/ 0,
6974					      /*bit*/ 0);
6975			ctl_done((union ctl_io *)ctsio);
6976			return (CTL_RETVAL_COMPLETE);
6977		}
6978
6979		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6980			if ((control_dev != 0)
6981			 && (lun->mode_pages.index[i].page_flags &
6982			     CTL_PAGE_FLAG_DISK_ONLY))
6983				continue;
6984
6985			/*
6986			 * We don't use this subpage if the user didn't
6987			 * request all subpages.
6988			 */
6989			if ((lun->mode_pages.index[i].subpage != 0)
6990			 && (subpage == SMS_SUBPAGE_PAGE_0))
6991				continue;
6992
6993#if 0
6994			printf("found page %#x len %d\n",
6995			       lun->mode_pages.index[i].page_code &
6996			       SMPH_PC_MASK,
6997			       lun->mode_pages.index[i].page_len);
6998#endif
6999			page_len += lun->mode_pages.index[i].page_len;
7000		}
7001		break;
7002	}
7003	default: {
7004		int i;
7005
7006		page_len = 0;
7007
7008		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7009			/* Look for the right page code */
7010			if ((lun->mode_pages.index[i].page_code &
7011			     SMPH_PC_MASK) != page_code)
7012				continue;
7013
7014			/* Look for the right subpage or the subpage wildcard*/
7015			if ((lun->mode_pages.index[i].subpage != subpage)
7016			 && (subpage != SMS_SUBPAGE_ALL))
7017				continue;
7018
7019			/* Make sure the page is supported for this dev type */
7020			if ((control_dev != 0)
7021			 && (lun->mode_pages.index[i].page_flags &
7022			     CTL_PAGE_FLAG_DISK_ONLY))
7023				continue;
7024
7025#if 0
7026			printf("found page %#x len %d\n",
7027			       lun->mode_pages.index[i].page_code &
7028			       SMPH_PC_MASK,
7029			       lun->mode_pages.index[i].page_len);
7030#endif
7031
7032			page_len += lun->mode_pages.index[i].page_len;
7033		}
7034
7035		if (page_len == 0) {
7036			ctl_set_invalid_field(ctsio,
7037					      /*sks_valid*/ 1,
7038					      /*command*/ 1,
7039					      /*field*/ 2,
7040					      /*bit_valid*/ 1,
7041					      /*bit*/ 5);
7042			ctl_done((union ctl_io *)ctsio);
7043			return (CTL_RETVAL_COMPLETE);
7044		}
7045		break;
7046	}
7047	}
7048
7049	total_len = header_len + page_len;
7050#if 0
7051	printf("header_len = %d, page_len = %d, total_len = %d\n",
7052	       header_len, page_len, total_len);
7053#endif
7054
7055	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7056	ctsio->kern_sg_entries = 0;
7057	ctsio->kern_data_resid = 0;
7058	ctsio->kern_rel_offset = 0;
7059	if (total_len < alloc_len) {
7060		ctsio->residual = alloc_len - total_len;
7061		ctsio->kern_data_len = total_len;
7062		ctsio->kern_total_len = total_len;
7063	} else {
7064		ctsio->residual = 0;
7065		ctsio->kern_data_len = alloc_len;
7066		ctsio->kern_total_len = alloc_len;
7067	}
7068
7069	switch (ctsio->cdb[0]) {
7070	case MODE_SENSE_6: {
7071		struct scsi_mode_hdr_6 *header;
7072
7073		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7074
7075		header->datalen = ctl_min(total_len - 1, 254);
7076
7077		if (dbd)
7078			header->block_descr_len = 0;
7079		else
7080			header->block_descr_len =
7081				sizeof(struct scsi_mode_block_descr);
7082		block_desc = (struct scsi_mode_block_descr *)&header[1];
7083		break;
7084	}
7085	case MODE_SENSE_10: {
7086		struct scsi_mode_hdr_10 *header;
7087		int datalen;
7088
7089		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7090
7091		datalen = ctl_min(total_len - 2, 65533);
7092		scsi_ulto2b(datalen, header->datalen);
7093		if (dbd)
7094			scsi_ulto2b(0, header->block_descr_len);
7095		else
7096			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7097				    header->block_descr_len);
7098		block_desc = (struct scsi_mode_block_descr *)&header[1];
7099		break;
7100	}
7101	default:
7102		panic("invalid CDB type %#x", ctsio->cdb[0]);
7103		break; /* NOTREACHED */
7104	}
7105
7106	/*
7107	 * If we've got a disk, use its blocksize in the block
7108	 * descriptor.  Otherwise, just set it to 0.
7109	 */
7110	if (dbd == 0) {
7111		if (control_dev != 0)
7112			scsi_ulto3b(lun->be_lun->blocksize,
7113				    block_desc->block_len);
7114		else
7115			scsi_ulto3b(0, block_desc->block_len);
7116	}
7117
7118	switch (page_code) {
7119	case SMS_ALL_PAGES_PAGE: {
7120		int i, data_used;
7121
7122		data_used = header_len;
7123		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7124			struct ctl_page_index *page_index;
7125
7126			page_index = &lun->mode_pages.index[i];
7127
7128			if ((control_dev != 0)
7129			 && (page_index->page_flags &
7130			    CTL_PAGE_FLAG_DISK_ONLY))
7131				continue;
7132
7133			/*
7134			 * We don't use this subpage if the user didn't
7135			 * request all subpages.  We already checked (above)
7136			 * to make sure the user only specified a subpage
7137			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7138			 */
7139			if ((page_index->subpage != 0)
7140			 && (subpage == SMS_SUBPAGE_PAGE_0))
7141				continue;
7142
7143			/*
7144			 * Call the handler, if it exists, to update the
7145			 * page to the latest values.
7146			 */
7147			if (page_index->sense_handler != NULL)
7148				page_index->sense_handler(ctsio, page_index,pc);
7149
7150			memcpy(ctsio->kern_data_ptr + data_used,
7151			       page_index->page_data +
7152			       (page_index->page_len * pc),
7153			       page_index->page_len);
7154			data_used += page_index->page_len;
7155		}
7156		break;
7157	}
7158	default: {
7159		int i, data_used;
7160
7161		data_used = header_len;
7162
7163		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7164			struct ctl_page_index *page_index;
7165
7166			page_index = &lun->mode_pages.index[i];
7167
7168			/* Look for the right page code */
7169			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7170				continue;
7171
7172			/* Look for the right subpage or the subpage wildcard*/
7173			if ((page_index->subpage != subpage)
7174			 && (subpage != SMS_SUBPAGE_ALL))
7175				continue;
7176
7177			/* Make sure the page is supported for this dev type */
7178			if ((control_dev != 0)
7179			 && (page_index->page_flags &
7180			     CTL_PAGE_FLAG_DISK_ONLY))
7181				continue;
7182
7183			/*
7184			 * Call the handler, if it exists, to update the
7185			 * page to the latest values.
7186			 */
7187			if (page_index->sense_handler != NULL)
7188				page_index->sense_handler(ctsio, page_index,pc);
7189
7190			memcpy(ctsio->kern_data_ptr + data_used,
7191			       page_index->page_data +
7192			       (page_index->page_len * pc),
7193			       page_index->page_len);
7194			data_used += page_index->page_len;
7195		}
7196		break;
7197	}
7198	}
7199
7200	ctsio->scsi_status = SCSI_STATUS_OK;
7201
7202	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7203	ctsio->be_move_done = ctl_config_move_done;
7204	ctl_datamove((union ctl_io *)ctsio);
7205
7206	return (CTL_RETVAL_COMPLETE);
7207}
7208
7209int
7210ctl_read_capacity(struct ctl_scsiio *ctsio)
7211{
7212	struct scsi_read_capacity *cdb;
7213	struct scsi_read_capacity_data *data;
7214	struct ctl_lun *lun;
7215	uint32_t lba;
7216
7217	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7218
7219	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7220
7221	lba = scsi_4btoul(cdb->addr);
7222	if (((cdb->pmi & SRC_PMI) == 0)
7223	 && (lba != 0)) {
7224		ctl_set_invalid_field(/*ctsio*/ ctsio,
7225				      /*sks_valid*/ 1,
7226				      /*command*/ 1,
7227				      /*field*/ 2,
7228				      /*bit_valid*/ 0,
7229				      /*bit*/ 0);
7230		ctl_done((union ctl_io *)ctsio);
7231		return (CTL_RETVAL_COMPLETE);
7232	}
7233
7234	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7235
7236	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7237	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7238	ctsio->residual = 0;
7239	ctsio->kern_data_len = sizeof(*data);
7240	ctsio->kern_total_len = sizeof(*data);
7241	ctsio->kern_data_resid = 0;
7242	ctsio->kern_rel_offset = 0;
7243	ctsio->kern_sg_entries = 0;
7244
7245	/*
7246	 * If the maximum LBA is greater than 0xfffffffe, the user must
7247	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7248	 * serivce action set.
7249	 */
7250	if (lun->be_lun->maxlba > 0xfffffffe)
7251		scsi_ulto4b(0xffffffff, data->addr);
7252	else
7253		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7254
7255	/*
7256	 * XXX KDM this may not be 512 bytes...
7257	 */
7258	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7259
7260	ctsio->scsi_status = SCSI_STATUS_OK;
7261
7262	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7263	ctsio->be_move_done = ctl_config_move_done;
7264	ctl_datamove((union ctl_io *)ctsio);
7265
7266	return (CTL_RETVAL_COMPLETE);
7267}
7268
7269int
7270ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7271{
7272	struct scsi_read_capacity_16 *cdb;
7273	struct scsi_read_capacity_data_long *data;
7274	struct ctl_lun *lun;
7275	uint64_t lba;
7276	uint32_t alloc_len;
7277
7278	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7279
7280	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7281
7282	alloc_len = scsi_4btoul(cdb->alloc_len);
7283	lba = scsi_8btou64(cdb->addr);
7284
7285	if ((cdb->reladr & SRC16_PMI)
7286	 && (lba != 0)) {
7287		ctl_set_invalid_field(/*ctsio*/ ctsio,
7288				      /*sks_valid*/ 1,
7289				      /*command*/ 1,
7290				      /*field*/ 2,
7291				      /*bit_valid*/ 0,
7292				      /*bit*/ 0);
7293		ctl_done((union ctl_io *)ctsio);
7294		return (CTL_RETVAL_COMPLETE);
7295	}
7296
7297	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7298
7299	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7300	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7301
7302	if (sizeof(*data) < alloc_len) {
7303		ctsio->residual = alloc_len - sizeof(*data);
7304		ctsio->kern_data_len = sizeof(*data);
7305		ctsio->kern_total_len = sizeof(*data);
7306	} else {
7307		ctsio->residual = 0;
7308		ctsio->kern_data_len = alloc_len;
7309		ctsio->kern_total_len = alloc_len;
7310	}
7311	ctsio->kern_data_resid = 0;
7312	ctsio->kern_rel_offset = 0;
7313	ctsio->kern_sg_entries = 0;
7314
7315	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7316	/* XXX KDM this may not be 512 bytes... */
7317	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7318	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7319	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7320	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7321		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7322
7323	ctsio->scsi_status = SCSI_STATUS_OK;
7324
7325	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7326	ctsio->be_move_done = ctl_config_move_done;
7327	ctl_datamove((union ctl_io *)ctsio);
7328
7329	return (CTL_RETVAL_COMPLETE);
7330}
7331
7332int
7333ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7334{
7335	struct scsi_maintenance_in *cdb;
7336	int retval;
7337	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7338	int num_target_port_groups, num_target_ports, single;
7339	struct ctl_lun *lun;
7340	struct ctl_softc *softc;
7341	struct ctl_port *port;
7342	struct scsi_target_group_data *rtg_ptr;
7343	struct scsi_target_group_data_extended *rtg_ext_ptr;
7344	struct scsi_target_port_group_descriptor *tpg_desc;
7345
7346	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7347
7348	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7349	softc = control_softc;
7350	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7351
7352	retval = CTL_RETVAL_COMPLETE;
7353
7354	switch (cdb->byte2 & STG_PDF_MASK) {
7355	case STG_PDF_LENGTH:
7356		ext = 0;
7357		break;
7358	case STG_PDF_EXTENDED:
7359		ext = 1;
7360		break;
7361	default:
7362		ctl_set_invalid_field(/*ctsio*/ ctsio,
7363				      /*sks_valid*/ 1,
7364				      /*command*/ 1,
7365				      /*field*/ 2,
7366				      /*bit_valid*/ 1,
7367				      /*bit*/ 5);
7368		ctl_done((union ctl_io *)ctsio);
7369		return(retval);
7370	}
7371
7372	single = ctl_is_single;
7373	if (single)
7374		num_target_port_groups = 1;
7375	else
7376		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7377	num_target_ports = 0;
7378	mtx_lock(&softc->ctl_lock);
7379	STAILQ_FOREACH(port, &softc->port_list, links) {
7380		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7381			continue;
7382		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7383			continue;
7384		num_target_ports++;
7385	}
7386	mtx_unlock(&softc->ctl_lock);
7387
7388	if (ext)
7389		total_len = sizeof(struct scsi_target_group_data_extended);
7390	else
7391		total_len = sizeof(struct scsi_target_group_data);
7392	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7393		num_target_port_groups +
7394	    sizeof(struct scsi_target_port_descriptor) *
7395		num_target_ports * num_target_port_groups;
7396
7397	alloc_len = scsi_4btoul(cdb->length);
7398
7399	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7400
7401	ctsio->kern_sg_entries = 0;
7402
7403	if (total_len < alloc_len) {
7404		ctsio->residual = alloc_len - total_len;
7405		ctsio->kern_data_len = total_len;
7406		ctsio->kern_total_len = total_len;
7407	} else {
7408		ctsio->residual = 0;
7409		ctsio->kern_data_len = alloc_len;
7410		ctsio->kern_total_len = alloc_len;
7411	}
7412	ctsio->kern_data_resid = 0;
7413	ctsio->kern_rel_offset = 0;
7414
7415	if (ext) {
7416		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7417		    ctsio->kern_data_ptr;
7418		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7419		rtg_ext_ptr->format_type = 0x10;
7420		rtg_ext_ptr->implicit_transition_time = 0;
7421		tpg_desc = &rtg_ext_ptr->groups[0];
7422	} else {
7423		rtg_ptr = (struct scsi_target_group_data *)
7424		    ctsio->kern_data_ptr;
7425		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7426		tpg_desc = &rtg_ptr->groups[0];
7427	}
7428
7429	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7430	mtx_lock(&softc->ctl_lock);
7431	for (g = 0; g < num_target_port_groups; g++) {
7432		if (g == pg)
7433			tpg_desc->pref_state = TPG_PRIMARY |
7434			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7435		else
7436			tpg_desc->pref_state =
7437			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7438		tpg_desc->support = TPG_AO_SUP;
7439		if (!single)
7440			tpg_desc->support |= TPG_AN_SUP;
7441		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7442		tpg_desc->status = TPG_IMPLICIT;
7443		pc = 0;
7444		STAILQ_FOREACH(port, &softc->port_list, links) {
7445			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7446				continue;
7447			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7448			    CTL_MAX_LUNS)
7449				continue;
7450			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7451			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7452			    relative_target_port_identifier);
7453			pc++;
7454		}
7455		tpg_desc->target_port_count = pc;
7456		tpg_desc = (struct scsi_target_port_group_descriptor *)
7457		    &tpg_desc->descriptors[pc];
7458	}
7459	mtx_unlock(&softc->ctl_lock);
7460
7461	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7462	ctsio->be_move_done = ctl_config_move_done;
7463
7464	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7465			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7466			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7467			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7468			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7469
7470	ctl_datamove((union ctl_io *)ctsio);
7471	return(retval);
7472}
7473
7474int
7475ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7476{
7477	struct ctl_lun *lun;
7478	struct scsi_report_supported_opcodes *cdb;
7479	const struct ctl_cmd_entry *entry, *sentry;
7480	struct scsi_report_supported_opcodes_all *all;
7481	struct scsi_report_supported_opcodes_descr *descr;
7482	struct scsi_report_supported_opcodes_one *one;
7483	int retval;
7484	int alloc_len, total_len;
7485	int opcode, service_action, i, j, num;
7486
7487	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7488
7489	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7490	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7491
7492	retval = CTL_RETVAL_COMPLETE;
7493
7494	opcode = cdb->requested_opcode;
7495	service_action = scsi_2btoul(cdb->requested_service_action);
7496	switch (cdb->options & RSO_OPTIONS_MASK) {
7497	case RSO_OPTIONS_ALL:
7498		num = 0;
7499		for (i = 0; i < 256; i++) {
7500			entry = &ctl_cmd_table[i];
7501			if (entry->flags & CTL_CMD_FLAG_SA5) {
7502				for (j = 0; j < 32; j++) {
7503					sentry = &((const struct ctl_cmd_entry *)
7504					    entry->execute)[j];
7505					if (ctl_cmd_applicable(
7506					    lun->be_lun->lun_type, sentry))
7507						num++;
7508				}
7509			} else {
7510				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7511				    entry))
7512					num++;
7513			}
7514		}
7515		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7516		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7517		break;
7518	case RSO_OPTIONS_OC:
7519		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7520			ctl_set_invalid_field(/*ctsio*/ ctsio,
7521					      /*sks_valid*/ 1,
7522					      /*command*/ 1,
7523					      /*field*/ 2,
7524					      /*bit_valid*/ 1,
7525					      /*bit*/ 2);
7526			ctl_done((union ctl_io *)ctsio);
7527			return (CTL_RETVAL_COMPLETE);
7528		}
7529		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7530		break;
7531	case RSO_OPTIONS_OC_SA:
7532		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7533		    service_action >= 32) {
7534			ctl_set_invalid_field(/*ctsio*/ ctsio,
7535					      /*sks_valid*/ 1,
7536					      /*command*/ 1,
7537					      /*field*/ 2,
7538					      /*bit_valid*/ 1,
7539					      /*bit*/ 2);
7540			ctl_done((union ctl_io *)ctsio);
7541			return (CTL_RETVAL_COMPLETE);
7542		}
7543		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7544		break;
7545	default:
7546		ctl_set_invalid_field(/*ctsio*/ ctsio,
7547				      /*sks_valid*/ 1,
7548				      /*command*/ 1,
7549				      /*field*/ 2,
7550				      /*bit_valid*/ 1,
7551				      /*bit*/ 2);
7552		ctl_done((union ctl_io *)ctsio);
7553		return (CTL_RETVAL_COMPLETE);
7554	}
7555
7556	alloc_len = scsi_4btoul(cdb->length);
7557
7558	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7559
7560	ctsio->kern_sg_entries = 0;
7561
7562	if (total_len < alloc_len) {
7563		ctsio->residual = alloc_len - total_len;
7564		ctsio->kern_data_len = total_len;
7565		ctsio->kern_total_len = total_len;
7566	} else {
7567		ctsio->residual = 0;
7568		ctsio->kern_data_len = alloc_len;
7569		ctsio->kern_total_len = alloc_len;
7570	}
7571	ctsio->kern_data_resid = 0;
7572	ctsio->kern_rel_offset = 0;
7573
7574	switch (cdb->options & RSO_OPTIONS_MASK) {
7575	case RSO_OPTIONS_ALL:
7576		all = (struct scsi_report_supported_opcodes_all *)
7577		    ctsio->kern_data_ptr;
7578		num = 0;
7579		for (i = 0; i < 256; i++) {
7580			entry = &ctl_cmd_table[i];
7581			if (entry->flags & CTL_CMD_FLAG_SA5) {
7582				for (j = 0; j < 32; j++) {
7583					sentry = &((const struct ctl_cmd_entry *)
7584					    entry->execute)[j];
7585					if (!ctl_cmd_applicable(
7586					    lun->be_lun->lun_type, sentry))
7587						continue;
7588					descr = &all->descr[num++];
7589					descr->opcode = i;
7590					scsi_ulto2b(j, descr->service_action);
7591					descr->flags = RSO_SERVACTV;
7592					scsi_ulto2b(sentry->length,
7593					    descr->cdb_length);
7594				}
7595			} else {
7596				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7597				    entry))
7598					continue;
7599				descr = &all->descr[num++];
7600				descr->opcode = i;
7601				scsi_ulto2b(0, descr->service_action);
7602				descr->flags = 0;
7603				scsi_ulto2b(entry->length, descr->cdb_length);
7604			}
7605		}
7606		scsi_ulto4b(
7607		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7608		    all->length);
7609		break;
7610	case RSO_OPTIONS_OC:
7611		one = (struct scsi_report_supported_opcodes_one *)
7612		    ctsio->kern_data_ptr;
7613		entry = &ctl_cmd_table[opcode];
7614		goto fill_one;
7615	case RSO_OPTIONS_OC_SA:
7616		one = (struct scsi_report_supported_opcodes_one *)
7617		    ctsio->kern_data_ptr;
7618		entry = &ctl_cmd_table[opcode];
7619		entry = &((const struct ctl_cmd_entry *)
7620		    entry->execute)[service_action];
7621fill_one:
7622		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7623			one->support = 3;
7624			scsi_ulto2b(entry->length, one->cdb_length);
7625			one->cdb_usage[0] = opcode;
7626			memcpy(&one->cdb_usage[1], entry->usage,
7627			    entry->length - 1);
7628		} else
7629			one->support = 1;
7630		break;
7631	}
7632
7633	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7634	ctsio->be_move_done = ctl_config_move_done;
7635
7636	ctl_datamove((union ctl_io *)ctsio);
7637	return(retval);
7638}
7639
7640int
7641ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7642{
7643	struct ctl_lun *lun;
7644	struct scsi_report_supported_tmf *cdb;
7645	struct scsi_report_supported_tmf_data *data;
7646	int retval;
7647	int alloc_len, total_len;
7648
7649	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7650
7651	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7652	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7653
7654	retval = CTL_RETVAL_COMPLETE;
7655
7656	total_len = sizeof(struct scsi_report_supported_tmf_data);
7657	alloc_len = scsi_4btoul(cdb->length);
7658
7659	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7660
7661	ctsio->kern_sg_entries = 0;
7662
7663	if (total_len < alloc_len) {
7664		ctsio->residual = alloc_len - total_len;
7665		ctsio->kern_data_len = total_len;
7666		ctsio->kern_total_len = total_len;
7667	} else {
7668		ctsio->residual = 0;
7669		ctsio->kern_data_len = alloc_len;
7670		ctsio->kern_total_len = alloc_len;
7671	}
7672	ctsio->kern_data_resid = 0;
7673	ctsio->kern_rel_offset = 0;
7674
7675	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7676	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7677	data->byte2 |= RST_ITNRS;
7678
7679	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7680	ctsio->be_move_done = ctl_config_move_done;
7681
7682	ctl_datamove((union ctl_io *)ctsio);
7683	return (retval);
7684}
7685
7686int
7687ctl_report_timestamp(struct ctl_scsiio *ctsio)
7688{
7689	struct ctl_lun *lun;
7690	struct scsi_report_timestamp *cdb;
7691	struct scsi_report_timestamp_data *data;
7692	struct timeval tv;
7693	int64_t timestamp;
7694	int retval;
7695	int alloc_len, total_len;
7696
7697	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7698
7699	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7700	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7701
7702	retval = CTL_RETVAL_COMPLETE;
7703
7704	total_len = sizeof(struct scsi_report_timestamp_data);
7705	alloc_len = scsi_4btoul(cdb->length);
7706
7707	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7708
7709	ctsio->kern_sg_entries = 0;
7710
7711	if (total_len < alloc_len) {
7712		ctsio->residual = alloc_len - total_len;
7713		ctsio->kern_data_len = total_len;
7714		ctsio->kern_total_len = total_len;
7715	} else {
7716		ctsio->residual = 0;
7717		ctsio->kern_data_len = alloc_len;
7718		ctsio->kern_total_len = alloc_len;
7719	}
7720	ctsio->kern_data_resid = 0;
7721	ctsio->kern_rel_offset = 0;
7722
7723	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7724	scsi_ulto2b(sizeof(*data) - 2, data->length);
7725	data->origin = RTS_ORIG_OUTSIDE;
7726	getmicrotime(&tv);
7727	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7728	scsi_ulto4b(timestamp >> 16, data->timestamp);
7729	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7730
7731	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7732	ctsio->be_move_done = ctl_config_move_done;
7733
7734	ctl_datamove((union ctl_io *)ctsio);
7735	return (retval);
7736}
7737
7738int
7739ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7740{
7741	struct scsi_per_res_in *cdb;
7742	int alloc_len, total_len = 0;
7743	/* struct scsi_per_res_in_rsrv in_data; */
7744	struct ctl_lun *lun;
7745	struct ctl_softc *softc;
7746
7747	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7748
7749	softc = control_softc;
7750
7751	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7752
7753	alloc_len = scsi_2btoul(cdb->length);
7754
7755	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7756
7757retry:
7758	mtx_lock(&lun->lun_lock);
7759	switch (cdb->action) {
7760	case SPRI_RK: /* read keys */
7761		total_len = sizeof(struct scsi_per_res_in_keys) +
7762			lun->pr_key_count *
7763			sizeof(struct scsi_per_res_key);
7764		break;
7765	case SPRI_RR: /* read reservation */
7766		if (lun->flags & CTL_LUN_PR_RESERVED)
7767			total_len = sizeof(struct scsi_per_res_in_rsrv);
7768		else
7769			total_len = sizeof(struct scsi_per_res_in_header);
7770		break;
7771	case SPRI_RC: /* report capabilities */
7772		total_len = sizeof(struct scsi_per_res_cap);
7773		break;
7774	case SPRI_RS: /* read full status */
7775		total_len = sizeof(struct scsi_per_res_in_header) +
7776		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7777		    lun->pr_key_count;
7778		break;
7779	default:
7780		panic("Invalid PR type %x", cdb->action);
7781	}
7782	mtx_unlock(&lun->lun_lock);
7783
7784	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7785
7786	if (total_len < alloc_len) {
7787		ctsio->residual = alloc_len - total_len;
7788		ctsio->kern_data_len = total_len;
7789		ctsio->kern_total_len = total_len;
7790	} else {
7791		ctsio->residual = 0;
7792		ctsio->kern_data_len = alloc_len;
7793		ctsio->kern_total_len = alloc_len;
7794	}
7795
7796	ctsio->kern_data_resid = 0;
7797	ctsio->kern_rel_offset = 0;
7798	ctsio->kern_sg_entries = 0;
7799
7800	mtx_lock(&lun->lun_lock);
7801	switch (cdb->action) {
7802	case SPRI_RK: { // read keys
7803        struct scsi_per_res_in_keys *res_keys;
7804		int i, key_count;
7805
7806		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7807
7808		/*
7809		 * We had to drop the lock to allocate our buffer, which
7810		 * leaves time for someone to come in with another
7811		 * persistent reservation.  (That is unlikely, though,
7812		 * since this should be the only persistent reservation
7813		 * command active right now.)
7814		 */
7815		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7816		    (lun->pr_key_count *
7817		     sizeof(struct scsi_per_res_key)))){
7818			mtx_unlock(&lun->lun_lock);
7819			free(ctsio->kern_data_ptr, M_CTL);
7820			printf("%s: reservation length changed, retrying\n",
7821			       __func__);
7822			goto retry;
7823		}
7824
7825		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7826
7827		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7828			     lun->pr_key_count, res_keys->header.length);
7829
7830		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7831			if (!lun->per_res[i].registered)
7832				continue;
7833
7834			/*
7835			 * We used lun->pr_key_count to calculate the
7836			 * size to allocate.  If it turns out the number of
7837			 * initiators with the registered flag set is
7838			 * larger than that (i.e. they haven't been kept in
7839			 * sync), we've got a problem.
7840			 */
7841			if (key_count >= lun->pr_key_count) {
7842#ifdef NEEDTOPORT
7843				csevent_log(CSC_CTL | CSC_SHELF_SW |
7844					    CTL_PR_ERROR,
7845					    csevent_LogType_Fault,
7846					    csevent_AlertLevel_Yellow,
7847					    csevent_FRU_ShelfController,
7848					    csevent_FRU_Firmware,
7849				        csevent_FRU_Unknown,
7850					    "registered keys %d >= key "
7851					    "count %d", key_count,
7852					    lun->pr_key_count);
7853#endif
7854				key_count++;
7855				continue;
7856			}
7857			memcpy(res_keys->keys[key_count].key,
7858			       lun->per_res[i].res_key.key,
7859			       ctl_min(sizeof(res_keys->keys[key_count].key),
7860			       sizeof(lun->per_res[i].res_key)));
7861			key_count++;
7862		}
7863		break;
7864	}
7865	case SPRI_RR: { // read reservation
7866		struct scsi_per_res_in_rsrv *res;
7867		int tmp_len, header_only;
7868
7869		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7870
7871		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7872
7873		if (lun->flags & CTL_LUN_PR_RESERVED)
7874		{
7875			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7876			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7877				    res->header.length);
7878			header_only = 0;
7879		} else {
7880			tmp_len = sizeof(struct scsi_per_res_in_header);
7881			scsi_ulto4b(0, res->header.length);
7882			header_only = 1;
7883		}
7884
7885		/*
7886		 * We had to drop the lock to allocate our buffer, which
7887		 * leaves time for someone to come in with another
7888		 * persistent reservation.  (That is unlikely, though,
7889		 * since this should be the only persistent reservation
7890		 * command active right now.)
7891		 */
7892		if (tmp_len != total_len) {
7893			mtx_unlock(&lun->lun_lock);
7894			free(ctsio->kern_data_ptr, M_CTL);
7895			printf("%s: reservation status changed, retrying\n",
7896			       __func__);
7897			goto retry;
7898		}
7899
7900		/*
7901		 * No reservation held, so we're done.
7902		 */
7903		if (header_only != 0)
7904			break;
7905
7906		/*
7907		 * If the registration is an All Registrants type, the key
7908		 * is 0, since it doesn't really matter.
7909		 */
7910		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7911			memcpy(res->data.reservation,
7912			       &lun->per_res[lun->pr_res_idx].res_key,
7913			       sizeof(struct scsi_per_res_key));
7914		}
7915		res->data.scopetype = lun->res_type;
7916		break;
7917	}
7918	case SPRI_RC:     //report capabilities
7919	{
7920		struct scsi_per_res_cap *res_cap;
7921		uint16_t type_mask;
7922
7923		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7924		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7925		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7926		type_mask = SPRI_TM_WR_EX_AR |
7927			    SPRI_TM_EX_AC_RO |
7928			    SPRI_TM_WR_EX_RO |
7929			    SPRI_TM_EX_AC |
7930			    SPRI_TM_WR_EX |
7931			    SPRI_TM_EX_AC_AR;
7932		scsi_ulto2b(type_mask, res_cap->type_mask);
7933		break;
7934	}
7935	case SPRI_RS: { // read full status
7936		struct scsi_per_res_in_full *res_status;
7937		struct scsi_per_res_in_full_desc *res_desc;
7938		struct ctl_port *port;
7939		int i, len;
7940
7941		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7942
7943		/*
7944		 * We had to drop the lock to allocate our buffer, which
7945		 * leaves time for someone to come in with another
7946		 * persistent reservation.  (That is unlikely, though,
7947		 * since this should be the only persistent reservation
7948		 * command active right now.)
7949		 */
7950		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7951		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7952		     lun->pr_key_count)){
7953			mtx_unlock(&lun->lun_lock);
7954			free(ctsio->kern_data_ptr, M_CTL);
7955			printf("%s: reservation length changed, retrying\n",
7956			       __func__);
7957			goto retry;
7958		}
7959
7960		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7961
7962		res_desc = &res_status->desc[0];
7963		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7964			if (!lun->per_res[i].registered)
7965				continue;
7966
7967			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7968			    sizeof(res_desc->res_key));
7969			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7970			    (lun->pr_res_idx == i ||
7971			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7972				res_desc->flags = SPRI_FULL_R_HOLDER;
7973				res_desc->scopetype = lun->res_type;
7974			}
7975			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7976			    res_desc->rel_trgt_port_id);
7977			len = 0;
7978			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7979			if (port != NULL)
7980				len = ctl_create_iid(port,
7981				    i % CTL_MAX_INIT_PER_PORT,
7982				    res_desc->transport_id);
7983			scsi_ulto4b(len, res_desc->additional_length);
7984			res_desc = (struct scsi_per_res_in_full_desc *)
7985			    &res_desc->transport_id[len];
7986		}
7987		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7988		    res_status->header.length);
7989		break;
7990	}
7991	default:
7992		/*
7993		 * This is a bug, because we just checked for this above,
7994		 * and should have returned an error.
7995		 */
7996		panic("Invalid PR type %x", cdb->action);
7997		break; /* NOTREACHED */
7998	}
7999	mtx_unlock(&lun->lun_lock);
8000
8001	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8002	ctsio->be_move_done = ctl_config_move_done;
8003
8004	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8005			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8006			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8007			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8008			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8009
8010	ctl_datamove((union ctl_io *)ctsio);
8011
8012	return (CTL_RETVAL_COMPLETE);
8013}
8014
8015/*
8016 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8017 * it should return.
8018 */
8019static int
8020ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8021		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8022		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8023		struct scsi_per_res_out_parms* param)
8024{
8025	union ctl_ha_msg persis_io;
8026	int retval, i;
8027	int isc_retval;
8028
8029	retval = 0;
8030
8031	mtx_lock(&lun->lun_lock);
8032	if (sa_res_key == 0) {
8033		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8034			/* validate scope and type */
8035			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8036			     SPR_LU_SCOPE) {
8037				mtx_unlock(&lun->lun_lock);
8038				ctl_set_invalid_field(/*ctsio*/ ctsio,
8039						      /*sks_valid*/ 1,
8040						      /*command*/ 1,
8041						      /*field*/ 2,
8042						      /*bit_valid*/ 1,
8043						      /*bit*/ 4);
8044				ctl_done((union ctl_io *)ctsio);
8045				return (1);
8046			}
8047
8048		        if (type>8 || type==2 || type==4 || type==0) {
8049				mtx_unlock(&lun->lun_lock);
8050				ctl_set_invalid_field(/*ctsio*/ ctsio,
8051       	           				      /*sks_valid*/ 1,
8052						      /*command*/ 1,
8053						      /*field*/ 2,
8054						      /*bit_valid*/ 1,
8055						      /*bit*/ 0);
8056				ctl_done((union ctl_io *)ctsio);
8057				return (1);
8058		        }
8059
8060			/* temporarily unregister this nexus */
8061			lun->per_res[residx].registered = 0;
8062
8063			/*
8064			 * Unregister everybody else and build UA for
8065			 * them
8066			 */
8067			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8068				if (lun->per_res[i].registered == 0)
8069					continue;
8070
8071				if (!persis_offset
8072				 && i <CTL_MAX_INITIATORS)
8073					lun->pending_ua[i] |=
8074						CTL_UA_REG_PREEMPT;
8075				else if (persis_offset
8076				      && i >= persis_offset)
8077					lun->pending_ua[i-persis_offset] |=
8078						CTL_UA_REG_PREEMPT;
8079				lun->per_res[i].registered = 0;
8080				memset(&lun->per_res[i].res_key, 0,
8081				       sizeof(struct scsi_per_res_key));
8082			}
8083			lun->per_res[residx].registered = 1;
8084			lun->pr_key_count = 1;
8085			lun->res_type = type;
8086			if (lun->res_type != SPR_TYPE_WR_EX_AR
8087			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8088				lun->pr_res_idx = residx;
8089
8090			/* send msg to other side */
8091			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8092			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8093			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8094			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8095			persis_io.pr.pr_info.res_type = type;
8096			memcpy(persis_io.pr.pr_info.sa_res_key,
8097			       param->serv_act_res_key,
8098			       sizeof(param->serv_act_res_key));
8099			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8100			     &persis_io, sizeof(persis_io), 0)) >
8101			     CTL_HA_STATUS_SUCCESS) {
8102				printf("CTL:Persis Out error returned "
8103				       "from ctl_ha_msg_send %d\n",
8104				       isc_retval);
8105			}
8106		} else {
8107			/* not all registrants */
8108			mtx_unlock(&lun->lun_lock);
8109			free(ctsio->kern_data_ptr, M_CTL);
8110			ctl_set_invalid_field(ctsio,
8111					      /*sks_valid*/ 1,
8112					      /*command*/ 0,
8113					      /*field*/ 8,
8114					      /*bit_valid*/ 0,
8115					      /*bit*/ 0);
8116			ctl_done((union ctl_io *)ctsio);
8117			return (1);
8118		}
8119	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8120		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8121		int found = 0;
8122
8123		if (res_key == sa_res_key) {
8124			/* special case */
8125			/*
8126			 * The spec implies this is not good but doesn't
8127			 * say what to do. There are two choices either
8128			 * generate a res conflict or check condition
8129			 * with illegal field in parameter data. Since
8130			 * that is what is done when the sa_res_key is
8131			 * zero I'll take that approach since this has
8132			 * to do with the sa_res_key.
8133			 */
8134			mtx_unlock(&lun->lun_lock);
8135			free(ctsio->kern_data_ptr, M_CTL);
8136			ctl_set_invalid_field(ctsio,
8137					      /*sks_valid*/ 1,
8138					      /*command*/ 0,
8139					      /*field*/ 8,
8140					      /*bit_valid*/ 0,
8141					      /*bit*/ 0);
8142			ctl_done((union ctl_io *)ctsio);
8143			return (1);
8144		}
8145
8146		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8147			if (lun->per_res[i].registered
8148			 && memcmp(param->serv_act_res_key,
8149			    lun->per_res[i].res_key.key,
8150			    sizeof(struct scsi_per_res_key)) != 0)
8151				continue;
8152
8153			found = 1;
8154			lun->per_res[i].registered = 0;
8155			memset(&lun->per_res[i].res_key, 0,
8156			       sizeof(struct scsi_per_res_key));
8157			lun->pr_key_count--;
8158
8159			if (!persis_offset && i < CTL_MAX_INITIATORS)
8160				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8161			else if (persis_offset && i >= persis_offset)
8162				lun->pending_ua[i-persis_offset] |=
8163					CTL_UA_REG_PREEMPT;
8164		}
8165		if (!found) {
8166			mtx_unlock(&lun->lun_lock);
8167			free(ctsio->kern_data_ptr, M_CTL);
8168			ctl_set_reservation_conflict(ctsio);
8169			ctl_done((union ctl_io *)ctsio);
8170			return (CTL_RETVAL_COMPLETE);
8171		}
8172		/* send msg to other side */
8173		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8174		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8175		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8176		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8177		persis_io.pr.pr_info.res_type = type;
8178		memcpy(persis_io.pr.pr_info.sa_res_key,
8179		       param->serv_act_res_key,
8180		       sizeof(param->serv_act_res_key));
8181		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8182		     &persis_io, sizeof(persis_io), 0)) >
8183		     CTL_HA_STATUS_SUCCESS) {
8184			printf("CTL:Persis Out error returned from "
8185			       "ctl_ha_msg_send %d\n", isc_retval);
8186		}
8187	} else {
8188		/* Reserved but not all registrants */
8189		/* sa_res_key is res holder */
8190		if (memcmp(param->serv_act_res_key,
8191                   lun->per_res[lun->pr_res_idx].res_key.key,
8192                   sizeof(struct scsi_per_res_key)) == 0) {
8193			/* validate scope and type */
8194			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8195			     SPR_LU_SCOPE) {
8196				mtx_unlock(&lun->lun_lock);
8197				ctl_set_invalid_field(/*ctsio*/ ctsio,
8198						      /*sks_valid*/ 1,
8199						      /*command*/ 1,
8200						      /*field*/ 2,
8201						      /*bit_valid*/ 1,
8202						      /*bit*/ 4);
8203				ctl_done((union ctl_io *)ctsio);
8204				return (1);
8205			}
8206
8207			if (type>8 || type==2 || type==4 || type==0) {
8208				mtx_unlock(&lun->lun_lock);
8209				ctl_set_invalid_field(/*ctsio*/ ctsio,
8210						      /*sks_valid*/ 1,
8211						      /*command*/ 1,
8212						      /*field*/ 2,
8213						      /*bit_valid*/ 1,
8214						      /*bit*/ 0);
8215				ctl_done((union ctl_io *)ctsio);
8216				return (1);
8217			}
8218
8219			/*
8220			 * Do the following:
8221			 * if sa_res_key != res_key remove all
8222			 * registrants w/sa_res_key and generate UA
8223			 * for these registrants(Registrations
8224			 * Preempted) if it wasn't an exclusive
8225			 * reservation generate UA(Reservations
8226			 * Preempted) for all other registered nexuses
8227			 * if the type has changed. Establish the new
8228			 * reservation and holder. If res_key and
8229			 * sa_res_key are the same do the above
8230			 * except don't unregister the res holder.
8231			 */
8232
8233			/*
8234			 * Temporarily unregister so it won't get
8235			 * removed or UA generated
8236			 */
8237			lun->per_res[residx].registered = 0;
8238			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8239				if (lun->per_res[i].registered == 0)
8240					continue;
8241
8242				if (memcmp(param->serv_act_res_key,
8243				    lun->per_res[i].res_key.key,
8244				    sizeof(struct scsi_per_res_key)) == 0) {
8245					lun->per_res[i].registered = 0;
8246					memset(&lun->per_res[i].res_key,
8247					       0,
8248					       sizeof(struct scsi_per_res_key));
8249					lun->pr_key_count--;
8250
8251					if (!persis_offset
8252					 && i < CTL_MAX_INITIATORS)
8253						lun->pending_ua[i] |=
8254							CTL_UA_REG_PREEMPT;
8255					else if (persis_offset
8256					      && i >= persis_offset)
8257						lun->pending_ua[i-persis_offset] |=
8258						  CTL_UA_REG_PREEMPT;
8259				} else if (type != lun->res_type
8260					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8261					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8262						if (!persis_offset
8263						 && i < CTL_MAX_INITIATORS)
8264							lun->pending_ua[i] |=
8265							CTL_UA_RES_RELEASE;
8266						else if (persis_offset
8267						      && i >= persis_offset)
8268							lun->pending_ua[
8269							i-persis_offset] |=
8270							CTL_UA_RES_RELEASE;
8271				}
8272			}
8273			lun->per_res[residx].registered = 1;
8274			lun->res_type = type;
8275			if (lun->res_type != SPR_TYPE_WR_EX_AR
8276			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8277				lun->pr_res_idx = residx;
8278			else
8279				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8280
8281			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8282			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8283			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8284			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8285			persis_io.pr.pr_info.res_type = type;
8286			memcpy(persis_io.pr.pr_info.sa_res_key,
8287			       param->serv_act_res_key,
8288			       sizeof(param->serv_act_res_key));
8289			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8290			     &persis_io, sizeof(persis_io), 0)) >
8291			     CTL_HA_STATUS_SUCCESS) {
8292				printf("CTL:Persis Out error returned "
8293				       "from ctl_ha_msg_send %d\n",
8294				       isc_retval);
8295			}
8296		} else {
8297			/*
8298			 * sa_res_key is not the res holder just
8299			 * remove registrants
8300			 */
8301			int found=0;
8302
8303			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8304				if (memcmp(param->serv_act_res_key,
8305				    lun->per_res[i].res_key.key,
8306				    sizeof(struct scsi_per_res_key)) != 0)
8307					continue;
8308
8309				found = 1;
8310				lun->per_res[i].registered = 0;
8311				memset(&lun->per_res[i].res_key, 0,
8312				       sizeof(struct scsi_per_res_key));
8313				lun->pr_key_count--;
8314
8315				if (!persis_offset
8316				 && i < CTL_MAX_INITIATORS)
8317					lun->pending_ua[i] |=
8318						CTL_UA_REG_PREEMPT;
8319				else if (persis_offset
8320				      && i >= persis_offset)
8321					lun->pending_ua[i-persis_offset] |=
8322						CTL_UA_REG_PREEMPT;
8323			}
8324
8325			if (!found) {
8326				mtx_unlock(&lun->lun_lock);
8327				free(ctsio->kern_data_ptr, M_CTL);
8328				ctl_set_reservation_conflict(ctsio);
8329				ctl_done((union ctl_io *)ctsio);
8330		        	return (1);
8331			}
8332			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8333			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8334			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8335			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8336			persis_io.pr.pr_info.res_type = type;
8337			memcpy(persis_io.pr.pr_info.sa_res_key,
8338			       param->serv_act_res_key,
8339			       sizeof(param->serv_act_res_key));
8340			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8341			     &persis_io, sizeof(persis_io), 0)) >
8342			     CTL_HA_STATUS_SUCCESS) {
8343				printf("CTL:Persis Out error returned "
8344				       "from ctl_ha_msg_send %d\n",
8345				isc_retval);
8346			}
8347		}
8348	}
8349
8350	lun->PRGeneration++;
8351	mtx_unlock(&lun->lun_lock);
8352
8353	return (retval);
8354}
8355
8356static void
8357ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8358{
8359	int i;
8360
8361	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8362	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8363	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8364		   msg->pr.pr_info.sa_res_key,
8365		   sizeof(struct scsi_per_res_key)) != 0) {
8366		uint64_t sa_res_key;
8367		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8368
8369		if (sa_res_key == 0) {
8370			/* temporarily unregister this nexus */
8371			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8372
8373			/*
8374			 * Unregister everybody else and build UA for
8375			 * them
8376			 */
8377			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8378				if (lun->per_res[i].registered == 0)
8379					continue;
8380
8381				if (!persis_offset
8382				 && i < CTL_MAX_INITIATORS)
8383					lun->pending_ua[i] |=
8384						CTL_UA_REG_PREEMPT;
8385				else if (persis_offset && i >= persis_offset)
8386					lun->pending_ua[i - persis_offset] |=
8387						CTL_UA_REG_PREEMPT;
8388				lun->per_res[i].registered = 0;
8389				memset(&lun->per_res[i].res_key, 0,
8390				       sizeof(struct scsi_per_res_key));
8391			}
8392
8393			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8394			lun->pr_key_count = 1;
8395			lun->res_type = msg->pr.pr_info.res_type;
8396			if (lun->res_type != SPR_TYPE_WR_EX_AR
8397			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8398				lun->pr_res_idx = msg->pr.pr_info.residx;
8399		} else {
8400		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8401				if (memcmp(msg->pr.pr_info.sa_res_key,
8402		                   lun->per_res[i].res_key.key,
8403		                   sizeof(struct scsi_per_res_key)) != 0)
8404					continue;
8405
8406				lun->per_res[i].registered = 0;
8407				memset(&lun->per_res[i].res_key, 0,
8408				       sizeof(struct scsi_per_res_key));
8409				lun->pr_key_count--;
8410
8411				if (!persis_offset
8412				 && i < persis_offset)
8413					lun->pending_ua[i] |=
8414						CTL_UA_REG_PREEMPT;
8415				else if (persis_offset
8416				      && i >= persis_offset)
8417					lun->pending_ua[i - persis_offset] |=
8418						CTL_UA_REG_PREEMPT;
8419			}
8420		}
8421	} else {
8422		/*
8423		 * Temporarily unregister so it won't get removed
8424		 * or UA generated
8425		 */
8426		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8427		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8428			if (lun->per_res[i].registered == 0)
8429				continue;
8430
8431			if (memcmp(msg->pr.pr_info.sa_res_key,
8432	                   lun->per_res[i].res_key.key,
8433	                   sizeof(struct scsi_per_res_key)) == 0) {
8434				lun->per_res[i].registered = 0;
8435				memset(&lun->per_res[i].res_key, 0,
8436				       sizeof(struct scsi_per_res_key));
8437				lun->pr_key_count--;
8438				if (!persis_offset
8439				 && i < CTL_MAX_INITIATORS)
8440					lun->pending_ua[i] |=
8441						CTL_UA_REG_PREEMPT;
8442				else if (persis_offset
8443				      && i >= persis_offset)
8444					lun->pending_ua[i - persis_offset] |=
8445						CTL_UA_REG_PREEMPT;
8446			} else if (msg->pr.pr_info.res_type != lun->res_type
8447				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8448				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8449					if (!persis_offset
8450					 && i < persis_offset)
8451						lun->pending_ua[i] |=
8452							CTL_UA_RES_RELEASE;
8453					else if (persis_offset
8454					      && i >= persis_offset)
8455					lun->pending_ua[i - persis_offset] |=
8456						CTL_UA_RES_RELEASE;
8457			}
8458		}
8459		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8460		lun->res_type = msg->pr.pr_info.res_type;
8461		if (lun->res_type != SPR_TYPE_WR_EX_AR
8462		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8463			lun->pr_res_idx = msg->pr.pr_info.residx;
8464		else
8465			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8466	}
8467	lun->PRGeneration++;
8468
8469}
8470
8471
8472int
8473ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8474{
8475	int retval;
8476	int isc_retval;
8477	u_int32_t param_len;
8478	struct scsi_per_res_out *cdb;
8479	struct ctl_lun *lun;
8480	struct scsi_per_res_out_parms* param;
8481	struct ctl_softc *softc;
8482	uint32_t residx;
8483	uint64_t res_key, sa_res_key;
8484	uint8_t type;
8485	union ctl_ha_msg persis_io;
8486	int    i;
8487
8488	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8489
8490	retval = CTL_RETVAL_COMPLETE;
8491
8492	softc = control_softc;
8493
8494	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8495	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8496
8497	/*
8498	 * We only support whole-LUN scope.  The scope & type are ignored for
8499	 * register, register and ignore existing key and clear.
8500	 * We sometimes ignore scope and type on preempts too!!
8501	 * Verify reservation type here as well.
8502	 */
8503	type = cdb->scope_type & SPR_TYPE_MASK;
8504	if ((cdb->action == SPRO_RESERVE)
8505	 || (cdb->action == SPRO_RELEASE)) {
8506		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8507			ctl_set_invalid_field(/*ctsio*/ ctsio,
8508					      /*sks_valid*/ 1,
8509					      /*command*/ 1,
8510					      /*field*/ 2,
8511					      /*bit_valid*/ 1,
8512					      /*bit*/ 4);
8513			ctl_done((union ctl_io *)ctsio);
8514			return (CTL_RETVAL_COMPLETE);
8515		}
8516
8517		if (type>8 || type==2 || type==4 || type==0) {
8518			ctl_set_invalid_field(/*ctsio*/ ctsio,
8519					      /*sks_valid*/ 1,
8520					      /*command*/ 1,
8521					      /*field*/ 2,
8522					      /*bit_valid*/ 1,
8523					      /*bit*/ 0);
8524			ctl_done((union ctl_io *)ctsio);
8525			return (CTL_RETVAL_COMPLETE);
8526		}
8527	}
8528
8529	param_len = scsi_4btoul(cdb->length);
8530
8531	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8532		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8533		ctsio->kern_data_len = param_len;
8534		ctsio->kern_total_len = param_len;
8535		ctsio->kern_data_resid = 0;
8536		ctsio->kern_rel_offset = 0;
8537		ctsio->kern_sg_entries = 0;
8538		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8539		ctsio->be_move_done = ctl_config_move_done;
8540		ctl_datamove((union ctl_io *)ctsio);
8541
8542		return (CTL_RETVAL_COMPLETE);
8543	}
8544
8545	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8546
8547	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8548	res_key = scsi_8btou64(param->res_key.key);
8549	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8550
8551	/*
8552	 * Validate the reservation key here except for SPRO_REG_IGNO
8553	 * This must be done for all other service actions
8554	 */
8555	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8556		mtx_lock(&lun->lun_lock);
8557		if (lun->per_res[residx].registered) {
8558		    if (memcmp(param->res_key.key,
8559			       lun->per_res[residx].res_key.key,
8560			       ctl_min(sizeof(param->res_key),
8561			       sizeof(lun->per_res[residx].res_key))) != 0) {
8562				/*
8563				 * The current key passed in doesn't match
8564				 * the one the initiator previously
8565				 * registered.
8566				 */
8567				mtx_unlock(&lun->lun_lock);
8568				free(ctsio->kern_data_ptr, M_CTL);
8569				ctl_set_reservation_conflict(ctsio);
8570				ctl_done((union ctl_io *)ctsio);
8571				return (CTL_RETVAL_COMPLETE);
8572			}
8573		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8574			/*
8575			 * We are not registered
8576			 */
8577			mtx_unlock(&lun->lun_lock);
8578			free(ctsio->kern_data_ptr, M_CTL);
8579			ctl_set_reservation_conflict(ctsio);
8580			ctl_done((union ctl_io *)ctsio);
8581			return (CTL_RETVAL_COMPLETE);
8582		} else if (res_key != 0) {
8583			/*
8584			 * We are not registered and trying to register but
8585			 * the register key isn't zero.
8586			 */
8587			mtx_unlock(&lun->lun_lock);
8588			free(ctsio->kern_data_ptr, M_CTL);
8589			ctl_set_reservation_conflict(ctsio);
8590			ctl_done((union ctl_io *)ctsio);
8591			return (CTL_RETVAL_COMPLETE);
8592		}
8593		mtx_unlock(&lun->lun_lock);
8594	}
8595
8596	switch (cdb->action & SPRO_ACTION_MASK) {
8597	case SPRO_REGISTER:
8598	case SPRO_REG_IGNO: {
8599
8600#if 0
8601		printf("Registration received\n");
8602#endif
8603
8604		/*
8605		 * We don't support any of these options, as we report in
8606		 * the read capabilities request (see
8607		 * ctl_persistent_reserve_in(), above).
8608		 */
8609		if ((param->flags & SPR_SPEC_I_PT)
8610		 || (param->flags & SPR_ALL_TG_PT)
8611		 || (param->flags & SPR_APTPL)) {
8612			int bit_ptr;
8613
8614			if (param->flags & SPR_APTPL)
8615				bit_ptr = 0;
8616			else if (param->flags & SPR_ALL_TG_PT)
8617				bit_ptr = 2;
8618			else /* SPR_SPEC_I_PT */
8619				bit_ptr = 3;
8620
8621			free(ctsio->kern_data_ptr, M_CTL);
8622			ctl_set_invalid_field(ctsio,
8623					      /*sks_valid*/ 1,
8624					      /*command*/ 0,
8625					      /*field*/ 20,
8626					      /*bit_valid*/ 1,
8627					      /*bit*/ bit_ptr);
8628			ctl_done((union ctl_io *)ctsio);
8629			return (CTL_RETVAL_COMPLETE);
8630		}
8631
8632		mtx_lock(&lun->lun_lock);
8633
8634		/*
8635		 * The initiator wants to clear the
8636		 * key/unregister.
8637		 */
8638		if (sa_res_key == 0) {
8639			if ((res_key == 0
8640			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8641			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8642			  && !lun->per_res[residx].registered)) {
8643				mtx_unlock(&lun->lun_lock);
8644				goto done;
8645			}
8646
8647			lun->per_res[residx].registered = 0;
8648			memset(&lun->per_res[residx].res_key,
8649			       0, sizeof(lun->per_res[residx].res_key));
8650			lun->pr_key_count--;
8651
8652			if (residx == lun->pr_res_idx) {
8653				lun->flags &= ~CTL_LUN_PR_RESERVED;
8654				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8655
8656				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8657				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8658				 && lun->pr_key_count) {
8659					/*
8660					 * If the reservation is a registrants
8661					 * only type we need to generate a UA
8662					 * for other registered inits.  The
8663					 * sense code should be RESERVATIONS
8664					 * RELEASED
8665					 */
8666
8667					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8668						if (lun->per_res[
8669						    i+persis_offset].registered
8670						    == 0)
8671							continue;
8672						lun->pending_ua[i] |=
8673							CTL_UA_RES_RELEASE;
8674					}
8675				}
8676				lun->res_type = 0;
8677			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8678				if (lun->pr_key_count==0) {
8679					lun->flags &= ~CTL_LUN_PR_RESERVED;
8680					lun->res_type = 0;
8681					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8682				}
8683			}
8684			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8685			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8686			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8687			persis_io.pr.pr_info.residx = residx;
8688			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8689			     &persis_io, sizeof(persis_io), 0 )) >
8690			     CTL_HA_STATUS_SUCCESS) {
8691				printf("CTL:Persis Out error returned from "
8692				       "ctl_ha_msg_send %d\n", isc_retval);
8693			}
8694		} else /* sa_res_key != 0 */ {
8695
8696			/*
8697			 * If we aren't registered currently then increment
8698			 * the key count and set the registered flag.
8699			 */
8700			if (!lun->per_res[residx].registered) {
8701				lun->pr_key_count++;
8702				lun->per_res[residx].registered = 1;
8703			}
8704
8705			memcpy(&lun->per_res[residx].res_key,
8706			       param->serv_act_res_key,
8707			       ctl_min(sizeof(param->serv_act_res_key),
8708			       sizeof(lun->per_res[residx].res_key)));
8709
8710			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8711			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8712			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8713			persis_io.pr.pr_info.residx = residx;
8714			memcpy(persis_io.pr.pr_info.sa_res_key,
8715			       param->serv_act_res_key,
8716			       sizeof(param->serv_act_res_key));
8717			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8718			     &persis_io, sizeof(persis_io), 0)) >
8719			     CTL_HA_STATUS_SUCCESS) {
8720				printf("CTL:Persis Out error returned from "
8721				       "ctl_ha_msg_send %d\n", isc_retval);
8722			}
8723		}
8724		lun->PRGeneration++;
8725		mtx_unlock(&lun->lun_lock);
8726
8727		break;
8728	}
8729	case SPRO_RESERVE:
8730#if 0
8731                printf("Reserve executed type %d\n", type);
8732#endif
8733		mtx_lock(&lun->lun_lock);
8734		if (lun->flags & CTL_LUN_PR_RESERVED) {
8735			/*
8736			 * if this isn't the reservation holder and it's
8737			 * not a "all registrants" type or if the type is
8738			 * different then we have a conflict
8739			 */
8740			if ((lun->pr_res_idx != residx
8741			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8742			 || lun->res_type != type) {
8743				mtx_unlock(&lun->lun_lock);
8744				free(ctsio->kern_data_ptr, M_CTL);
8745				ctl_set_reservation_conflict(ctsio);
8746				ctl_done((union ctl_io *)ctsio);
8747				return (CTL_RETVAL_COMPLETE);
8748			}
8749			mtx_unlock(&lun->lun_lock);
8750		} else /* create a reservation */ {
8751			/*
8752			 * If it's not an "all registrants" type record
8753			 * reservation holder
8754			 */
8755			if (type != SPR_TYPE_WR_EX_AR
8756			 && type != SPR_TYPE_EX_AC_AR)
8757				lun->pr_res_idx = residx; /* Res holder */
8758			else
8759				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8760
8761			lun->flags |= CTL_LUN_PR_RESERVED;
8762			lun->res_type = type;
8763
8764			mtx_unlock(&lun->lun_lock);
8765
8766			/* send msg to other side */
8767			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8768			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8769			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8770			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8771			persis_io.pr.pr_info.res_type = type;
8772			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8773			     &persis_io, sizeof(persis_io), 0)) >
8774			     CTL_HA_STATUS_SUCCESS) {
8775				printf("CTL:Persis Out error returned from "
8776				       "ctl_ha_msg_send %d\n", isc_retval);
8777			}
8778		}
8779		break;
8780
8781	case SPRO_RELEASE:
8782		mtx_lock(&lun->lun_lock);
8783		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8784			/* No reservation exists return good status */
8785			mtx_unlock(&lun->lun_lock);
8786			goto done;
8787		}
8788		/*
8789		 * Is this nexus a reservation holder?
8790		 */
8791		if (lun->pr_res_idx != residx
8792		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8793			/*
8794			 * not a res holder return good status but
8795			 * do nothing
8796			 */
8797			mtx_unlock(&lun->lun_lock);
8798			goto done;
8799		}
8800
8801		if (lun->res_type != type) {
8802			mtx_unlock(&lun->lun_lock);
8803			free(ctsio->kern_data_ptr, M_CTL);
8804			ctl_set_illegal_pr_release(ctsio);
8805			ctl_done((union ctl_io *)ctsio);
8806			return (CTL_RETVAL_COMPLETE);
8807		}
8808
8809		/* okay to release */
8810		lun->flags &= ~CTL_LUN_PR_RESERVED;
8811		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8812		lun->res_type = 0;
8813
8814		/*
8815		 * if this isn't an exclusive access
8816		 * res generate UA for all other
8817		 * registrants.
8818		 */
8819		if (type != SPR_TYPE_EX_AC
8820		 && type != SPR_TYPE_WR_EX) {
8821			/*
8822			 * temporarily unregister so we don't generate UA
8823			 */
8824			lun->per_res[residx].registered = 0;
8825
8826			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8827				if (lun->per_res[i+persis_offset].registered
8828				    == 0)
8829					continue;
8830				lun->pending_ua[i] |=
8831					CTL_UA_RES_RELEASE;
8832			}
8833
8834			lun->per_res[residx].registered = 1;
8835		}
8836		mtx_unlock(&lun->lun_lock);
8837		/* Send msg to other side */
8838		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8839		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8840		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8841		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8842		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8843			printf("CTL:Persis Out error returned from "
8844			       "ctl_ha_msg_send %d\n", isc_retval);
8845		}
8846		break;
8847
8848	case SPRO_CLEAR:
8849		/* send msg to other side */
8850
8851		mtx_lock(&lun->lun_lock);
8852		lun->flags &= ~CTL_LUN_PR_RESERVED;
8853		lun->res_type = 0;
8854		lun->pr_key_count = 0;
8855		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8856
8857
8858		memset(&lun->per_res[residx].res_key,
8859		       0, sizeof(lun->per_res[residx].res_key));
8860		lun->per_res[residx].registered = 0;
8861
8862		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8863			if (lun->per_res[i].registered) {
8864				if (!persis_offset && i < CTL_MAX_INITIATORS)
8865					lun->pending_ua[i] |=
8866						CTL_UA_RES_PREEMPT;
8867				else if (persis_offset && i >= persis_offset)
8868					lun->pending_ua[i-persis_offset] |=
8869					    CTL_UA_RES_PREEMPT;
8870
8871				memset(&lun->per_res[i].res_key,
8872				       0, sizeof(struct scsi_per_res_key));
8873				lun->per_res[i].registered = 0;
8874			}
8875		lun->PRGeneration++;
8876		mtx_unlock(&lun->lun_lock);
8877		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8878		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8879		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8880		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8881		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8882			printf("CTL:Persis Out error returned from "
8883			       "ctl_ha_msg_send %d\n", isc_retval);
8884		}
8885		break;
8886
8887	case SPRO_PREEMPT: {
8888		int nretval;
8889
8890		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8891					  residx, ctsio, cdb, param);
8892		if (nretval != 0)
8893			return (CTL_RETVAL_COMPLETE);
8894		break;
8895	}
8896	default:
8897		panic("Invalid PR type %x", cdb->action);
8898	}
8899
8900done:
8901	free(ctsio->kern_data_ptr, M_CTL);
8902	ctl_set_success(ctsio);
8903	ctl_done((union ctl_io *)ctsio);
8904
8905	return (retval);
8906}
8907
8908/*
8909 * This routine is for handling a message from the other SC pertaining to
8910 * persistent reserve out. All the error checking will have been done
8911 * so only perorming the action need be done here to keep the two
8912 * in sync.
8913 */
8914static void
8915ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8916{
8917	struct ctl_lun *lun;
8918	struct ctl_softc *softc;
8919	int i;
8920	uint32_t targ_lun;
8921
8922	softc = control_softc;
8923
8924	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8925	lun = softc->ctl_luns[targ_lun];
8926	mtx_lock(&lun->lun_lock);
8927	switch(msg->pr.pr_info.action) {
8928	case CTL_PR_REG_KEY:
8929		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8930			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8931			lun->pr_key_count++;
8932		}
8933		lun->PRGeneration++;
8934		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8935		       msg->pr.pr_info.sa_res_key,
8936		       sizeof(struct scsi_per_res_key));
8937		break;
8938
8939	case CTL_PR_UNREG_KEY:
8940		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8941		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8942		       0, sizeof(struct scsi_per_res_key));
8943		lun->pr_key_count--;
8944
8945		/* XXX Need to see if the reservation has been released */
8946		/* if so do we need to generate UA? */
8947		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8948			lun->flags &= ~CTL_LUN_PR_RESERVED;
8949			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8950
8951			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8952			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8953			 && lun->pr_key_count) {
8954				/*
8955				 * If the reservation is a registrants
8956				 * only type we need to generate a UA
8957				 * for other registered inits.  The
8958				 * sense code should be RESERVATIONS
8959				 * RELEASED
8960				 */
8961
8962				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8963					if (lun->per_res[i+
8964					    persis_offset].registered == 0)
8965						continue;
8966
8967					lun->pending_ua[i] |=
8968						CTL_UA_RES_RELEASE;
8969				}
8970			}
8971			lun->res_type = 0;
8972		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8973			if (lun->pr_key_count==0) {
8974				lun->flags &= ~CTL_LUN_PR_RESERVED;
8975				lun->res_type = 0;
8976				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8977			}
8978		}
8979		lun->PRGeneration++;
8980		break;
8981
8982	case CTL_PR_RESERVE:
8983		lun->flags |= CTL_LUN_PR_RESERVED;
8984		lun->res_type = msg->pr.pr_info.res_type;
8985		lun->pr_res_idx = msg->pr.pr_info.residx;
8986
8987		break;
8988
8989	case CTL_PR_RELEASE:
8990		/*
8991		 * if this isn't an exclusive access res generate UA for all
8992		 * other registrants.
8993		 */
8994		if (lun->res_type != SPR_TYPE_EX_AC
8995		 && lun->res_type != SPR_TYPE_WR_EX) {
8996			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8997				if (lun->per_res[i+persis_offset].registered)
8998					lun->pending_ua[i] |=
8999						CTL_UA_RES_RELEASE;
9000		}
9001
9002		lun->flags &= ~CTL_LUN_PR_RESERVED;
9003		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9004		lun->res_type = 0;
9005		break;
9006
9007	case CTL_PR_PREEMPT:
9008		ctl_pro_preempt_other(lun, msg);
9009		break;
9010	case CTL_PR_CLEAR:
9011		lun->flags &= ~CTL_LUN_PR_RESERVED;
9012		lun->res_type = 0;
9013		lun->pr_key_count = 0;
9014		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9015
9016		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9017			if (lun->per_res[i].registered == 0)
9018				continue;
9019			if (!persis_offset
9020			 && i < CTL_MAX_INITIATORS)
9021				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9022			else if (persis_offset
9023			      && i >= persis_offset)
9024				lun->pending_ua[i-persis_offset] |=
9025					CTL_UA_RES_PREEMPT;
9026			memset(&lun->per_res[i].res_key, 0,
9027			       sizeof(struct scsi_per_res_key));
9028			lun->per_res[i].registered = 0;
9029		}
9030		lun->PRGeneration++;
9031		break;
9032	}
9033
9034	mtx_unlock(&lun->lun_lock);
9035}
9036
9037int
9038ctl_read_write(struct ctl_scsiio *ctsio)
9039{
9040	struct ctl_lun *lun;
9041	struct ctl_lba_len_flags *lbalen;
9042	uint64_t lba;
9043	uint32_t num_blocks;
9044	int flags, retval;
9045	int isread;
9046
9047	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9048
9049	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9050
9051	flags = 0;
9052	retval = CTL_RETVAL_COMPLETE;
9053
9054	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9055	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9056	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9057		uint32_t residx;
9058
9059		/*
9060		 * XXX KDM need a lock here.
9061		 */
9062		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9063		if ((lun->res_type == SPR_TYPE_EX_AC
9064		  && residx != lun->pr_res_idx)
9065		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9066		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9067		  && !lun->per_res[residx].registered)) {
9068			ctl_set_reservation_conflict(ctsio);
9069			ctl_done((union ctl_io *)ctsio);
9070			return (CTL_RETVAL_COMPLETE);
9071	        }
9072	}
9073
9074	switch (ctsio->cdb[0]) {
9075	case READ_6:
9076	case WRITE_6: {
9077		struct scsi_rw_6 *cdb;
9078
9079		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9080
9081		lba = scsi_3btoul(cdb->addr);
9082		/* only 5 bits are valid in the most significant address byte */
9083		lba &= 0x1fffff;
9084		num_blocks = cdb->length;
9085		/*
9086		 * This is correct according to SBC-2.
9087		 */
9088		if (num_blocks == 0)
9089			num_blocks = 256;
9090		break;
9091	}
9092	case READ_10:
9093	case WRITE_10: {
9094		struct scsi_rw_10 *cdb;
9095
9096		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9097		if (cdb->byte2 & SRW10_FUA)
9098			flags |= CTL_LLF_FUA;
9099		if (cdb->byte2 & SRW10_DPO)
9100			flags |= CTL_LLF_DPO;
9101		lba = scsi_4btoul(cdb->addr);
9102		num_blocks = scsi_2btoul(cdb->length);
9103		break;
9104	}
9105	case WRITE_VERIFY_10: {
9106		struct scsi_write_verify_10 *cdb;
9107
9108		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9109		flags |= CTL_LLF_FUA;
9110		if (cdb->byte2 & SWV_DPO)
9111			flags |= CTL_LLF_DPO;
9112		lba = scsi_4btoul(cdb->addr);
9113		num_blocks = scsi_2btoul(cdb->length);
9114		break;
9115	}
9116	case READ_12:
9117	case WRITE_12: {
9118		struct scsi_rw_12 *cdb;
9119
9120		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9121		if (cdb->byte2 & SRW12_FUA)
9122			flags |= CTL_LLF_FUA;
9123		if (cdb->byte2 & SRW12_DPO)
9124			flags |= CTL_LLF_DPO;
9125		lba = scsi_4btoul(cdb->addr);
9126		num_blocks = scsi_4btoul(cdb->length);
9127		break;
9128	}
9129	case WRITE_VERIFY_12: {
9130		struct scsi_write_verify_12 *cdb;
9131
9132		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9133		flags |= CTL_LLF_FUA;
9134		if (cdb->byte2 & SWV_DPO)
9135			flags |= CTL_LLF_DPO;
9136		lba = scsi_4btoul(cdb->addr);
9137		num_blocks = scsi_4btoul(cdb->length);
9138		break;
9139	}
9140	case READ_16:
9141	case WRITE_16: {
9142		struct scsi_rw_16 *cdb;
9143
9144		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9145		if (cdb->byte2 & SRW12_FUA)
9146			flags |= CTL_LLF_FUA;
9147		if (cdb->byte2 & SRW12_DPO)
9148			flags |= CTL_LLF_DPO;
9149		lba = scsi_8btou64(cdb->addr);
9150		num_blocks = scsi_4btoul(cdb->length);
9151		break;
9152	}
9153	case WRITE_VERIFY_16: {
9154		struct scsi_write_verify_16 *cdb;
9155
9156		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9157		flags |= CTL_LLF_FUA;
9158		if (cdb->byte2 & SWV_DPO)
9159			flags |= CTL_LLF_DPO;
9160		lba = scsi_8btou64(cdb->addr);
9161		num_blocks = scsi_4btoul(cdb->length);
9162		break;
9163	}
9164	default:
9165		/*
9166		 * We got a command we don't support.  This shouldn't
9167		 * happen, commands should be filtered out above us.
9168		 */
9169		ctl_set_invalid_opcode(ctsio);
9170		ctl_done((union ctl_io *)ctsio);
9171
9172		return (CTL_RETVAL_COMPLETE);
9173		break; /* NOTREACHED */
9174	}
9175
9176	/*
9177	 * The first check is to make sure we're in bounds, the second
9178	 * check is to catch wrap-around problems.  If the lba + num blocks
9179	 * is less than the lba, then we've wrapped around and the block
9180	 * range is invalid anyway.
9181	 */
9182	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9183	 || ((lba + num_blocks) < lba)) {
9184		ctl_set_lba_out_of_range(ctsio);
9185		ctl_done((union ctl_io *)ctsio);
9186		return (CTL_RETVAL_COMPLETE);
9187	}
9188
9189	/*
9190	 * According to SBC-3, a transfer length of 0 is not an error.
9191	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9192	 * translates to 256 blocks for those commands.
9193	 */
9194	if (num_blocks == 0) {
9195		ctl_set_success(ctsio);
9196		ctl_done((union ctl_io *)ctsio);
9197		return (CTL_RETVAL_COMPLETE);
9198	}
9199
9200	/* Set FUA and/or DPO if caches are disabled. */
9201	if (isread) {
9202		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9203		    SCP_RCD) != 0)
9204			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9205	} else {
9206		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9207		    SCP_WCE) == 0)
9208			flags |= CTL_LLF_FUA;
9209	}
9210
9211	lbalen = (struct ctl_lba_len_flags *)
9212	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9213	lbalen->lba = lba;
9214	lbalen->len = num_blocks;
9215	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9216
9217	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9218	ctsio->kern_rel_offset = 0;
9219
9220	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9221
9222	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9223
9224	return (retval);
9225}
9226
9227static int
9228ctl_cnw_cont(union ctl_io *io)
9229{
9230	struct ctl_scsiio *ctsio;
9231	struct ctl_lun *lun;
9232	struct ctl_lba_len_flags *lbalen;
9233	int retval;
9234
9235	ctsio = &io->scsiio;
9236	ctsio->io_hdr.status = CTL_STATUS_NONE;
9237	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9238	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9239	lbalen = (struct ctl_lba_len_flags *)
9240	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9241	lbalen->flags &= ~CTL_LLF_COMPARE;
9242	lbalen->flags |= CTL_LLF_WRITE;
9243
9244	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9245	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9246	return (retval);
9247}
9248
9249int
9250ctl_cnw(struct ctl_scsiio *ctsio)
9251{
9252	struct ctl_lun *lun;
9253	struct ctl_lba_len_flags *lbalen;
9254	uint64_t lba;
9255	uint32_t num_blocks;
9256	int flags, retval;
9257
9258	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9259
9260	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9261
9262	flags = 0;
9263	retval = CTL_RETVAL_COMPLETE;
9264
9265	switch (ctsio->cdb[0]) {
9266	case COMPARE_AND_WRITE: {
9267		struct scsi_compare_and_write *cdb;
9268
9269		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9270		if (cdb->byte2 & SRW10_FUA)
9271			flags |= CTL_LLF_FUA;
9272		if (cdb->byte2 & SRW10_DPO)
9273			flags |= CTL_LLF_DPO;
9274		lba = scsi_8btou64(cdb->addr);
9275		num_blocks = cdb->length;
9276		break;
9277	}
9278	default:
9279		/*
9280		 * We got a command we don't support.  This shouldn't
9281		 * happen, commands should be filtered out above us.
9282		 */
9283		ctl_set_invalid_opcode(ctsio);
9284		ctl_done((union ctl_io *)ctsio);
9285
9286		return (CTL_RETVAL_COMPLETE);
9287		break; /* NOTREACHED */
9288	}
9289
9290	/*
9291	 * The first check is to make sure we're in bounds, the second
9292	 * check is to catch wrap-around problems.  If the lba + num blocks
9293	 * is less than the lba, then we've wrapped around and the block
9294	 * range is invalid anyway.
9295	 */
9296	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9297	 || ((lba + num_blocks) < lba)) {
9298		ctl_set_lba_out_of_range(ctsio);
9299		ctl_done((union ctl_io *)ctsio);
9300		return (CTL_RETVAL_COMPLETE);
9301	}
9302
9303	/*
9304	 * According to SBC-3, a transfer length of 0 is not an error.
9305	 */
9306	if (num_blocks == 0) {
9307		ctl_set_success(ctsio);
9308		ctl_done((union ctl_io *)ctsio);
9309		return (CTL_RETVAL_COMPLETE);
9310	}
9311
9312	/* Set FUA if write cache is disabled. */
9313	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9314	    SCP_WCE) == 0)
9315		flags |= CTL_LLF_FUA;
9316
9317	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9318	ctsio->kern_rel_offset = 0;
9319
9320	/*
9321	 * Set the IO_CONT flag, so that if this I/O gets passed to
9322	 * ctl_data_submit_done(), it'll get passed back to
9323	 * ctl_ctl_cnw_cont() for further processing.
9324	 */
9325	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9326	ctsio->io_cont = ctl_cnw_cont;
9327
9328	lbalen = (struct ctl_lba_len_flags *)
9329	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9330	lbalen->lba = lba;
9331	lbalen->len = num_blocks;
9332	lbalen->flags = CTL_LLF_COMPARE | flags;
9333
9334	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9335	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9336	return (retval);
9337}
9338
9339int
9340ctl_verify(struct ctl_scsiio *ctsio)
9341{
9342	struct ctl_lun *lun;
9343	struct ctl_lba_len_flags *lbalen;
9344	uint64_t lba;
9345	uint32_t num_blocks;
9346	int bytchk, flags;
9347	int retval;
9348
9349	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9350
9351	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9352
9353	bytchk = 0;
9354	flags = CTL_LLF_FUA;
9355	retval = CTL_RETVAL_COMPLETE;
9356
9357	switch (ctsio->cdb[0]) {
9358	case VERIFY_10: {
9359		struct scsi_verify_10 *cdb;
9360
9361		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9362		if (cdb->byte2 & SVFY_BYTCHK)
9363			bytchk = 1;
9364		if (cdb->byte2 & SVFY_DPO)
9365			flags |= CTL_LLF_DPO;
9366		lba = scsi_4btoul(cdb->addr);
9367		num_blocks = scsi_2btoul(cdb->length);
9368		break;
9369	}
9370	case VERIFY_12: {
9371		struct scsi_verify_12 *cdb;
9372
9373		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9374		if (cdb->byte2 & SVFY_BYTCHK)
9375			bytchk = 1;
9376		if (cdb->byte2 & SVFY_DPO)
9377			flags |= CTL_LLF_DPO;
9378		lba = scsi_4btoul(cdb->addr);
9379		num_blocks = scsi_4btoul(cdb->length);
9380		break;
9381	}
9382	case VERIFY_16: {
9383		struct scsi_rw_16 *cdb;
9384
9385		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9386		if (cdb->byte2 & SVFY_BYTCHK)
9387			bytchk = 1;
9388		if (cdb->byte2 & SVFY_DPO)
9389			flags |= CTL_LLF_DPO;
9390		lba = scsi_8btou64(cdb->addr);
9391		num_blocks = scsi_4btoul(cdb->length);
9392		break;
9393	}
9394	default:
9395		/*
9396		 * We got a command we don't support.  This shouldn't
9397		 * happen, commands should be filtered out above us.
9398		 */
9399		ctl_set_invalid_opcode(ctsio);
9400		ctl_done((union ctl_io *)ctsio);
9401		return (CTL_RETVAL_COMPLETE);
9402	}
9403
9404	/*
9405	 * The first check is to make sure we're in bounds, the second
9406	 * check is to catch wrap-around problems.  If the lba + num blocks
9407	 * is less than the lba, then we've wrapped around and the block
9408	 * range is invalid anyway.
9409	 */
9410	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9411	 || ((lba + num_blocks) < lba)) {
9412		ctl_set_lba_out_of_range(ctsio);
9413		ctl_done((union ctl_io *)ctsio);
9414		return (CTL_RETVAL_COMPLETE);
9415	}
9416
9417	/*
9418	 * According to SBC-3, a transfer length of 0 is not an error.
9419	 */
9420	if (num_blocks == 0) {
9421		ctl_set_success(ctsio);
9422		ctl_done((union ctl_io *)ctsio);
9423		return (CTL_RETVAL_COMPLETE);
9424	}
9425
9426	lbalen = (struct ctl_lba_len_flags *)
9427	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9428	lbalen->lba = lba;
9429	lbalen->len = num_blocks;
9430	if (bytchk) {
9431		lbalen->flags = CTL_LLF_COMPARE | flags;
9432		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9433	} else {
9434		lbalen->flags = CTL_LLF_VERIFY | flags;
9435		ctsio->kern_total_len = 0;
9436	}
9437	ctsio->kern_rel_offset = 0;
9438
9439	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9440	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9441	return (retval);
9442}
9443
9444int
9445ctl_report_luns(struct ctl_scsiio *ctsio)
9446{
9447	struct scsi_report_luns *cdb;
9448	struct scsi_report_luns_data *lun_data;
9449	struct ctl_lun *lun, *request_lun;
9450	int num_luns, retval;
9451	uint32_t alloc_len, lun_datalen;
9452	int num_filled, well_known;
9453	uint32_t initidx, targ_lun_id, lun_id;
9454
9455	retval = CTL_RETVAL_COMPLETE;
9456	well_known = 0;
9457
9458	cdb = (struct scsi_report_luns *)ctsio->cdb;
9459
9460	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9461
9462	mtx_lock(&control_softc->ctl_lock);
9463	num_luns = control_softc->num_luns;
9464	mtx_unlock(&control_softc->ctl_lock);
9465
9466	switch (cdb->select_report) {
9467	case RPL_REPORT_DEFAULT:
9468	case RPL_REPORT_ALL:
9469		break;
9470	case RPL_REPORT_WELLKNOWN:
9471		well_known = 1;
9472		num_luns = 0;
9473		break;
9474	default:
9475		ctl_set_invalid_field(ctsio,
9476				      /*sks_valid*/ 1,
9477				      /*command*/ 1,
9478				      /*field*/ 2,
9479				      /*bit_valid*/ 0,
9480				      /*bit*/ 0);
9481		ctl_done((union ctl_io *)ctsio);
9482		return (retval);
9483		break; /* NOTREACHED */
9484	}
9485
9486	alloc_len = scsi_4btoul(cdb->length);
9487	/*
9488	 * The initiator has to allocate at least 16 bytes for this request,
9489	 * so he can at least get the header and the first LUN.  Otherwise
9490	 * we reject the request (per SPC-3 rev 14, section 6.21).
9491	 */
9492	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9493	    sizeof(struct scsi_report_luns_lundata))) {
9494		ctl_set_invalid_field(ctsio,
9495				      /*sks_valid*/ 1,
9496				      /*command*/ 1,
9497				      /*field*/ 6,
9498				      /*bit_valid*/ 0,
9499				      /*bit*/ 0);
9500		ctl_done((union ctl_io *)ctsio);
9501		return (retval);
9502	}
9503
9504	request_lun = (struct ctl_lun *)
9505		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9506
9507	lun_datalen = sizeof(*lun_data) +
9508		(num_luns * sizeof(struct scsi_report_luns_lundata));
9509
9510	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9511	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9512	ctsio->kern_sg_entries = 0;
9513
9514	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9515
9516	mtx_lock(&control_softc->ctl_lock);
9517	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9518		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9519		if (lun_id >= CTL_MAX_LUNS)
9520			continue;
9521		lun = control_softc->ctl_luns[lun_id];
9522		if (lun == NULL)
9523			continue;
9524
9525		if (targ_lun_id <= 0xff) {
9526			/*
9527			 * Peripheral addressing method, bus number 0.
9528			 */
9529			lun_data->luns[num_filled].lundata[0] =
9530				RPL_LUNDATA_ATYP_PERIPH;
9531			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9532			num_filled++;
9533		} else if (targ_lun_id <= 0x3fff) {
9534			/*
9535			 * Flat addressing method.
9536			 */
9537			lun_data->luns[num_filled].lundata[0] =
9538				RPL_LUNDATA_ATYP_FLAT |
9539				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9540#ifdef OLDCTLHEADERS
9541				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9542				(targ_lun_id & SRLD_BUS_LUN_MASK);
9543#endif
9544			lun_data->luns[num_filled].lundata[1] =
9545#ifdef OLDCTLHEADERS
9546				targ_lun_id >> SRLD_BUS_LUN_BITS;
9547#endif
9548				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9549			num_filled++;
9550		} else {
9551			printf("ctl_report_luns: bogus LUN number %jd, "
9552			       "skipping\n", (intmax_t)targ_lun_id);
9553		}
9554		/*
9555		 * According to SPC-3, rev 14 section 6.21:
9556		 *
9557		 * "The execution of a REPORT LUNS command to any valid and
9558		 * installed logical unit shall clear the REPORTED LUNS DATA
9559		 * HAS CHANGED unit attention condition for all logical
9560		 * units of that target with respect to the requesting
9561		 * initiator. A valid and installed logical unit is one
9562		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9563		 * INQUIRY data (see 6.4.2)."
9564		 *
9565		 * If request_lun is NULL, the LUN this report luns command
9566		 * was issued to is either disabled or doesn't exist. In that
9567		 * case, we shouldn't clear any pending lun change unit
9568		 * attention.
9569		 */
9570		if (request_lun != NULL) {
9571			mtx_lock(&lun->lun_lock);
9572			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9573			mtx_unlock(&lun->lun_lock);
9574		}
9575	}
9576	mtx_unlock(&control_softc->ctl_lock);
9577
9578	/*
9579	 * It's quite possible that we've returned fewer LUNs than we allocated
9580	 * space for.  Trim it.
9581	 */
9582	lun_datalen = sizeof(*lun_data) +
9583		(num_filled * sizeof(struct scsi_report_luns_lundata));
9584
9585	if (lun_datalen < alloc_len) {
9586		ctsio->residual = alloc_len - lun_datalen;
9587		ctsio->kern_data_len = lun_datalen;
9588		ctsio->kern_total_len = lun_datalen;
9589	} else {
9590		ctsio->residual = 0;
9591		ctsio->kern_data_len = alloc_len;
9592		ctsio->kern_total_len = alloc_len;
9593	}
9594	ctsio->kern_data_resid = 0;
9595	ctsio->kern_rel_offset = 0;
9596	ctsio->kern_sg_entries = 0;
9597
9598	/*
9599	 * We set this to the actual data length, regardless of how much
9600	 * space we actually have to return results.  If the user looks at
9601	 * this value, he'll know whether or not he allocated enough space
9602	 * and reissue the command if necessary.  We don't support well
9603	 * known logical units, so if the user asks for that, return none.
9604	 */
9605	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9606
9607	/*
9608	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9609	 * this request.
9610	 */
9611	ctsio->scsi_status = SCSI_STATUS_OK;
9612
9613	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9614	ctsio->be_move_done = ctl_config_move_done;
9615	ctl_datamove((union ctl_io *)ctsio);
9616
9617	return (retval);
9618}
9619
9620int
9621ctl_request_sense(struct ctl_scsiio *ctsio)
9622{
9623	struct scsi_request_sense *cdb;
9624	struct scsi_sense_data *sense_ptr;
9625	struct ctl_lun *lun;
9626	uint32_t initidx;
9627	int have_error;
9628	scsi_sense_data_type sense_format;
9629
9630	cdb = (struct scsi_request_sense *)ctsio->cdb;
9631
9632	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9633
9634	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9635
9636	/*
9637	 * Determine which sense format the user wants.
9638	 */
9639	if (cdb->byte2 & SRS_DESC)
9640		sense_format = SSD_TYPE_DESC;
9641	else
9642		sense_format = SSD_TYPE_FIXED;
9643
9644	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9645	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9646	ctsio->kern_sg_entries = 0;
9647
9648	/*
9649	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9650	 * larger than the largest allowed value for the length field in the
9651	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9652	 */
9653	ctsio->residual = 0;
9654	ctsio->kern_data_len = cdb->length;
9655	ctsio->kern_total_len = cdb->length;
9656
9657	ctsio->kern_data_resid = 0;
9658	ctsio->kern_rel_offset = 0;
9659	ctsio->kern_sg_entries = 0;
9660
9661	/*
9662	 * If we don't have a LUN, we don't have any pending sense.
9663	 */
9664	if (lun == NULL)
9665		goto no_sense;
9666
9667	have_error = 0;
9668	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9669	/*
9670	 * Check for pending sense, and then for pending unit attentions.
9671	 * Pending sense gets returned first, then pending unit attentions.
9672	 */
9673	mtx_lock(&lun->lun_lock);
9674#ifdef CTL_WITH_CA
9675	if (ctl_is_set(lun->have_ca, initidx)) {
9676		scsi_sense_data_type stored_format;
9677
9678		/*
9679		 * Check to see which sense format was used for the stored
9680		 * sense data.
9681		 */
9682		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9683
9684		/*
9685		 * If the user requested a different sense format than the
9686		 * one we stored, then we need to convert it to the other
9687		 * format.  If we're going from descriptor to fixed format
9688		 * sense data, we may lose things in translation, depending
9689		 * on what options were used.
9690		 *
9691		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9692		 * for some reason we'll just copy it out as-is.
9693		 */
9694		if ((stored_format == SSD_TYPE_FIXED)
9695		 && (sense_format == SSD_TYPE_DESC))
9696			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9697			    &lun->pending_sense[initidx],
9698			    (struct scsi_sense_data_desc *)sense_ptr);
9699		else if ((stored_format == SSD_TYPE_DESC)
9700		      && (sense_format == SSD_TYPE_FIXED))
9701			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9702			    &lun->pending_sense[initidx],
9703			    (struct scsi_sense_data_fixed *)sense_ptr);
9704		else
9705			memcpy(sense_ptr, &lun->pending_sense[initidx],
9706			       ctl_min(sizeof(*sense_ptr),
9707			       sizeof(lun->pending_sense[initidx])));
9708
9709		ctl_clear_mask(lun->have_ca, initidx);
9710		have_error = 1;
9711	} else
9712#endif
9713	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9714		ctl_ua_type ua_type;
9715
9716		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9717				       sense_ptr, sense_format);
9718		if (ua_type != CTL_UA_NONE)
9719			have_error = 1;
9720	}
9721	mtx_unlock(&lun->lun_lock);
9722
9723	/*
9724	 * We already have a pending error, return it.
9725	 */
9726	if (have_error != 0) {
9727		/*
9728		 * We report the SCSI status as OK, since the status of the
9729		 * request sense command itself is OK.
9730		 */
9731		ctsio->scsi_status = SCSI_STATUS_OK;
9732
9733		/*
9734		 * We report 0 for the sense length, because we aren't doing
9735		 * autosense in this case.  We're reporting sense as
9736		 * parameter data.
9737		 */
9738		ctsio->sense_len = 0;
9739		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9740		ctsio->be_move_done = ctl_config_move_done;
9741		ctl_datamove((union ctl_io *)ctsio);
9742
9743		return (CTL_RETVAL_COMPLETE);
9744	}
9745
9746no_sense:
9747
9748	/*
9749	 * No sense information to report, so we report that everything is
9750	 * okay.
9751	 */
9752	ctl_set_sense_data(sense_ptr,
9753			   lun,
9754			   sense_format,
9755			   /*current_error*/ 1,
9756			   /*sense_key*/ SSD_KEY_NO_SENSE,
9757			   /*asc*/ 0x00,
9758			   /*ascq*/ 0x00,
9759			   SSD_ELEM_NONE);
9760
9761	ctsio->scsi_status = SCSI_STATUS_OK;
9762
9763	/*
9764	 * We report 0 for the sense length, because we aren't doing
9765	 * autosense in this case.  We're reporting sense as parameter data.
9766	 */
9767	ctsio->sense_len = 0;
9768	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9769	ctsio->be_move_done = ctl_config_move_done;
9770	ctl_datamove((union ctl_io *)ctsio);
9771
9772	return (CTL_RETVAL_COMPLETE);
9773}
9774
9775int
9776ctl_tur(struct ctl_scsiio *ctsio)
9777{
9778	struct ctl_lun *lun;
9779
9780	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9781
9782	CTL_DEBUG_PRINT(("ctl_tur\n"));
9783
9784	if (lun == NULL)
9785		return (EINVAL);
9786
9787	ctsio->scsi_status = SCSI_STATUS_OK;
9788	ctsio->io_hdr.status = CTL_SUCCESS;
9789
9790	ctl_done((union ctl_io *)ctsio);
9791
9792	return (CTL_RETVAL_COMPLETE);
9793}
9794
9795#ifdef notyet
9796static int
9797ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9798{
9799
9800}
9801#endif
9802
9803static int
9804ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9805{
9806	struct scsi_vpd_supported_pages *pages;
9807	int sup_page_size;
9808	struct ctl_lun *lun;
9809
9810	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9811
9812	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9813	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9814	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9815	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9816	ctsio->kern_sg_entries = 0;
9817
9818	if (sup_page_size < alloc_len) {
9819		ctsio->residual = alloc_len - sup_page_size;
9820		ctsio->kern_data_len = sup_page_size;
9821		ctsio->kern_total_len = sup_page_size;
9822	} else {
9823		ctsio->residual = 0;
9824		ctsio->kern_data_len = alloc_len;
9825		ctsio->kern_total_len = alloc_len;
9826	}
9827	ctsio->kern_data_resid = 0;
9828	ctsio->kern_rel_offset = 0;
9829	ctsio->kern_sg_entries = 0;
9830
9831	/*
9832	 * The control device is always connected.  The disk device, on the
9833	 * other hand, may not be online all the time.  Need to change this
9834	 * to figure out whether the disk device is actually online or not.
9835	 */
9836	if (lun != NULL)
9837		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9838				lun->be_lun->lun_type;
9839	else
9840		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9841
9842	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9843	/* Supported VPD pages */
9844	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9845	/* Serial Number */
9846	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9847	/* Device Identification */
9848	pages->page_list[2] = SVPD_DEVICE_ID;
9849	/* Mode Page Policy */
9850	pages->page_list[3] = SVPD_MODE_PAGE_POLICY;
9851	/* SCSI Ports */
9852	pages->page_list[4] = SVPD_SCSI_PORTS;
9853	/* Third-party Copy */
9854	pages->page_list[5] = SVPD_SCSI_TPC;
9855	/* Block limits */
9856	pages->page_list[6] = SVPD_BLOCK_LIMITS;
9857	/* Block Device Characteristics */
9858	pages->page_list[7] = SVPD_BDC;
9859	/* Logical Block Provisioning */
9860	pages->page_list[8] = SVPD_LBP;
9861
9862	ctsio->scsi_status = SCSI_STATUS_OK;
9863
9864	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9865	ctsio->be_move_done = ctl_config_move_done;
9866	ctl_datamove((union ctl_io *)ctsio);
9867
9868	return (CTL_RETVAL_COMPLETE);
9869}
9870
9871static int
9872ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9873{
9874	struct scsi_vpd_unit_serial_number *sn_ptr;
9875	struct ctl_lun *lun;
9876
9877	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9878
9879	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9880	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9881	ctsio->kern_sg_entries = 0;
9882
9883	if (sizeof(*sn_ptr) < alloc_len) {
9884		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9885		ctsio->kern_data_len = sizeof(*sn_ptr);
9886		ctsio->kern_total_len = sizeof(*sn_ptr);
9887	} else {
9888		ctsio->residual = 0;
9889		ctsio->kern_data_len = alloc_len;
9890		ctsio->kern_total_len = alloc_len;
9891	}
9892	ctsio->kern_data_resid = 0;
9893	ctsio->kern_rel_offset = 0;
9894	ctsio->kern_sg_entries = 0;
9895
9896	/*
9897	 * The control device is always connected.  The disk device, on the
9898	 * other hand, may not be online all the time.  Need to change this
9899	 * to figure out whether the disk device is actually online or not.
9900	 */
9901	if (lun != NULL)
9902		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9903				  lun->be_lun->lun_type;
9904	else
9905		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9906
9907	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9908	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9909	/*
9910	 * If we don't have a LUN, we just leave the serial number as
9911	 * all spaces.
9912	 */
9913	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9914	if (lun != NULL) {
9915		strncpy((char *)sn_ptr->serial_num,
9916			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9917	}
9918	ctsio->scsi_status = SCSI_STATUS_OK;
9919
9920	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9921	ctsio->be_move_done = ctl_config_move_done;
9922	ctl_datamove((union ctl_io *)ctsio);
9923
9924	return (CTL_RETVAL_COMPLETE);
9925}
9926
9927
9928static int
9929ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9930{
9931	struct scsi_vpd_mode_page_policy *mpp_ptr;
9932	struct ctl_lun *lun;
9933	int data_len;
9934
9935	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9936
9937	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9938	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9939
9940	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9941	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9942	ctsio->kern_sg_entries = 0;
9943
9944	if (data_len < alloc_len) {
9945		ctsio->residual = alloc_len - data_len;
9946		ctsio->kern_data_len = data_len;
9947		ctsio->kern_total_len = data_len;
9948	} else {
9949		ctsio->residual = 0;
9950		ctsio->kern_data_len = alloc_len;
9951		ctsio->kern_total_len = alloc_len;
9952	}
9953	ctsio->kern_data_resid = 0;
9954	ctsio->kern_rel_offset = 0;
9955	ctsio->kern_sg_entries = 0;
9956
9957	/*
9958	 * The control device is always connected.  The disk device, on the
9959	 * other hand, may not be online all the time.
9960	 */
9961	if (lun != NULL)
9962		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9963				     lun->be_lun->lun_type;
9964	else
9965		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9966	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9967	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9968	mpp_ptr->descr[0].page_code = 0x3f;
9969	mpp_ptr->descr[0].subpage_code = 0xff;
9970	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9971
9972	ctsio->scsi_status = SCSI_STATUS_OK;
9973	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9974	ctsio->be_move_done = ctl_config_move_done;
9975	ctl_datamove((union ctl_io *)ctsio);
9976
9977	return (CTL_RETVAL_COMPLETE);
9978}
9979
9980static int
9981ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9982{
9983	struct scsi_vpd_device_id *devid_ptr;
9984	struct scsi_vpd_id_descriptor *desc;
9985	struct ctl_softc *ctl_softc;
9986	struct ctl_lun *lun;
9987	struct ctl_port *port;
9988	int data_len;
9989	uint8_t proto;
9990
9991	ctl_softc = control_softc;
9992
9993	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9994	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9995
9996	data_len = sizeof(struct scsi_vpd_device_id) +
9997	    sizeof(struct scsi_vpd_id_descriptor) +
9998		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9999	    sizeof(struct scsi_vpd_id_descriptor) +
10000		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10001	if (lun && lun->lun_devid)
10002		data_len += lun->lun_devid->len;
10003	if (port->port_devid)
10004		data_len += port->port_devid->len;
10005	if (port->target_devid)
10006		data_len += port->target_devid->len;
10007
10008	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10009	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10010	ctsio->kern_sg_entries = 0;
10011
10012	if (data_len < alloc_len) {
10013		ctsio->residual = alloc_len - data_len;
10014		ctsio->kern_data_len = data_len;
10015		ctsio->kern_total_len = data_len;
10016	} else {
10017		ctsio->residual = 0;
10018		ctsio->kern_data_len = alloc_len;
10019		ctsio->kern_total_len = alloc_len;
10020	}
10021	ctsio->kern_data_resid = 0;
10022	ctsio->kern_rel_offset = 0;
10023	ctsio->kern_sg_entries = 0;
10024
10025	/*
10026	 * The control device is always connected.  The disk device, on the
10027	 * other hand, may not be online all the time.
10028	 */
10029	if (lun != NULL)
10030		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10031				     lun->be_lun->lun_type;
10032	else
10033		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10034	devid_ptr->page_code = SVPD_DEVICE_ID;
10035	scsi_ulto2b(data_len - 4, devid_ptr->length);
10036
10037	if (port->port_type == CTL_PORT_FC)
10038		proto = SCSI_PROTO_FC << 4;
10039	else if (port->port_type == CTL_PORT_ISCSI)
10040		proto = SCSI_PROTO_ISCSI << 4;
10041	else
10042		proto = SCSI_PROTO_SPI << 4;
10043	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10044
10045	/*
10046	 * We're using a LUN association here.  i.e., this device ID is a
10047	 * per-LUN identifier.
10048	 */
10049	if (lun && lun->lun_devid) {
10050		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10051		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10052		    lun->lun_devid->len);
10053	}
10054
10055	/*
10056	 * This is for the WWPN which is a port association.
10057	 */
10058	if (port->port_devid) {
10059		memcpy(desc, port->port_devid->data, port->port_devid->len);
10060		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10061		    port->port_devid->len);
10062	}
10063
10064	/*
10065	 * This is for the Relative Target Port(type 4h) 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_RELTARG;
10070	desc->length = 4;
10071	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10072	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10073	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10074
10075	/*
10076	 * This is for the Target Port Group(type 5h) identifier
10077	 */
10078	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10079	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10080	    SVPD_ID_TYPE_TPORTGRP;
10081	desc->length = 4;
10082	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10083	    &desc->identifier[2]);
10084	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10085	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10086
10087	/*
10088	 * This is for the Target identifier
10089	 */
10090	if (port->target_devid) {
10091		memcpy(desc, port->target_devid->data, port->target_devid->len);
10092	}
10093
10094	ctsio->scsi_status = SCSI_STATUS_OK;
10095	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10096	ctsio->be_move_done = ctl_config_move_done;
10097	ctl_datamove((union ctl_io *)ctsio);
10098
10099	return (CTL_RETVAL_COMPLETE);
10100}
10101
10102static int
10103ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10104{
10105	struct ctl_softc *softc = control_softc;
10106	struct scsi_vpd_scsi_ports *sp;
10107	struct scsi_vpd_port_designation *pd;
10108	struct scsi_vpd_port_designation_cont *pdc;
10109	struct ctl_lun *lun;
10110	struct ctl_port *port;
10111	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10112	int num_target_port_groups, single;
10113
10114	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10115
10116	single = ctl_is_single;
10117	if (single)
10118		num_target_port_groups = 1;
10119	else
10120		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10121	num_target_ports = 0;
10122	iid_len = 0;
10123	id_len = 0;
10124	mtx_lock(&softc->ctl_lock);
10125	STAILQ_FOREACH(port, &softc->port_list, links) {
10126		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10127			continue;
10128		if (lun != NULL &&
10129		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10130		    CTL_MAX_LUNS)
10131			continue;
10132		num_target_ports++;
10133		if (port->init_devid)
10134			iid_len += port->init_devid->len;
10135		if (port->port_devid)
10136			id_len += port->port_devid->len;
10137	}
10138	mtx_unlock(&softc->ctl_lock);
10139
10140	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10141	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10142	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10143	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10144	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10145	ctsio->kern_sg_entries = 0;
10146
10147	if (data_len < alloc_len) {
10148		ctsio->residual = alloc_len - data_len;
10149		ctsio->kern_data_len = data_len;
10150		ctsio->kern_total_len = data_len;
10151	} else {
10152		ctsio->residual = 0;
10153		ctsio->kern_data_len = alloc_len;
10154		ctsio->kern_total_len = alloc_len;
10155	}
10156	ctsio->kern_data_resid = 0;
10157	ctsio->kern_rel_offset = 0;
10158	ctsio->kern_sg_entries = 0;
10159
10160	/*
10161	 * The control device is always connected.  The disk device, on the
10162	 * other hand, may not be online all the time.  Need to change this
10163	 * to figure out whether the disk device is actually online or not.
10164	 */
10165	if (lun != NULL)
10166		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10167				  lun->be_lun->lun_type;
10168	else
10169		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10170
10171	sp->page_code = SVPD_SCSI_PORTS;
10172	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10173	    sp->page_length);
10174	pd = &sp->design[0];
10175
10176	mtx_lock(&softc->ctl_lock);
10177	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10178		pg = 0;
10179	else
10180		pg = 1;
10181	for (g = 0; g < num_target_port_groups; g++) {
10182		STAILQ_FOREACH(port, &softc->port_list, links) {
10183			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10184				continue;
10185			if (lun != NULL &&
10186			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10187			    CTL_MAX_LUNS)
10188				continue;
10189			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10190			scsi_ulto2b(p, pd->relative_port_id);
10191			if (port->init_devid && g == pg) {
10192				iid_len = port->init_devid->len;
10193				memcpy(pd->initiator_transportid,
10194				    port->init_devid->data, port->init_devid->len);
10195			} else
10196				iid_len = 0;
10197			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10198			pdc = (struct scsi_vpd_port_designation_cont *)
10199			    (&pd->initiator_transportid[iid_len]);
10200			if (port->port_devid && g == pg) {
10201				id_len = port->port_devid->len;
10202				memcpy(pdc->target_port_descriptors,
10203				    port->port_devid->data, port->port_devid->len);
10204			} else
10205				id_len = 0;
10206			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10207			pd = (struct scsi_vpd_port_designation *)
10208			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10209		}
10210	}
10211	mtx_unlock(&softc->ctl_lock);
10212
10213	ctsio->scsi_status = SCSI_STATUS_OK;
10214	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10215	ctsio->be_move_done = ctl_config_move_done;
10216	ctl_datamove((union ctl_io *)ctsio);
10217
10218	return (CTL_RETVAL_COMPLETE);
10219}
10220
10221static int
10222ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10223{
10224	struct scsi_vpd_block_limits *bl_ptr;
10225	struct ctl_lun *lun;
10226	int bs;
10227
10228	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10229
10230	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10231	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10232	ctsio->kern_sg_entries = 0;
10233
10234	if (sizeof(*bl_ptr) < alloc_len) {
10235		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10236		ctsio->kern_data_len = sizeof(*bl_ptr);
10237		ctsio->kern_total_len = sizeof(*bl_ptr);
10238	} else {
10239		ctsio->residual = 0;
10240		ctsio->kern_data_len = alloc_len;
10241		ctsio->kern_total_len = alloc_len;
10242	}
10243	ctsio->kern_data_resid = 0;
10244	ctsio->kern_rel_offset = 0;
10245	ctsio->kern_sg_entries = 0;
10246
10247	/*
10248	 * The control device is always connected.  The disk device, on the
10249	 * other hand, may not be online all the time.  Need to change this
10250	 * to figure out whether the disk device is actually online or not.
10251	 */
10252	if (lun != NULL)
10253		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10254				  lun->be_lun->lun_type;
10255	else
10256		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10257
10258	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10259	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10260	bl_ptr->max_cmp_write_len = 0xff;
10261	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10262	if (lun != NULL) {
10263		bs = lun->be_lun->blocksize;
10264		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10265		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10266			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10267			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10268			if (lun->be_lun->pblockexp != 0) {
10269				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10270				    bl_ptr->opt_unmap_grain);
10271				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10272				    bl_ptr->unmap_grain_align);
10273			}
10274		}
10275	}
10276	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10277
10278	ctsio->scsi_status = SCSI_STATUS_OK;
10279	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10280	ctsio->be_move_done = ctl_config_move_done;
10281	ctl_datamove((union ctl_io *)ctsio);
10282
10283	return (CTL_RETVAL_COMPLETE);
10284}
10285
10286static int
10287ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10288{
10289	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10290	struct ctl_lun *lun;
10291
10292	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10293
10294	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10295	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10296	ctsio->kern_sg_entries = 0;
10297
10298	if (sizeof(*bdc_ptr) < alloc_len) {
10299		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10300		ctsio->kern_data_len = sizeof(*bdc_ptr);
10301		ctsio->kern_total_len = sizeof(*bdc_ptr);
10302	} else {
10303		ctsio->residual = 0;
10304		ctsio->kern_data_len = alloc_len;
10305		ctsio->kern_total_len = alloc_len;
10306	}
10307	ctsio->kern_data_resid = 0;
10308	ctsio->kern_rel_offset = 0;
10309	ctsio->kern_sg_entries = 0;
10310
10311	/*
10312	 * The control device is always connected.  The disk device, on the
10313	 * other hand, may not be online all the time.  Need to change this
10314	 * to figure out whether the disk device is actually online or not.
10315	 */
10316	if (lun != NULL)
10317		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10318				  lun->be_lun->lun_type;
10319	else
10320		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10321	bdc_ptr->page_code = SVPD_BDC;
10322	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10323	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10324	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10325
10326	ctsio->scsi_status = SCSI_STATUS_OK;
10327	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10328	ctsio->be_move_done = ctl_config_move_done;
10329	ctl_datamove((union ctl_io *)ctsio);
10330
10331	return (CTL_RETVAL_COMPLETE);
10332}
10333
10334static int
10335ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10336{
10337	struct scsi_vpd_logical_block_prov *lbp_ptr;
10338	struct ctl_lun *lun;
10339
10340	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10341
10342	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10343	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10344	ctsio->kern_sg_entries = 0;
10345
10346	if (sizeof(*lbp_ptr) < alloc_len) {
10347		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10348		ctsio->kern_data_len = sizeof(*lbp_ptr);
10349		ctsio->kern_total_len = sizeof(*lbp_ptr);
10350	} else {
10351		ctsio->residual = 0;
10352		ctsio->kern_data_len = alloc_len;
10353		ctsio->kern_total_len = alloc_len;
10354	}
10355	ctsio->kern_data_resid = 0;
10356	ctsio->kern_rel_offset = 0;
10357	ctsio->kern_sg_entries = 0;
10358
10359	/*
10360	 * The control device is always connected.  The disk device, on the
10361	 * other hand, may not be online all the time.  Need to change this
10362	 * to figure out whether the disk device is actually online or not.
10363	 */
10364	if (lun != NULL)
10365		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10366				  lun->be_lun->lun_type;
10367	else
10368		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10369
10370	lbp_ptr->page_code = SVPD_LBP;
10371	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10372	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10373		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10374		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10375		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10376	}
10377
10378	ctsio->scsi_status = SCSI_STATUS_OK;
10379	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10380	ctsio->be_move_done = ctl_config_move_done;
10381	ctl_datamove((union ctl_io *)ctsio);
10382
10383	return (CTL_RETVAL_COMPLETE);
10384}
10385
10386static int
10387ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10388{
10389	struct scsi_inquiry *cdb;
10390	struct ctl_lun *lun;
10391	int alloc_len, retval;
10392
10393	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10394	cdb = (struct scsi_inquiry *)ctsio->cdb;
10395
10396	retval = CTL_RETVAL_COMPLETE;
10397
10398	alloc_len = scsi_2btoul(cdb->length);
10399
10400	switch (cdb->page_code) {
10401	case SVPD_SUPPORTED_PAGES:
10402		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10403		break;
10404	case SVPD_UNIT_SERIAL_NUMBER:
10405		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10406		break;
10407	case SVPD_DEVICE_ID:
10408		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10409		break;
10410	case SVPD_MODE_PAGE_POLICY:
10411		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10412		break;
10413	case SVPD_SCSI_PORTS:
10414		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10415		break;
10416	case SVPD_SCSI_TPC:
10417		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10418		break;
10419	case SVPD_BLOCK_LIMITS:
10420		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10421		break;
10422	case SVPD_BDC:
10423		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10424		break;
10425	case SVPD_LBP:
10426		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10427		break;
10428	default:
10429		ctl_set_invalid_field(ctsio,
10430				      /*sks_valid*/ 1,
10431				      /*command*/ 1,
10432				      /*field*/ 2,
10433				      /*bit_valid*/ 0,
10434				      /*bit*/ 0);
10435		ctl_done((union ctl_io *)ctsio);
10436		retval = CTL_RETVAL_COMPLETE;
10437		break;
10438	}
10439
10440	return (retval);
10441}
10442
10443static int
10444ctl_inquiry_std(struct ctl_scsiio *ctsio)
10445{
10446	struct scsi_inquiry_data *inq_ptr;
10447	struct scsi_inquiry *cdb;
10448	struct ctl_softc *ctl_softc;
10449	struct ctl_lun *lun;
10450	char *val;
10451	uint32_t alloc_len;
10452	ctl_port_type port_type;
10453
10454	ctl_softc = control_softc;
10455
10456	/*
10457	 * Figure out whether we're talking to a Fibre Channel port or not.
10458	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10459	 * SCSI front ends.
10460	 */
10461	port_type = ctl_softc->ctl_ports[
10462	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10463	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10464		port_type = CTL_PORT_SCSI;
10465
10466	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10467	cdb = (struct scsi_inquiry *)ctsio->cdb;
10468	alloc_len = scsi_2btoul(cdb->length);
10469
10470	/*
10471	 * We malloc the full inquiry data size here and fill it
10472	 * in.  If the user only asks for less, we'll give him
10473	 * that much.
10474	 */
10475	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10476	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10477	ctsio->kern_sg_entries = 0;
10478	ctsio->kern_data_resid = 0;
10479	ctsio->kern_rel_offset = 0;
10480
10481	if (sizeof(*inq_ptr) < alloc_len) {
10482		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10483		ctsio->kern_data_len = sizeof(*inq_ptr);
10484		ctsio->kern_total_len = sizeof(*inq_ptr);
10485	} else {
10486		ctsio->residual = 0;
10487		ctsio->kern_data_len = alloc_len;
10488		ctsio->kern_total_len = alloc_len;
10489	}
10490
10491	/*
10492	 * If we have a LUN configured, report it as connected.  Otherwise,
10493	 * report that it is offline or no device is supported, depending
10494	 * on the value of inquiry_pq_no_lun.
10495	 *
10496	 * According to the spec (SPC-4 r34), the peripheral qualifier
10497	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10498	 *
10499	 * "A peripheral device having the specified peripheral device type
10500	 * is not connected to this logical unit. However, the device
10501	 * server is capable of supporting the specified peripheral device
10502	 * type on this logical unit."
10503	 *
10504	 * According to the same spec, the peripheral qualifier
10505	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10506	 *
10507	 * "The device server is not capable of supporting a peripheral
10508	 * device on this logical unit. For this peripheral qualifier the
10509	 * peripheral device type shall be set to 1Fh. All other peripheral
10510	 * device type values are reserved for this peripheral qualifier."
10511	 *
10512	 * Given the text, it would seem that we probably want to report that
10513	 * the LUN is offline here.  There is no LUN connected, but we can
10514	 * support a LUN at the given LUN number.
10515	 *
10516	 * In the real world, though, it sounds like things are a little
10517	 * different:
10518	 *
10519	 * - Linux, when presented with a LUN with the offline peripheral
10520	 *   qualifier, will create an sg driver instance for it.  So when
10521	 *   you attach it to CTL, you wind up with a ton of sg driver
10522	 *   instances.  (One for every LUN that Linux bothered to probe.)
10523	 *   Linux does this despite the fact that it issues a REPORT LUNs
10524	 *   to LUN 0 to get the inventory of supported LUNs.
10525	 *
10526	 * - There is other anecdotal evidence (from Emulex folks) about
10527	 *   arrays that use the offline peripheral qualifier for LUNs that
10528	 *   are on the "passive" path in an active/passive array.
10529	 *
10530	 * So the solution is provide a hopefully reasonable default
10531	 * (return bad/no LUN) and allow the user to change the behavior
10532	 * with a tunable/sysctl variable.
10533	 */
10534	if (lun != NULL)
10535		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10536				  lun->be_lun->lun_type;
10537	else if (ctl_softc->inquiry_pq_no_lun == 0)
10538		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10539	else
10540		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10541
10542	/* RMB in byte 2 is 0 */
10543	inq_ptr->version = SCSI_REV_SPC4;
10544
10545	/*
10546	 * According to SAM-3, even if a device only supports a single
10547	 * level of LUN addressing, it should still set the HISUP bit:
10548	 *
10549	 * 4.9.1 Logical unit numbers overview
10550	 *
10551	 * All logical unit number formats described in this standard are
10552	 * hierarchical in structure even when only a single level in that
10553	 * hierarchy is used. The HISUP bit shall be set to one in the
10554	 * standard INQUIRY data (see SPC-2) when any logical unit number
10555	 * format described in this standard is used.  Non-hierarchical
10556	 * formats are outside the scope of this standard.
10557	 *
10558	 * Therefore we set the HiSup bit here.
10559	 *
10560	 * The reponse format is 2, per SPC-3.
10561	 */
10562	inq_ptr->response_format = SID_HiSup | 2;
10563
10564	inq_ptr->additional_length =
10565	    offsetof(struct scsi_inquiry_data, vendor_specific1) -
10566	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10567	CTL_DEBUG_PRINT(("additional_length = %d\n",
10568			 inq_ptr->additional_length));
10569
10570	inq_ptr->spc3_flags = SPC3_SID_3PC;
10571	if (!ctl_is_single)
10572		inq_ptr->spc3_flags |= SPC3_SID_TPGS_IMPLICIT;
10573	/* 16 bit addressing */
10574	if (port_type == CTL_PORT_SCSI)
10575		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10576	/* XXX set the SID_MultiP bit here if we're actually going to
10577	   respond on multiple ports */
10578	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10579
10580	/* 16 bit data bus, synchronous transfers */
10581	if (port_type == CTL_PORT_SCSI)
10582		inq_ptr->flags = SID_WBus16 | SID_Sync;
10583	/*
10584	 * XXX KDM do we want to support tagged queueing on the control
10585	 * device at all?
10586	 */
10587	if ((lun == NULL)
10588	 || (lun->be_lun->lun_type != T_PROCESSOR))
10589		inq_ptr->flags |= SID_CmdQue;
10590	/*
10591	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10592	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10593	 * name and 4 bytes for the revision.
10594	 */
10595	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10596	    "vendor")) == NULL) {
10597		strcpy(inq_ptr->vendor, CTL_VENDOR);
10598	} else {
10599		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10600		strncpy(inq_ptr->vendor, val,
10601		    min(sizeof(inq_ptr->vendor), strlen(val)));
10602	}
10603	if (lun == NULL) {
10604		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10605	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10606		switch (lun->be_lun->lun_type) {
10607		case T_DIRECT:
10608			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10609			break;
10610		case T_PROCESSOR:
10611			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10612			break;
10613		default:
10614			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10615			break;
10616		}
10617	} else {
10618		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10619		strncpy(inq_ptr->product, val,
10620		    min(sizeof(inq_ptr->product), strlen(val)));
10621	}
10622
10623	/*
10624	 * XXX make this a macro somewhere so it automatically gets
10625	 * incremented when we make changes.
10626	 */
10627	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10628	    "revision")) == NULL) {
10629		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10630	} else {
10631		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10632		strncpy(inq_ptr->revision, val,
10633		    min(sizeof(inq_ptr->revision), strlen(val)));
10634	}
10635
10636	/*
10637	 * For parallel SCSI, we support double transition and single
10638	 * transition clocking.  We also support QAS (Quick Arbitration
10639	 * and Selection) and Information Unit transfers on both the
10640	 * control and array devices.
10641	 */
10642	if (port_type == CTL_PORT_SCSI)
10643		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10644				    SID_SPI_IUS;
10645
10646	/* SAM-5 (no version claimed) */
10647	scsi_ulto2b(0x00A0, inq_ptr->version1);
10648	/* SPC-4 (no version claimed) */
10649	scsi_ulto2b(0x0460, inq_ptr->version2);
10650	if (port_type == CTL_PORT_FC) {
10651		/* FCP-2 ANSI INCITS.350:2003 */
10652		scsi_ulto2b(0x0917, inq_ptr->version3);
10653	} else if (port_type == CTL_PORT_SCSI) {
10654		/* SPI-4 ANSI INCITS.362:200x */
10655		scsi_ulto2b(0x0B56, inq_ptr->version3);
10656	} else if (port_type == CTL_PORT_ISCSI) {
10657		/* iSCSI (no version claimed) */
10658		scsi_ulto2b(0x0960, inq_ptr->version3);
10659	} else if (port_type == CTL_PORT_SAS) {
10660		/* SAS (no version claimed) */
10661		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10662	}
10663
10664	if (lun == NULL) {
10665		/* SBC-3 (no version claimed) */
10666		scsi_ulto2b(0x04C0, inq_ptr->version4);
10667	} else {
10668		switch (lun->be_lun->lun_type) {
10669		case T_DIRECT:
10670			/* SBC-3 (no version claimed) */
10671			scsi_ulto2b(0x04C0, inq_ptr->version4);
10672			break;
10673		case T_PROCESSOR:
10674		default:
10675			break;
10676		}
10677	}
10678
10679	ctsio->scsi_status = SCSI_STATUS_OK;
10680	if (ctsio->kern_data_len > 0) {
10681		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10682		ctsio->be_move_done = ctl_config_move_done;
10683		ctl_datamove((union ctl_io *)ctsio);
10684	} else {
10685		ctsio->io_hdr.status = CTL_SUCCESS;
10686		ctl_done((union ctl_io *)ctsio);
10687	}
10688
10689	return (CTL_RETVAL_COMPLETE);
10690}
10691
10692int
10693ctl_inquiry(struct ctl_scsiio *ctsio)
10694{
10695	struct scsi_inquiry *cdb;
10696	int retval;
10697
10698	cdb = (struct scsi_inquiry *)ctsio->cdb;
10699
10700	retval = 0;
10701
10702	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10703
10704	/*
10705	 * Right now, we don't support the CmdDt inquiry information.
10706	 * This would be nice to support in the future.  When we do
10707	 * support it, we should change this test so that it checks to make
10708	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10709	 */
10710#ifdef notyet
10711	if (((cdb->byte2 & SI_EVPD)
10712	 && (cdb->byte2 & SI_CMDDT)))
10713#endif
10714	if (cdb->byte2 & SI_CMDDT) {
10715		/*
10716		 * Point to the SI_CMDDT bit.  We might change this
10717		 * when we support SI_CMDDT, but since both bits would be
10718		 * "wrong", this should probably just stay as-is then.
10719		 */
10720		ctl_set_invalid_field(ctsio,
10721				      /*sks_valid*/ 1,
10722				      /*command*/ 1,
10723				      /*field*/ 1,
10724				      /*bit_valid*/ 1,
10725				      /*bit*/ 1);
10726		ctl_done((union ctl_io *)ctsio);
10727		return (CTL_RETVAL_COMPLETE);
10728	}
10729	if (cdb->byte2 & SI_EVPD)
10730		retval = ctl_inquiry_evpd(ctsio);
10731#ifdef notyet
10732	else if (cdb->byte2 & SI_CMDDT)
10733		retval = ctl_inquiry_cmddt(ctsio);
10734#endif
10735	else
10736		retval = ctl_inquiry_std(ctsio);
10737
10738	return (retval);
10739}
10740
10741/*
10742 * For known CDB types, parse the LBA and length.
10743 */
10744static int
10745ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10746{
10747	if (io->io_hdr.io_type != CTL_IO_SCSI)
10748		return (1);
10749
10750	switch (io->scsiio.cdb[0]) {
10751	case COMPARE_AND_WRITE: {
10752		struct scsi_compare_and_write *cdb;
10753
10754		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10755
10756		*lba = scsi_8btou64(cdb->addr);
10757		*len = cdb->length;
10758		break;
10759	}
10760	case READ_6:
10761	case WRITE_6: {
10762		struct scsi_rw_6 *cdb;
10763
10764		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10765
10766		*lba = scsi_3btoul(cdb->addr);
10767		/* only 5 bits are valid in the most significant address byte */
10768		*lba &= 0x1fffff;
10769		*len = cdb->length;
10770		break;
10771	}
10772	case READ_10:
10773	case WRITE_10: {
10774		struct scsi_rw_10 *cdb;
10775
10776		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10777
10778		*lba = scsi_4btoul(cdb->addr);
10779		*len = scsi_2btoul(cdb->length);
10780		break;
10781	}
10782	case WRITE_VERIFY_10: {
10783		struct scsi_write_verify_10 *cdb;
10784
10785		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10786
10787		*lba = scsi_4btoul(cdb->addr);
10788		*len = scsi_2btoul(cdb->length);
10789		break;
10790	}
10791	case READ_12:
10792	case WRITE_12: {
10793		struct scsi_rw_12 *cdb;
10794
10795		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10796
10797		*lba = scsi_4btoul(cdb->addr);
10798		*len = scsi_4btoul(cdb->length);
10799		break;
10800	}
10801	case WRITE_VERIFY_12: {
10802		struct scsi_write_verify_12 *cdb;
10803
10804		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10805
10806		*lba = scsi_4btoul(cdb->addr);
10807		*len = scsi_4btoul(cdb->length);
10808		break;
10809	}
10810	case READ_16:
10811	case WRITE_16: {
10812		struct scsi_rw_16 *cdb;
10813
10814		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10815
10816		*lba = scsi_8btou64(cdb->addr);
10817		*len = scsi_4btoul(cdb->length);
10818		break;
10819	}
10820	case WRITE_VERIFY_16: {
10821		struct scsi_write_verify_16 *cdb;
10822
10823		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10824
10825
10826		*lba = scsi_8btou64(cdb->addr);
10827		*len = scsi_4btoul(cdb->length);
10828		break;
10829	}
10830	case WRITE_SAME_10: {
10831		struct scsi_write_same_10 *cdb;
10832
10833		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10834
10835		*lba = scsi_4btoul(cdb->addr);
10836		*len = scsi_2btoul(cdb->length);
10837		break;
10838	}
10839	case WRITE_SAME_16: {
10840		struct scsi_write_same_16 *cdb;
10841
10842		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10843
10844		*lba = scsi_8btou64(cdb->addr);
10845		*len = scsi_4btoul(cdb->length);
10846		break;
10847	}
10848	case VERIFY_10: {
10849		struct scsi_verify_10 *cdb;
10850
10851		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10852
10853		*lba = scsi_4btoul(cdb->addr);
10854		*len = scsi_2btoul(cdb->length);
10855		break;
10856	}
10857	case VERIFY_12: {
10858		struct scsi_verify_12 *cdb;
10859
10860		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10861
10862		*lba = scsi_4btoul(cdb->addr);
10863		*len = scsi_4btoul(cdb->length);
10864		break;
10865	}
10866	case VERIFY_16: {
10867		struct scsi_verify_16 *cdb;
10868
10869		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10870
10871		*lba = scsi_8btou64(cdb->addr);
10872		*len = scsi_4btoul(cdb->length);
10873		break;
10874	}
10875	default:
10876		return (1);
10877		break; /* NOTREACHED */
10878	}
10879
10880	return (0);
10881}
10882
10883static ctl_action
10884ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10885{
10886	uint64_t endlba1, endlba2;
10887
10888	endlba1 = lba1 + len1 - 1;
10889	endlba2 = lba2 + len2 - 1;
10890
10891	if ((endlba1 < lba2)
10892	 || (endlba2 < lba1))
10893		return (CTL_ACTION_PASS);
10894	else
10895		return (CTL_ACTION_BLOCK);
10896}
10897
10898static ctl_action
10899ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10900{
10901	uint64_t lba1, lba2;
10902	uint32_t len1, len2;
10903	int retval;
10904
10905	retval = ctl_get_lba_len(io1, &lba1, &len1);
10906	if (retval != 0)
10907		return (CTL_ACTION_ERROR);
10908
10909	retval = ctl_get_lba_len(io2, &lba2, &len2);
10910	if (retval != 0)
10911		return (CTL_ACTION_ERROR);
10912
10913	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10914}
10915
10916static ctl_action
10917ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10918{
10919	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10920	ctl_serialize_action *serialize_row;
10921
10922	/*
10923	 * The initiator attempted multiple untagged commands at the same
10924	 * time.  Can't do that.
10925	 */
10926	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10927	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10928	 && ((pending_io->io_hdr.nexus.targ_port ==
10929	      ooa_io->io_hdr.nexus.targ_port)
10930	  && (pending_io->io_hdr.nexus.initid.id ==
10931	      ooa_io->io_hdr.nexus.initid.id))
10932	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10933		return (CTL_ACTION_OVERLAP);
10934
10935	/*
10936	 * The initiator attempted to send multiple tagged commands with
10937	 * the same ID.  (It's fine if different initiators have the same
10938	 * tag ID.)
10939	 *
10940	 * Even if all of those conditions are true, we don't kill the I/O
10941	 * if the command ahead of us has been aborted.  We won't end up
10942	 * sending it to the FETD, and it's perfectly legal to resend a
10943	 * command with the same tag number as long as the previous
10944	 * instance of this tag number has been aborted somehow.
10945	 */
10946	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10947	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10948	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10949	 && ((pending_io->io_hdr.nexus.targ_port ==
10950	      ooa_io->io_hdr.nexus.targ_port)
10951	  && (pending_io->io_hdr.nexus.initid.id ==
10952	      ooa_io->io_hdr.nexus.initid.id))
10953	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10954		return (CTL_ACTION_OVERLAP_TAG);
10955
10956	/*
10957	 * If we get a head of queue tag, SAM-3 says that we should
10958	 * immediately execute it.
10959	 *
10960	 * What happens if this command would normally block for some other
10961	 * reason?  e.g. a request sense with a head of queue tag
10962	 * immediately after a write.  Normally that would block, but this
10963	 * will result in its getting executed immediately...
10964	 *
10965	 * We currently return "pass" instead of "skip", so we'll end up
10966	 * going through the rest of the queue to check for overlapped tags.
10967	 *
10968	 * XXX KDM check for other types of blockage first??
10969	 */
10970	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10971		return (CTL_ACTION_PASS);
10972
10973	/*
10974	 * Ordered tags have to block until all items ahead of them
10975	 * have completed.  If we get called with an ordered tag, we always
10976	 * block, if something else is ahead of us in the queue.
10977	 */
10978	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10979		return (CTL_ACTION_BLOCK);
10980
10981	/*
10982	 * Simple tags get blocked until all head of queue and ordered tags
10983	 * ahead of them have completed.  I'm lumping untagged commands in
10984	 * with simple tags here.  XXX KDM is that the right thing to do?
10985	 */
10986	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10987	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10988	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10989	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10990		return (CTL_ACTION_BLOCK);
10991
10992	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10993	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10994
10995	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10996
10997	switch (serialize_row[pending_entry->seridx]) {
10998	case CTL_SER_BLOCK:
10999		return (CTL_ACTION_BLOCK);
11000		break; /* NOTREACHED */
11001	case CTL_SER_EXTENT:
11002		return (ctl_extent_check(pending_io, ooa_io));
11003		break; /* NOTREACHED */
11004	case CTL_SER_PASS:
11005		return (CTL_ACTION_PASS);
11006		break; /* NOTREACHED */
11007	case CTL_SER_SKIP:
11008		return (CTL_ACTION_SKIP);
11009		break;
11010	default:
11011		panic("invalid serialization value %d",
11012		      serialize_row[pending_entry->seridx]);
11013		break; /* NOTREACHED */
11014	}
11015
11016	return (CTL_ACTION_ERROR);
11017}
11018
11019/*
11020 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11021 * Assumptions:
11022 * - pending_io is generally either incoming, or on the blocked queue
11023 * - starting I/O is the I/O we want to start the check with.
11024 */
11025static ctl_action
11026ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11027	      union ctl_io *starting_io)
11028{
11029	union ctl_io *ooa_io;
11030	ctl_action action;
11031
11032	mtx_assert(&lun->lun_lock, MA_OWNED);
11033
11034	/*
11035	 * Run back along the OOA queue, starting with the current
11036	 * blocked I/O and going through every I/O before it on the
11037	 * queue.  If starting_io is NULL, we'll just end up returning
11038	 * CTL_ACTION_PASS.
11039	 */
11040	for (ooa_io = starting_io; ooa_io != NULL;
11041	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11042	     ooa_links)){
11043
11044		/*
11045		 * This routine just checks to see whether
11046		 * cur_blocked is blocked by ooa_io, which is ahead
11047		 * of it in the queue.  It doesn't queue/dequeue
11048		 * cur_blocked.
11049		 */
11050		action = ctl_check_for_blockage(pending_io, ooa_io);
11051		switch (action) {
11052		case CTL_ACTION_BLOCK:
11053		case CTL_ACTION_OVERLAP:
11054		case CTL_ACTION_OVERLAP_TAG:
11055		case CTL_ACTION_SKIP:
11056		case CTL_ACTION_ERROR:
11057			return (action);
11058			break; /* NOTREACHED */
11059		case CTL_ACTION_PASS:
11060			break;
11061		default:
11062			panic("invalid action %d", action);
11063			break;  /* NOTREACHED */
11064		}
11065	}
11066
11067	return (CTL_ACTION_PASS);
11068}
11069
11070/*
11071 * Assumptions:
11072 * - An I/O has just completed, and has been removed from the per-LUN OOA
11073 *   queue, so some items on the blocked queue may now be unblocked.
11074 */
11075static int
11076ctl_check_blocked(struct ctl_lun *lun)
11077{
11078	union ctl_io *cur_blocked, *next_blocked;
11079
11080	mtx_assert(&lun->lun_lock, MA_OWNED);
11081
11082	/*
11083	 * Run forward from the head of the blocked queue, checking each
11084	 * entry against the I/Os prior to it on the OOA queue to see if
11085	 * there is still any blockage.
11086	 *
11087	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11088	 * with our removing a variable on it while it is traversing the
11089	 * list.
11090	 */
11091	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11092	     cur_blocked != NULL; cur_blocked = next_blocked) {
11093		union ctl_io *prev_ooa;
11094		ctl_action action;
11095
11096		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11097							  blocked_links);
11098
11099		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11100						      ctl_ooaq, ooa_links);
11101
11102		/*
11103		 * If cur_blocked happens to be the first item in the OOA
11104		 * queue now, prev_ooa will be NULL, and the action
11105		 * returned will just be CTL_ACTION_PASS.
11106		 */
11107		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11108
11109		switch (action) {
11110		case CTL_ACTION_BLOCK:
11111			/* Nothing to do here, still blocked */
11112			break;
11113		case CTL_ACTION_OVERLAP:
11114		case CTL_ACTION_OVERLAP_TAG:
11115			/*
11116			 * This shouldn't happen!  In theory we've already
11117			 * checked this command for overlap...
11118			 */
11119			break;
11120		case CTL_ACTION_PASS:
11121		case CTL_ACTION_SKIP: {
11122			struct ctl_softc *softc;
11123			const struct ctl_cmd_entry *entry;
11124			uint32_t initidx;
11125			int isc_retval;
11126
11127			/*
11128			 * The skip case shouldn't happen, this transaction
11129			 * should have never made it onto the blocked queue.
11130			 */
11131			/*
11132			 * This I/O is no longer blocked, we can remove it
11133			 * from the blocked queue.  Since this is a TAILQ
11134			 * (doubly linked list), we can do O(1) removals
11135			 * from any place on the list.
11136			 */
11137			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11138				     blocked_links);
11139			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11140
11141			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11142				/*
11143				 * Need to send IO back to original side to
11144				 * run
11145				 */
11146				union ctl_ha_msg msg_info;
11147
11148				msg_info.hdr.original_sc =
11149					cur_blocked->io_hdr.original_sc;
11150				msg_info.hdr.serializing_sc = cur_blocked;
11151				msg_info.hdr.msg_type = CTL_MSG_R2R;
11152				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11153				     &msg_info, sizeof(msg_info), 0)) >
11154				     CTL_HA_STATUS_SUCCESS) {
11155					printf("CTL:Check Blocked error from "
11156					       "ctl_ha_msg_send %d\n",
11157					       isc_retval);
11158				}
11159				break;
11160			}
11161			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
11162			softc = control_softc;
11163
11164			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11165
11166			/*
11167			 * Check this I/O for LUN state changes that may
11168			 * have happened while this command was blocked.
11169			 * The LUN state may have been changed by a command
11170			 * ahead of us in the queue, so we need to re-check
11171			 * for any states that can be caused by SCSI
11172			 * commands.
11173			 */
11174			if (ctl_scsiio_lun_check(softc, lun, entry,
11175						 &cur_blocked->scsiio) == 0) {
11176				cur_blocked->io_hdr.flags |=
11177				                      CTL_FLAG_IS_WAS_ON_RTR;
11178				ctl_enqueue_rtr(cur_blocked);
11179			} else
11180				ctl_done(cur_blocked);
11181			break;
11182		}
11183		default:
11184			/*
11185			 * This probably shouldn't happen -- we shouldn't
11186			 * get CTL_ACTION_ERROR, or anything else.
11187			 */
11188			break;
11189		}
11190	}
11191
11192	return (CTL_RETVAL_COMPLETE);
11193}
11194
11195/*
11196 * This routine (with one exception) checks LUN flags that can be set by
11197 * commands ahead of us in the OOA queue.  These flags have to be checked
11198 * when a command initially comes in, and when we pull a command off the
11199 * blocked queue and are preparing to execute it.  The reason we have to
11200 * check these flags for commands on the blocked queue is that the LUN
11201 * state may have been changed by a command ahead of us while we're on the
11202 * blocked queue.
11203 *
11204 * Ordering is somewhat important with these checks, so please pay
11205 * careful attention to the placement of any new checks.
11206 */
11207static int
11208ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11209    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11210{
11211	int retval;
11212
11213	retval = 0;
11214
11215	mtx_assert(&lun->lun_lock, MA_OWNED);
11216
11217	/*
11218	 * If this shelf is a secondary shelf controller, we have to reject
11219	 * any media access commands.
11220	 */
11221#if 0
11222	/* No longer needed for HA */
11223	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11224	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11225		ctl_set_lun_standby(ctsio);
11226		retval = 1;
11227		goto bailout;
11228	}
11229#endif
11230
11231	/*
11232	 * Check for a reservation conflict.  If this command isn't allowed
11233	 * even on reserved LUNs, and if this initiator isn't the one who
11234	 * reserved us, reject the command with a reservation conflict.
11235	 */
11236	if ((lun->flags & CTL_LUN_RESERVED)
11237	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11238		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11239		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11240		 || (ctsio->io_hdr.nexus.targ_target.id !=
11241		     lun->rsv_nexus.targ_target.id)) {
11242			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11243			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11244			retval = 1;
11245			goto bailout;
11246		}
11247	}
11248
11249	if ( (lun->flags & CTL_LUN_PR_RESERVED)
11250	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11251		uint32_t residx;
11252
11253		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11254		/*
11255		 * if we aren't registered or it's a res holder type
11256		 * reservation and this isn't the res holder then set a
11257		 * conflict.
11258		 * NOTE: Commands which might be allowed on write exclusive
11259		 * type reservations are checked in the particular command
11260		 * for a conflict. Read and SSU are the only ones.
11261		 */
11262		if (!lun->per_res[residx].registered
11263		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11264			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11265			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11266			retval = 1;
11267			goto bailout;
11268		}
11269
11270	}
11271
11272	if ((lun->flags & CTL_LUN_OFFLINE)
11273	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11274		ctl_set_lun_not_ready(ctsio);
11275		retval = 1;
11276		goto bailout;
11277	}
11278
11279	/*
11280	 * If the LUN is stopped, see if this particular command is allowed
11281	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11282	 */
11283	if ((lun->flags & CTL_LUN_STOPPED)
11284	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11285		/* "Logical unit not ready, initializing cmd. required" */
11286		ctl_set_lun_stopped(ctsio);
11287		retval = 1;
11288		goto bailout;
11289	}
11290
11291	if ((lun->flags & CTL_LUN_INOPERABLE)
11292	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11293		/* "Medium format corrupted" */
11294		ctl_set_medium_format_corrupted(ctsio);
11295		retval = 1;
11296		goto bailout;
11297	}
11298
11299bailout:
11300	return (retval);
11301
11302}
11303
11304static void
11305ctl_failover_io(union ctl_io *io, int have_lock)
11306{
11307	ctl_set_busy(&io->scsiio);
11308	ctl_done(io);
11309}
11310
11311static void
11312ctl_failover(void)
11313{
11314	struct ctl_lun *lun;
11315	struct ctl_softc *ctl_softc;
11316	union ctl_io *next_io, *pending_io;
11317	union ctl_io *io;
11318	int lun_idx;
11319	int i;
11320
11321	ctl_softc = control_softc;
11322
11323	mtx_lock(&ctl_softc->ctl_lock);
11324	/*
11325	 * Remove any cmds from the other SC from the rtr queue.  These
11326	 * will obviously only be for LUNs for which we're the primary.
11327	 * We can't send status or get/send data for these commands.
11328	 * Since they haven't been executed yet, we can just remove them.
11329	 * We'll either abort them or delete them below, depending on
11330	 * which HA mode we're in.
11331	 */
11332#ifdef notyet
11333	mtx_lock(&ctl_softc->queue_lock);
11334	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11335	     io != NULL; io = next_io) {
11336		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11337		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11338			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11339				      ctl_io_hdr, links);
11340	}
11341	mtx_unlock(&ctl_softc->queue_lock);
11342#endif
11343
11344	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11345		lun = ctl_softc->ctl_luns[lun_idx];
11346		if (lun==NULL)
11347			continue;
11348
11349		/*
11350		 * Processor LUNs are primary on both sides.
11351		 * XXX will this always be true?
11352		 */
11353		if (lun->be_lun->lun_type == T_PROCESSOR)
11354			continue;
11355
11356		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11357		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11358			printf("FAILOVER: primary lun %d\n", lun_idx);
11359		        /*
11360			 * Remove all commands from the other SC. First from the
11361			 * blocked queue then from the ooa queue. Once we have
11362			 * removed them. Call ctl_check_blocked to see if there
11363			 * is anything that can run.
11364			 */
11365			for (io = (union ctl_io *)TAILQ_FIRST(
11366			     &lun->blocked_queue); io != NULL; io = next_io) {
11367
11368		        	next_io = (union ctl_io *)TAILQ_NEXT(
11369				    &io->io_hdr, blocked_links);
11370
11371				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11372					TAILQ_REMOVE(&lun->blocked_queue,
11373						     &io->io_hdr,blocked_links);
11374					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11375					TAILQ_REMOVE(&lun->ooa_queue,
11376						     &io->io_hdr, ooa_links);
11377
11378					ctl_free_io(io);
11379				}
11380			}
11381
11382			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11383	     		     io != NULL; io = next_io) {
11384
11385		        	next_io = (union ctl_io *)TAILQ_NEXT(
11386				    &io->io_hdr, ooa_links);
11387
11388				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11389
11390					TAILQ_REMOVE(&lun->ooa_queue,
11391						&io->io_hdr,
11392					     	ooa_links);
11393
11394					ctl_free_io(io);
11395				}
11396			}
11397			ctl_check_blocked(lun);
11398		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11399			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11400
11401			printf("FAILOVER: primary lun %d\n", lun_idx);
11402			/*
11403			 * Abort all commands from the other SC.  We can't
11404			 * send status back for them now.  These should get
11405			 * cleaned up when they are completed or come out
11406			 * for a datamove operation.
11407			 */
11408			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11409	     		     io != NULL; io = next_io) {
11410		        	next_io = (union ctl_io *)TAILQ_NEXT(
11411					&io->io_hdr, ooa_links);
11412
11413				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11414					io->io_hdr.flags |= CTL_FLAG_ABORT;
11415			}
11416		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11417			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11418
11419			printf("FAILOVER: secondary lun %d\n", lun_idx);
11420
11421			lun->flags |= CTL_LUN_PRIMARY_SC;
11422
11423			/*
11424			 * We send all I/O that was sent to this controller
11425			 * and redirected to the other side back with
11426			 * busy status, and have the initiator retry it.
11427			 * Figuring out how much data has been transferred,
11428			 * etc. and picking up where we left off would be
11429			 * very tricky.
11430			 *
11431			 * XXX KDM need to remove I/O from the blocked
11432			 * queue as well!
11433			 */
11434			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11435			     &lun->ooa_queue); pending_io != NULL;
11436			     pending_io = next_io) {
11437
11438				next_io =  (union ctl_io *)TAILQ_NEXT(
11439					&pending_io->io_hdr, ooa_links);
11440
11441				pending_io->io_hdr.flags &=
11442					~CTL_FLAG_SENT_2OTHER_SC;
11443
11444				if (pending_io->io_hdr.flags &
11445				    CTL_FLAG_IO_ACTIVE) {
11446					pending_io->io_hdr.flags |=
11447						CTL_FLAG_FAILOVER;
11448				} else {
11449					ctl_set_busy(&pending_io->scsiio);
11450					ctl_done(pending_io);
11451				}
11452			}
11453
11454			/*
11455			 * Build Unit Attention
11456			 */
11457			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11458				lun->pending_ua[i] |=
11459				                     CTL_UA_ASYM_ACC_CHANGE;
11460			}
11461		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11462			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11463			printf("FAILOVER: secondary lun %d\n", lun_idx);
11464			/*
11465			 * if the first io on the OOA is not on the RtR queue
11466			 * add it.
11467			 */
11468			lun->flags |= CTL_LUN_PRIMARY_SC;
11469
11470			pending_io = (union ctl_io *)TAILQ_FIRST(
11471			    &lun->ooa_queue);
11472			if (pending_io==NULL) {
11473				printf("Nothing on OOA queue\n");
11474				continue;
11475			}
11476
11477			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11478			if ((pending_io->io_hdr.flags &
11479			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11480				pending_io->io_hdr.flags |=
11481				    CTL_FLAG_IS_WAS_ON_RTR;
11482				ctl_enqueue_rtr(pending_io);
11483			}
11484#if 0
11485			else
11486			{
11487				printf("Tag 0x%04x is running\n",
11488				      pending_io->scsiio.tag_num);
11489			}
11490#endif
11491
11492			next_io = (union ctl_io *)TAILQ_NEXT(
11493			    &pending_io->io_hdr, ooa_links);
11494			for (pending_io=next_io; pending_io != NULL;
11495			     pending_io = next_io) {
11496				pending_io->io_hdr.flags &=
11497				    ~CTL_FLAG_SENT_2OTHER_SC;
11498				next_io = (union ctl_io *)TAILQ_NEXT(
11499					&pending_io->io_hdr, ooa_links);
11500				if (pending_io->io_hdr.flags &
11501				    CTL_FLAG_IS_WAS_ON_RTR) {
11502#if 0
11503				        printf("Tag 0x%04x is running\n",
11504				      		pending_io->scsiio.tag_num);
11505#endif
11506					continue;
11507				}
11508
11509				switch (ctl_check_ooa(lun, pending_io,
11510			            (union ctl_io *)TAILQ_PREV(
11511				    &pending_io->io_hdr, ctl_ooaq,
11512				    ooa_links))) {
11513
11514				case CTL_ACTION_BLOCK:
11515					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11516							  &pending_io->io_hdr,
11517							  blocked_links);
11518					pending_io->io_hdr.flags |=
11519					    CTL_FLAG_BLOCKED;
11520					break;
11521				case CTL_ACTION_PASS:
11522				case CTL_ACTION_SKIP:
11523					pending_io->io_hdr.flags |=
11524					    CTL_FLAG_IS_WAS_ON_RTR;
11525					ctl_enqueue_rtr(pending_io);
11526					break;
11527				case CTL_ACTION_OVERLAP:
11528					ctl_set_overlapped_cmd(
11529					    (struct ctl_scsiio *)pending_io);
11530					ctl_done(pending_io);
11531					break;
11532				case CTL_ACTION_OVERLAP_TAG:
11533					ctl_set_overlapped_tag(
11534					    (struct ctl_scsiio *)pending_io,
11535					    pending_io->scsiio.tag_num & 0xff);
11536					ctl_done(pending_io);
11537					break;
11538				case CTL_ACTION_ERROR:
11539				default:
11540					ctl_set_internal_failure(
11541						(struct ctl_scsiio *)pending_io,
11542						0,  // sks_valid
11543						0); //retry count
11544					ctl_done(pending_io);
11545					break;
11546				}
11547			}
11548
11549			/*
11550			 * Build Unit Attention
11551			 */
11552			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11553				lun->pending_ua[i] |=
11554				                     CTL_UA_ASYM_ACC_CHANGE;
11555			}
11556		} else {
11557			panic("Unhandled HA mode failover, LUN flags = %#x, "
11558			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11559		}
11560	}
11561	ctl_pause_rtr = 0;
11562	mtx_unlock(&ctl_softc->ctl_lock);
11563}
11564
11565static int
11566ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11567{
11568	struct ctl_lun *lun;
11569	const struct ctl_cmd_entry *entry;
11570	uint32_t initidx, targ_lun;
11571	int retval;
11572
11573	retval = 0;
11574
11575	lun = NULL;
11576
11577	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11578	if ((targ_lun < CTL_MAX_LUNS)
11579	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11580		lun = ctl_softc->ctl_luns[targ_lun];
11581		/*
11582		 * If the LUN is invalid, pretend that it doesn't exist.
11583		 * It will go away as soon as all pending I/O has been
11584		 * completed.
11585		 */
11586		if (lun->flags & CTL_LUN_DISABLED) {
11587			lun = NULL;
11588		} else {
11589			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11590			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11591				lun->be_lun;
11592			if (lun->be_lun->lun_type == T_PROCESSOR) {
11593				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11594			}
11595
11596			/*
11597			 * Every I/O goes into the OOA queue for a
11598			 * particular LUN, and stays there until completion.
11599			 */
11600			mtx_lock(&lun->lun_lock);
11601			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11602			    ooa_links);
11603		}
11604	} else {
11605		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11606		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11607	}
11608
11609	/* Get command entry and return error if it is unsuppotyed. */
11610	entry = ctl_validate_command(ctsio);
11611	if (entry == NULL) {
11612		if (lun)
11613			mtx_unlock(&lun->lun_lock);
11614		return (retval);
11615	}
11616
11617	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11618	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11619
11620	/*
11621	 * Check to see whether we can send this command to LUNs that don't
11622	 * exist.  This should pretty much only be the case for inquiry
11623	 * and request sense.  Further checks, below, really require having
11624	 * a LUN, so we can't really check the command anymore.  Just put
11625	 * it on the rtr queue.
11626	 */
11627	if (lun == NULL) {
11628		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11629			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11630			ctl_enqueue_rtr((union ctl_io *)ctsio);
11631			return (retval);
11632		}
11633
11634		ctl_set_unsupported_lun(ctsio);
11635		ctl_done((union ctl_io *)ctsio);
11636		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11637		return (retval);
11638	} else {
11639		/*
11640		 * Make sure we support this particular command on this LUN.
11641		 * e.g., we don't support writes to the control LUN.
11642		 */
11643		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11644			mtx_unlock(&lun->lun_lock);
11645			ctl_set_invalid_opcode(ctsio);
11646			ctl_done((union ctl_io *)ctsio);
11647			return (retval);
11648		}
11649	}
11650
11651	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11652
11653#ifdef CTL_WITH_CA
11654	/*
11655	 * If we've got a request sense, it'll clear the contingent
11656	 * allegiance condition.  Otherwise, if we have a CA condition for
11657	 * this initiator, clear it, because it sent down a command other
11658	 * than request sense.
11659	 */
11660	if ((ctsio->cdb[0] != REQUEST_SENSE)
11661	 && (ctl_is_set(lun->have_ca, initidx)))
11662		ctl_clear_mask(lun->have_ca, initidx);
11663#endif
11664
11665	/*
11666	 * If the command has this flag set, it handles its own unit
11667	 * attention reporting, we shouldn't do anything.  Otherwise we
11668	 * check for any pending unit attentions, and send them back to the
11669	 * initiator.  We only do this when a command initially comes in,
11670	 * not when we pull it off the blocked queue.
11671	 *
11672	 * According to SAM-3, section 5.3.2, the order that things get
11673	 * presented back to the host is basically unit attentions caused
11674	 * by some sort of reset event, busy status, reservation conflicts
11675	 * or task set full, and finally any other status.
11676	 *
11677	 * One issue here is that some of the unit attentions we report
11678	 * don't fall into the "reset" category (e.g. "reported luns data
11679	 * has changed").  So reporting it here, before the reservation
11680	 * check, may be technically wrong.  I guess the only thing to do
11681	 * would be to check for and report the reset events here, and then
11682	 * check for the other unit attention types after we check for a
11683	 * reservation conflict.
11684	 *
11685	 * XXX KDM need to fix this
11686	 */
11687	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11688		ctl_ua_type ua_type;
11689
11690		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11691			scsi_sense_data_type sense_format;
11692
11693			if (lun != NULL)
11694				sense_format = (lun->flags &
11695				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11696				    SSD_TYPE_FIXED;
11697			else
11698				sense_format = SSD_TYPE_FIXED;
11699
11700			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11701			    &ctsio->sense_data, sense_format);
11702			if (ua_type != CTL_UA_NONE) {
11703				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11704				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11705						       CTL_AUTOSENSE;
11706				ctsio->sense_len = SSD_FULL_SIZE;
11707				mtx_unlock(&lun->lun_lock);
11708				ctl_done((union ctl_io *)ctsio);
11709				return (retval);
11710			}
11711		}
11712	}
11713
11714
11715	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11716		mtx_unlock(&lun->lun_lock);
11717		ctl_done((union ctl_io *)ctsio);
11718		return (retval);
11719	}
11720
11721	/*
11722	 * XXX CHD this is where we want to send IO to other side if
11723	 * this LUN is secondary on this SC. We will need to make a copy
11724	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11725	 * the copy we send as FROM_OTHER.
11726	 * We also need to stuff the address of the original IO so we can
11727	 * find it easily. Something similar will need be done on the other
11728	 * side so when we are done we can find the copy.
11729	 */
11730	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11731		union ctl_ha_msg msg_info;
11732		int isc_retval;
11733
11734		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11735
11736		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11737		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11738#if 0
11739		printf("1. ctsio %p\n", ctsio);
11740#endif
11741		msg_info.hdr.serializing_sc = NULL;
11742		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11743		msg_info.scsi.tag_num = ctsio->tag_num;
11744		msg_info.scsi.tag_type = ctsio->tag_type;
11745		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11746
11747		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11748
11749		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11750		    (void *)&msg_info, sizeof(msg_info), 0)) >
11751		    CTL_HA_STATUS_SUCCESS) {
11752			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11753			       isc_retval);
11754			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11755		} else {
11756#if 0
11757			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11758#endif
11759		}
11760
11761		/*
11762		 * XXX KDM this I/O is off the incoming queue, but hasn't
11763		 * been inserted on any other queue.  We may need to come
11764		 * up with a holding queue while we wait for serialization
11765		 * so that we have an idea of what we're waiting for from
11766		 * the other side.
11767		 */
11768		mtx_unlock(&lun->lun_lock);
11769		return (retval);
11770	}
11771
11772	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11773			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11774			      ctl_ooaq, ooa_links))) {
11775	case CTL_ACTION_BLOCK:
11776		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11777		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11778				  blocked_links);
11779		mtx_unlock(&lun->lun_lock);
11780		return (retval);
11781	case CTL_ACTION_PASS:
11782	case CTL_ACTION_SKIP:
11783		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11784		mtx_unlock(&lun->lun_lock);
11785		ctl_enqueue_rtr((union ctl_io *)ctsio);
11786		break;
11787	case CTL_ACTION_OVERLAP:
11788		mtx_unlock(&lun->lun_lock);
11789		ctl_set_overlapped_cmd(ctsio);
11790		ctl_done((union ctl_io *)ctsio);
11791		break;
11792	case CTL_ACTION_OVERLAP_TAG:
11793		mtx_unlock(&lun->lun_lock);
11794		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11795		ctl_done((union ctl_io *)ctsio);
11796		break;
11797	case CTL_ACTION_ERROR:
11798	default:
11799		mtx_unlock(&lun->lun_lock);
11800		ctl_set_internal_failure(ctsio,
11801					 /*sks_valid*/ 0,
11802					 /*retry_count*/ 0);
11803		ctl_done((union ctl_io *)ctsio);
11804		break;
11805	}
11806	return (retval);
11807}
11808
11809const struct ctl_cmd_entry *
11810ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11811{
11812	const struct ctl_cmd_entry *entry;
11813	int service_action;
11814
11815	entry = &ctl_cmd_table[ctsio->cdb[0]];
11816	if (entry->flags & CTL_CMD_FLAG_SA5) {
11817		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11818		entry = &((const struct ctl_cmd_entry *)
11819		    entry->execute)[service_action];
11820	}
11821	return (entry);
11822}
11823
11824const struct ctl_cmd_entry *
11825ctl_validate_command(struct ctl_scsiio *ctsio)
11826{
11827	const struct ctl_cmd_entry *entry;
11828	int i;
11829	uint8_t diff;
11830
11831	entry = ctl_get_cmd_entry(ctsio);
11832	if (entry->execute == NULL) {
11833		ctl_set_invalid_opcode(ctsio);
11834		ctl_done((union ctl_io *)ctsio);
11835		return (NULL);
11836	}
11837	KASSERT(entry->length > 0,
11838	    ("Not defined length for command 0x%02x/0x%02x",
11839	     ctsio->cdb[0], ctsio->cdb[1]));
11840	for (i = 1; i < entry->length; i++) {
11841		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11842		if (diff == 0)
11843			continue;
11844		ctl_set_invalid_field(ctsio,
11845				      /*sks_valid*/ 1,
11846				      /*command*/ 1,
11847				      /*field*/ i,
11848				      /*bit_valid*/ 1,
11849				      /*bit*/ fls(diff) - 1);
11850		ctl_done((union ctl_io *)ctsio);
11851		return (NULL);
11852	}
11853	return (entry);
11854}
11855
11856static int
11857ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11858{
11859
11860	switch (lun_type) {
11861	case T_PROCESSOR:
11862		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11863		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11864			return (0);
11865		break;
11866	case T_DIRECT:
11867		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11868		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11869			return (0);
11870		break;
11871	default:
11872		return (0);
11873	}
11874	return (1);
11875}
11876
11877static int
11878ctl_scsiio(struct ctl_scsiio *ctsio)
11879{
11880	int retval;
11881	const struct ctl_cmd_entry *entry;
11882
11883	retval = CTL_RETVAL_COMPLETE;
11884
11885	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11886
11887	entry = ctl_get_cmd_entry(ctsio);
11888
11889	/*
11890	 * If this I/O has been aborted, just send it straight to
11891	 * ctl_done() without executing it.
11892	 */
11893	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11894		ctl_done((union ctl_io *)ctsio);
11895		goto bailout;
11896	}
11897
11898	/*
11899	 * All the checks should have been handled by ctl_scsiio_precheck().
11900	 * We should be clear now to just execute the I/O.
11901	 */
11902	retval = entry->execute(ctsio);
11903
11904bailout:
11905	return (retval);
11906}
11907
11908/*
11909 * Since we only implement one target right now, a bus reset simply resets
11910 * our single target.
11911 */
11912static int
11913ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11914{
11915	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11916}
11917
11918static int
11919ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11920		 ctl_ua_type ua_type)
11921{
11922	struct ctl_lun *lun;
11923	int retval;
11924
11925	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11926		union ctl_ha_msg msg_info;
11927
11928		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11929		msg_info.hdr.nexus = io->io_hdr.nexus;
11930		if (ua_type==CTL_UA_TARG_RESET)
11931			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11932		else
11933			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11934		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11935		msg_info.hdr.original_sc = NULL;
11936		msg_info.hdr.serializing_sc = NULL;
11937		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11938		    (void *)&msg_info, sizeof(msg_info), 0)) {
11939		}
11940	}
11941	retval = 0;
11942
11943	mtx_lock(&ctl_softc->ctl_lock);
11944	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11945		retval += ctl_lun_reset(lun, io, ua_type);
11946	mtx_unlock(&ctl_softc->ctl_lock);
11947
11948	return (retval);
11949}
11950
11951/*
11952 * The LUN should always be set.  The I/O is optional, and is used to
11953 * distinguish between I/Os sent by this initiator, and by other
11954 * initiators.  We set unit attention for initiators other than this one.
11955 * SAM-3 is vague on this point.  It does say that a unit attention should
11956 * be established for other initiators when a LUN is reset (see section
11957 * 5.7.3), but it doesn't specifically say that the unit attention should
11958 * be established for this particular initiator when a LUN is reset.  Here
11959 * is the relevant text, from SAM-3 rev 8:
11960 *
11961 * 5.7.2 When a SCSI initiator port aborts its own tasks
11962 *
11963 * When a SCSI initiator port causes its own task(s) to be aborted, no
11964 * notification that the task(s) have been aborted shall be returned to
11965 * the SCSI initiator port other than the completion response for the
11966 * command or task management function action that caused the task(s) to
11967 * be aborted and notification(s) associated with related effects of the
11968 * action (e.g., a reset unit attention condition).
11969 *
11970 * XXX KDM for now, we're setting unit attention for all initiators.
11971 */
11972static int
11973ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11974{
11975	union ctl_io *xio;
11976#if 0
11977	uint32_t initindex;
11978#endif
11979	int i;
11980
11981	mtx_lock(&lun->lun_lock);
11982	/*
11983	 * Run through the OOA queue and abort each I/O.
11984	 */
11985#if 0
11986	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11987#endif
11988	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11989	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11990		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11991	}
11992
11993	/*
11994	 * This version sets unit attention for every
11995	 */
11996#if 0
11997	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11998	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11999		if (initindex == i)
12000			continue;
12001		lun->pending_ua[i] |= ua_type;
12002	}
12003#endif
12004
12005	/*
12006	 * A reset (any kind, really) clears reservations established with
12007	 * RESERVE/RELEASE.  It does not clear reservations established
12008	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12009	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12010	 * reservations made with the RESERVE/RELEASE commands, because
12011	 * those commands are obsolete in SPC-3.
12012	 */
12013	lun->flags &= ~CTL_LUN_RESERVED;
12014
12015	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12016#ifdef CTL_WITH_CA
12017		ctl_clear_mask(lun->have_ca, i);
12018#endif
12019		lun->pending_ua[i] |= ua_type;
12020	}
12021	mtx_unlock(&lun->lun_lock);
12022
12023	return (0);
12024}
12025
12026static int
12027ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12028    int other_sc)
12029{
12030	union ctl_io *xio;
12031	int found;
12032
12033	mtx_assert(&lun->lun_lock, MA_OWNED);
12034
12035	/*
12036	 * Run through the OOA queue and attempt to find the given I/O.
12037	 * The target port, initiator ID, tag type and tag number have to
12038	 * match the values that we got from the initiator.  If we have an
12039	 * untagged command to abort, simply abort the first untagged command
12040	 * we come to.  We only allow one untagged command at a time of course.
12041	 */
12042	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12043	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12044
12045		if ((targ_port == UINT32_MAX ||
12046		     targ_port == xio->io_hdr.nexus.targ_port) &&
12047		    (init_id == UINT32_MAX ||
12048		     init_id == xio->io_hdr.nexus.initid.id)) {
12049			if (targ_port != xio->io_hdr.nexus.targ_port ||
12050			    init_id != xio->io_hdr.nexus.initid.id)
12051				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12052			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12053			found = 1;
12054			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12055				union ctl_ha_msg msg_info;
12056
12057				msg_info.hdr.nexus = xio->io_hdr.nexus;
12058				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12059				msg_info.task.tag_num = xio->scsiio.tag_num;
12060				msg_info.task.tag_type = xio->scsiio.tag_type;
12061				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12062				msg_info.hdr.original_sc = NULL;
12063				msg_info.hdr.serializing_sc = NULL;
12064				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12065				    (void *)&msg_info, sizeof(msg_info), 0);
12066			}
12067		}
12068	}
12069	return (found);
12070}
12071
12072static int
12073ctl_abort_task_set(union ctl_io *io)
12074{
12075	struct ctl_softc *softc = control_softc;
12076	struct ctl_lun *lun;
12077	uint32_t targ_lun;
12078
12079	/*
12080	 * Look up the LUN.
12081	 */
12082	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12083	mtx_lock(&softc->ctl_lock);
12084	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12085		lun = softc->ctl_luns[targ_lun];
12086	else {
12087		mtx_unlock(&softc->ctl_lock);
12088		return (1);
12089	}
12090
12091	mtx_lock(&lun->lun_lock);
12092	mtx_unlock(&softc->ctl_lock);
12093	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12094		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12095		    io->io_hdr.nexus.initid.id,
12096		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12097	} else { /* CTL_TASK_CLEAR_TASK_SET */
12098		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12099		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12100	}
12101	mtx_unlock(&lun->lun_lock);
12102	return (0);
12103}
12104
12105static int
12106ctl_i_t_nexus_reset(union ctl_io *io)
12107{
12108	struct ctl_softc *softc = control_softc;
12109	struct ctl_lun *lun;
12110	uint32_t initindex;
12111
12112	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12113	mtx_lock(&softc->ctl_lock);
12114	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12115		mtx_lock(&lun->lun_lock);
12116		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12117		    io->io_hdr.nexus.initid.id,
12118		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12119#ifdef CTL_WITH_CA
12120		ctl_clear_mask(lun->have_ca, initindex);
12121#endif
12122		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12123		mtx_unlock(&lun->lun_lock);
12124	}
12125	mtx_unlock(&softc->ctl_lock);
12126	return (0);
12127}
12128
12129static int
12130ctl_abort_task(union ctl_io *io)
12131{
12132	union ctl_io *xio;
12133	struct ctl_lun *lun;
12134	struct ctl_softc *ctl_softc;
12135#if 0
12136	struct sbuf sb;
12137	char printbuf[128];
12138#endif
12139	int found;
12140	uint32_t targ_lun;
12141
12142	ctl_softc = control_softc;
12143	found = 0;
12144
12145	/*
12146	 * Look up the LUN.
12147	 */
12148	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12149	mtx_lock(&ctl_softc->ctl_lock);
12150	if ((targ_lun < CTL_MAX_LUNS)
12151	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12152		lun = ctl_softc->ctl_luns[targ_lun];
12153	else {
12154		mtx_unlock(&ctl_softc->ctl_lock);
12155		return (1);
12156	}
12157
12158#if 0
12159	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12160	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12161#endif
12162
12163	mtx_lock(&lun->lun_lock);
12164	mtx_unlock(&ctl_softc->ctl_lock);
12165	/*
12166	 * Run through the OOA queue and attempt to find the given I/O.
12167	 * The target port, initiator ID, tag type and tag number have to
12168	 * match the values that we got from the initiator.  If we have an
12169	 * untagged command to abort, simply abort the first untagged command
12170	 * we come to.  We only allow one untagged command at a time of course.
12171	 */
12172#if 0
12173	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12174#endif
12175	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12176	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12177#if 0
12178		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12179
12180		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12181			    lun->lun, xio->scsiio.tag_num,
12182			    xio->scsiio.tag_type,
12183			    (xio->io_hdr.blocked_links.tqe_prev
12184			    == NULL) ? "" : " BLOCKED",
12185			    (xio->io_hdr.flags &
12186			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12187			    (xio->io_hdr.flags &
12188			    CTL_FLAG_ABORT) ? " ABORT" : "",
12189			    (xio->io_hdr.flags &
12190			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12191		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12192		sbuf_finish(&sb);
12193		printf("%s\n", sbuf_data(&sb));
12194#endif
12195
12196		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12197		 && (xio->io_hdr.nexus.initid.id ==
12198		     io->io_hdr.nexus.initid.id)) {
12199			/*
12200			 * If the abort says that the task is untagged, the
12201			 * task in the queue must be untagged.  Otherwise,
12202			 * we just check to see whether the tag numbers
12203			 * match.  This is because the QLogic firmware
12204			 * doesn't pass back the tag type in an abort
12205			 * request.
12206			 */
12207#if 0
12208			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12209			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12210			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12211#endif
12212			/*
12213			 * XXX KDM we've got problems with FC, because it
12214			 * doesn't send down a tag type with aborts.  So we
12215			 * can only really go by the tag number...
12216			 * This may cause problems with parallel SCSI.
12217			 * Need to figure that out!!
12218			 */
12219			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12220				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12221				found = 1;
12222				if ((io->io_hdr.flags &
12223				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12224				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12225					union ctl_ha_msg msg_info;
12226
12227					io->io_hdr.flags |=
12228					                CTL_FLAG_SENT_2OTHER_SC;
12229					msg_info.hdr.nexus = io->io_hdr.nexus;
12230					msg_info.task.task_action =
12231						CTL_TASK_ABORT_TASK;
12232					msg_info.task.tag_num =
12233						io->taskio.tag_num;
12234					msg_info.task.tag_type =
12235						io->taskio.tag_type;
12236					msg_info.hdr.msg_type =
12237						CTL_MSG_MANAGE_TASKS;
12238					msg_info.hdr.original_sc = NULL;
12239					msg_info.hdr.serializing_sc = NULL;
12240#if 0
12241					printf("Sent Abort to other side\n");
12242#endif
12243					if (CTL_HA_STATUS_SUCCESS !=
12244					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12245		    				(void *)&msg_info,
12246						sizeof(msg_info), 0)) {
12247					}
12248				}
12249#if 0
12250				printf("ctl_abort_task: found I/O to abort\n");
12251#endif
12252				break;
12253			}
12254		}
12255	}
12256	mtx_unlock(&lun->lun_lock);
12257
12258	if (found == 0) {
12259		/*
12260		 * This isn't really an error.  It's entirely possible for
12261		 * the abort and command completion to cross on the wire.
12262		 * This is more of an informative/diagnostic error.
12263		 */
12264#if 0
12265		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12266		       "%d:%d:%d:%d tag %d type %d\n",
12267		       io->io_hdr.nexus.initid.id,
12268		       io->io_hdr.nexus.targ_port,
12269		       io->io_hdr.nexus.targ_target.id,
12270		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12271		       io->taskio.tag_type);
12272#endif
12273	}
12274	return (0);
12275}
12276
12277static void
12278ctl_run_task(union ctl_io *io)
12279{
12280	struct ctl_softc *ctl_softc = control_softc;
12281	int retval = 1;
12282	const char *task_desc;
12283
12284	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12285
12286	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12287	    ("ctl_run_task: Unextected io_type %d\n",
12288	     io->io_hdr.io_type));
12289
12290	task_desc = ctl_scsi_task_string(&io->taskio);
12291	if (task_desc != NULL) {
12292#ifdef NEEDTOPORT
12293		csevent_log(CSC_CTL | CSC_SHELF_SW |
12294			    CTL_TASK_REPORT,
12295			    csevent_LogType_Trace,
12296			    csevent_Severity_Information,
12297			    csevent_AlertLevel_Green,
12298			    csevent_FRU_Firmware,
12299			    csevent_FRU_Unknown,
12300			    "CTL: received task: %s",task_desc);
12301#endif
12302	} else {
12303#ifdef NEEDTOPORT
12304		csevent_log(CSC_CTL | CSC_SHELF_SW |
12305			    CTL_TASK_REPORT,
12306			    csevent_LogType_Trace,
12307			    csevent_Severity_Information,
12308			    csevent_AlertLevel_Green,
12309			    csevent_FRU_Firmware,
12310			    csevent_FRU_Unknown,
12311			    "CTL: received unknown task "
12312			    "type: %d (%#x)",
12313			    io->taskio.task_action,
12314			    io->taskio.task_action);
12315#endif
12316	}
12317	switch (io->taskio.task_action) {
12318	case CTL_TASK_ABORT_TASK:
12319		retval = ctl_abort_task(io);
12320		break;
12321	case CTL_TASK_ABORT_TASK_SET:
12322	case CTL_TASK_CLEAR_TASK_SET:
12323		retval = ctl_abort_task_set(io);
12324		break;
12325	case CTL_TASK_CLEAR_ACA:
12326		break;
12327	case CTL_TASK_I_T_NEXUS_RESET:
12328		retval = ctl_i_t_nexus_reset(io);
12329		break;
12330	case CTL_TASK_LUN_RESET: {
12331		struct ctl_lun *lun;
12332		uint32_t targ_lun;
12333
12334		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12335		mtx_lock(&ctl_softc->ctl_lock);
12336		if ((targ_lun < CTL_MAX_LUNS)
12337		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12338			lun = ctl_softc->ctl_luns[targ_lun];
12339		else {
12340			mtx_unlock(&ctl_softc->ctl_lock);
12341			retval = 1;
12342			break;
12343		}
12344
12345		if (!(io->io_hdr.flags &
12346		    CTL_FLAG_FROM_OTHER_SC)) {
12347			union ctl_ha_msg msg_info;
12348
12349			io->io_hdr.flags |=
12350				CTL_FLAG_SENT_2OTHER_SC;
12351			msg_info.hdr.msg_type =
12352				CTL_MSG_MANAGE_TASKS;
12353			msg_info.hdr.nexus = io->io_hdr.nexus;
12354			msg_info.task.task_action =
12355				CTL_TASK_LUN_RESET;
12356			msg_info.hdr.original_sc = NULL;
12357			msg_info.hdr.serializing_sc = NULL;
12358			if (CTL_HA_STATUS_SUCCESS !=
12359			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12360			    (void *)&msg_info,
12361			    sizeof(msg_info), 0)) {
12362			}
12363		}
12364
12365		retval = ctl_lun_reset(lun, io,
12366				       CTL_UA_LUN_RESET);
12367		mtx_unlock(&ctl_softc->ctl_lock);
12368		break;
12369	}
12370	case CTL_TASK_TARGET_RESET:
12371		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12372		break;
12373	case CTL_TASK_BUS_RESET:
12374		retval = ctl_bus_reset(ctl_softc, io);
12375		break;
12376	case CTL_TASK_PORT_LOGIN:
12377		break;
12378	case CTL_TASK_PORT_LOGOUT:
12379		break;
12380	default:
12381		printf("ctl_run_task: got unknown task management event %d\n",
12382		       io->taskio.task_action);
12383		break;
12384	}
12385	if (retval == 0)
12386		io->io_hdr.status = CTL_SUCCESS;
12387	else
12388		io->io_hdr.status = CTL_ERROR;
12389	ctl_done(io);
12390}
12391
12392/*
12393 * For HA operation.  Handle commands that come in from the other
12394 * controller.
12395 */
12396static void
12397ctl_handle_isc(union ctl_io *io)
12398{
12399	int free_io;
12400	struct ctl_lun *lun;
12401	struct ctl_softc *ctl_softc;
12402	uint32_t targ_lun;
12403
12404	ctl_softc = control_softc;
12405
12406	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12407	lun = ctl_softc->ctl_luns[targ_lun];
12408
12409	switch (io->io_hdr.msg_type) {
12410	case CTL_MSG_SERIALIZE:
12411		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12412		break;
12413	case CTL_MSG_R2R: {
12414		const struct ctl_cmd_entry *entry;
12415
12416		/*
12417		 * This is only used in SER_ONLY mode.
12418		 */
12419		free_io = 0;
12420		entry = ctl_get_cmd_entry(&io->scsiio);
12421		mtx_lock(&lun->lun_lock);
12422		if (ctl_scsiio_lun_check(ctl_softc, lun,
12423		    entry, (struct ctl_scsiio *)io) != 0) {
12424			mtx_unlock(&lun->lun_lock);
12425			ctl_done(io);
12426			break;
12427		}
12428		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12429		mtx_unlock(&lun->lun_lock);
12430		ctl_enqueue_rtr(io);
12431		break;
12432	}
12433	case CTL_MSG_FINISH_IO:
12434		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12435			free_io = 0;
12436			ctl_done(io);
12437		} else {
12438			free_io = 1;
12439			mtx_lock(&lun->lun_lock);
12440			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12441				     ooa_links);
12442			ctl_check_blocked(lun);
12443			mtx_unlock(&lun->lun_lock);
12444		}
12445		break;
12446	case CTL_MSG_PERS_ACTION:
12447		ctl_hndl_per_res_out_on_other_sc(
12448			(union ctl_ha_msg *)&io->presio.pr_msg);
12449		free_io = 1;
12450		break;
12451	case CTL_MSG_BAD_JUJU:
12452		free_io = 0;
12453		ctl_done(io);
12454		break;
12455	case CTL_MSG_DATAMOVE:
12456		/* Only used in XFER mode */
12457		free_io = 0;
12458		ctl_datamove_remote(io);
12459		break;
12460	case CTL_MSG_DATAMOVE_DONE:
12461		/* Only used in XFER mode */
12462		free_io = 0;
12463		io->scsiio.be_move_done(io);
12464		break;
12465	default:
12466		free_io = 1;
12467		printf("%s: Invalid message type %d\n",
12468		       __func__, io->io_hdr.msg_type);
12469		break;
12470	}
12471	if (free_io)
12472		ctl_free_io(io);
12473
12474}
12475
12476
12477/*
12478 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12479 * there is no match.
12480 */
12481static ctl_lun_error_pattern
12482ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12483{
12484	const struct ctl_cmd_entry *entry;
12485	ctl_lun_error_pattern filtered_pattern, pattern;
12486
12487	pattern = desc->error_pattern;
12488
12489	/*
12490	 * XXX KDM we need more data passed into this function to match a
12491	 * custom pattern, and we actually need to implement custom pattern
12492	 * matching.
12493	 */
12494	if (pattern & CTL_LUN_PAT_CMD)
12495		return (CTL_LUN_PAT_CMD);
12496
12497	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12498		return (CTL_LUN_PAT_ANY);
12499
12500	entry = ctl_get_cmd_entry(ctsio);
12501
12502	filtered_pattern = entry->pattern & pattern;
12503
12504	/*
12505	 * If the user requested specific flags in the pattern (e.g.
12506	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12507	 * flags.
12508	 *
12509	 * If the user did not specify any flags, it doesn't matter whether
12510	 * or not the command supports the flags.
12511	 */
12512	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12513	     (pattern & ~CTL_LUN_PAT_MASK))
12514		return (CTL_LUN_PAT_NONE);
12515
12516	/*
12517	 * If the user asked for a range check, see if the requested LBA
12518	 * range overlaps with this command's LBA range.
12519	 */
12520	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12521		uint64_t lba1;
12522		uint32_t len1;
12523		ctl_action action;
12524		int retval;
12525
12526		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12527		if (retval != 0)
12528			return (CTL_LUN_PAT_NONE);
12529
12530		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12531					      desc->lba_range.len);
12532		/*
12533		 * A "pass" means that the LBA ranges don't overlap, so
12534		 * this doesn't match the user's range criteria.
12535		 */
12536		if (action == CTL_ACTION_PASS)
12537			return (CTL_LUN_PAT_NONE);
12538	}
12539
12540	return (filtered_pattern);
12541}
12542
12543static void
12544ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12545{
12546	struct ctl_error_desc *desc, *desc2;
12547
12548	mtx_assert(&lun->lun_lock, MA_OWNED);
12549
12550	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12551		ctl_lun_error_pattern pattern;
12552		/*
12553		 * Check to see whether this particular command matches
12554		 * the pattern in the descriptor.
12555		 */
12556		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12557		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12558			continue;
12559
12560		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12561		case CTL_LUN_INJ_ABORTED:
12562			ctl_set_aborted(&io->scsiio);
12563			break;
12564		case CTL_LUN_INJ_MEDIUM_ERR:
12565			ctl_set_medium_error(&io->scsiio);
12566			break;
12567		case CTL_LUN_INJ_UA:
12568			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12569			 * OCCURRED */
12570			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12571			break;
12572		case CTL_LUN_INJ_CUSTOM:
12573			/*
12574			 * We're assuming the user knows what he is doing.
12575			 * Just copy the sense information without doing
12576			 * checks.
12577			 */
12578			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12579			      ctl_min(sizeof(desc->custom_sense),
12580				      sizeof(io->scsiio.sense_data)));
12581			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12582			io->scsiio.sense_len = SSD_FULL_SIZE;
12583			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12584			break;
12585		case CTL_LUN_INJ_NONE:
12586		default:
12587			/*
12588			 * If this is an error injection type we don't know
12589			 * about, clear the continuous flag (if it is set)
12590			 * so it will get deleted below.
12591			 */
12592			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12593			break;
12594		}
12595		/*
12596		 * By default, each error injection action is a one-shot
12597		 */
12598		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12599			continue;
12600
12601		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12602
12603		free(desc, M_CTL);
12604	}
12605}
12606
12607#ifdef CTL_IO_DELAY
12608static void
12609ctl_datamove_timer_wakeup(void *arg)
12610{
12611	union ctl_io *io;
12612
12613	io = (union ctl_io *)arg;
12614
12615	ctl_datamove(io);
12616}
12617#endif /* CTL_IO_DELAY */
12618
12619void
12620ctl_datamove(union ctl_io *io)
12621{
12622	void (*fe_datamove)(union ctl_io *io);
12623
12624	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12625
12626	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12627
12628#ifdef CTL_TIME_IO
12629	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12630		char str[256];
12631		char path_str[64];
12632		struct sbuf sb;
12633
12634		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12635		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12636
12637		sbuf_cat(&sb, path_str);
12638		switch (io->io_hdr.io_type) {
12639		case CTL_IO_SCSI:
12640			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12641			sbuf_printf(&sb, "\n");
12642			sbuf_cat(&sb, path_str);
12643			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12644				    io->scsiio.tag_num, io->scsiio.tag_type);
12645			break;
12646		case CTL_IO_TASK:
12647			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12648				    "Tag Type: %d\n", io->taskio.task_action,
12649				    io->taskio.tag_num, io->taskio.tag_type);
12650			break;
12651		default:
12652			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12653			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12654			break;
12655		}
12656		sbuf_cat(&sb, path_str);
12657		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12658			    (intmax_t)time_uptime - io->io_hdr.start_time);
12659		sbuf_finish(&sb);
12660		printf("%s", sbuf_data(&sb));
12661	}
12662#endif /* CTL_TIME_IO */
12663
12664#ifdef CTL_IO_DELAY
12665	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12666		struct ctl_lun *lun;
12667
12668		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12669
12670		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12671	} else {
12672		struct ctl_lun *lun;
12673
12674		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12675		if ((lun != NULL)
12676		 && (lun->delay_info.datamove_delay > 0)) {
12677			struct callout *callout;
12678
12679			callout = (struct callout *)&io->io_hdr.timer_bytes;
12680			callout_init(callout, /*mpsafe*/ 1);
12681			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12682			callout_reset(callout,
12683				      lun->delay_info.datamove_delay * hz,
12684				      ctl_datamove_timer_wakeup, io);
12685			if (lun->delay_info.datamove_type ==
12686			    CTL_DELAY_TYPE_ONESHOT)
12687				lun->delay_info.datamove_delay = 0;
12688			return;
12689		}
12690	}
12691#endif
12692
12693	/*
12694	 * This command has been aborted.  Set the port status, so we fail
12695	 * the data move.
12696	 */
12697	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12698		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12699		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12700		       io->io_hdr.nexus.targ_port,
12701		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12702		       io->io_hdr.nexus.targ_lun);
12703		io->io_hdr.port_status = 31337;
12704		/*
12705		 * Note that the backend, in this case, will get the
12706		 * callback in its context.  In other cases it may get
12707		 * called in the frontend's interrupt thread context.
12708		 */
12709		io->scsiio.be_move_done(io);
12710		return;
12711	}
12712
12713	/*
12714	 * If we're in XFER mode and this I/O is from the other shelf
12715	 * controller, we need to send the DMA to the other side to
12716	 * actually transfer the data to/from the host.  In serialize only
12717	 * mode the transfer happens below CTL and ctl_datamove() is only
12718	 * called on the machine that originally received the I/O.
12719	 */
12720	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12721	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12722		union ctl_ha_msg msg;
12723		uint32_t sg_entries_sent;
12724		int do_sg_copy;
12725		int i;
12726
12727		memset(&msg, 0, sizeof(msg));
12728		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12729		msg.hdr.original_sc = io->io_hdr.original_sc;
12730		msg.hdr.serializing_sc = io;
12731		msg.hdr.nexus = io->io_hdr.nexus;
12732		msg.dt.flags = io->io_hdr.flags;
12733		/*
12734		 * We convert everything into a S/G list here.  We can't
12735		 * pass by reference, only by value between controllers.
12736		 * So we can't pass a pointer to the S/G list, only as many
12737		 * S/G entries as we can fit in here.  If it's possible for
12738		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12739		 * then we need to break this up into multiple transfers.
12740		 */
12741		if (io->scsiio.kern_sg_entries == 0) {
12742			msg.dt.kern_sg_entries = 1;
12743			/*
12744			 * If this is in cached memory, flush the cache
12745			 * before we send the DMA request to the other
12746			 * controller.  We want to do this in either the
12747			 * read or the write case.  The read case is
12748			 * straightforward.  In the write case, we want to
12749			 * make sure nothing is in the local cache that
12750			 * could overwrite the DMAed data.
12751			 */
12752			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12753				/*
12754				 * XXX KDM use bus_dmamap_sync() here.
12755				 */
12756			}
12757
12758			/*
12759			 * Convert to a physical address if this is a
12760			 * virtual address.
12761			 */
12762			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12763				msg.dt.sg_list[0].addr =
12764					io->scsiio.kern_data_ptr;
12765			} else {
12766				/*
12767				 * XXX KDM use busdma here!
12768				 */
12769#if 0
12770				msg.dt.sg_list[0].addr = (void *)
12771					vtophys(io->scsiio.kern_data_ptr);
12772#endif
12773			}
12774
12775			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12776			do_sg_copy = 0;
12777		} else {
12778			struct ctl_sg_entry *sgl;
12779
12780			do_sg_copy = 1;
12781			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12782			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12783			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12784				/*
12785				 * XXX KDM use bus_dmamap_sync() here.
12786				 */
12787			}
12788		}
12789
12790		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12791		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12792		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12793		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12794		msg.dt.sg_sequence = 0;
12795
12796		/*
12797		 * Loop until we've sent all of the S/G entries.  On the
12798		 * other end, we'll recompose these S/G entries into one
12799		 * contiguous list before passing it to the
12800		 */
12801		for (sg_entries_sent = 0; sg_entries_sent <
12802		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12803			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12804				sizeof(msg.dt.sg_list[0])),
12805				msg.dt.kern_sg_entries - sg_entries_sent);
12806
12807			if (do_sg_copy != 0) {
12808				struct ctl_sg_entry *sgl;
12809				int j;
12810
12811				sgl = (struct ctl_sg_entry *)
12812					io->scsiio.kern_data_ptr;
12813				/*
12814				 * If this is in cached memory, flush the cache
12815				 * before we send the DMA request to the other
12816				 * controller.  We want to do this in either
12817				 * the * read or the write case.  The read
12818				 * case is straightforward.  In the write
12819				 * case, we want to make sure nothing is
12820				 * in the local cache that could overwrite
12821				 * the DMAed data.
12822				 */
12823
12824				for (i = sg_entries_sent, j = 0;
12825				     i < msg.dt.cur_sg_entries; i++, j++) {
12826					if ((io->io_hdr.flags &
12827					     CTL_FLAG_NO_DATASYNC) == 0) {
12828						/*
12829						 * XXX KDM use bus_dmamap_sync()
12830						 */
12831					}
12832					if ((io->io_hdr.flags &
12833					     CTL_FLAG_BUS_ADDR) == 0) {
12834						/*
12835						 * XXX KDM use busdma.
12836						 */
12837#if 0
12838						msg.dt.sg_list[j].addr =(void *)
12839						       vtophys(sgl[i].addr);
12840#endif
12841					} else {
12842						msg.dt.sg_list[j].addr =
12843							sgl[i].addr;
12844					}
12845					msg.dt.sg_list[j].len = sgl[i].len;
12846				}
12847			}
12848
12849			sg_entries_sent += msg.dt.cur_sg_entries;
12850			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12851				msg.dt.sg_last = 1;
12852			else
12853				msg.dt.sg_last = 0;
12854
12855			/*
12856			 * XXX KDM drop and reacquire the lock here?
12857			 */
12858			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12859			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12860				/*
12861				 * XXX do something here.
12862				 */
12863			}
12864
12865			msg.dt.sent_sg_entries = sg_entries_sent;
12866		}
12867		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12868		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12869			ctl_failover_io(io, /*have_lock*/ 0);
12870
12871	} else {
12872
12873		/*
12874		 * Lookup the fe_datamove() function for this particular
12875		 * front end.
12876		 */
12877		fe_datamove =
12878		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12879
12880		fe_datamove(io);
12881	}
12882}
12883
12884static void
12885ctl_send_datamove_done(union ctl_io *io, int have_lock)
12886{
12887	union ctl_ha_msg msg;
12888	int isc_status;
12889
12890	memset(&msg, 0, sizeof(msg));
12891
12892	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12893	msg.hdr.original_sc = io;
12894	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12895	msg.hdr.nexus = io->io_hdr.nexus;
12896	msg.hdr.status = io->io_hdr.status;
12897	msg.scsi.tag_num = io->scsiio.tag_num;
12898	msg.scsi.tag_type = io->scsiio.tag_type;
12899	msg.scsi.scsi_status = io->scsiio.scsi_status;
12900	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12901	       sizeof(io->scsiio.sense_data));
12902	msg.scsi.sense_len = io->scsiio.sense_len;
12903	msg.scsi.sense_residual = io->scsiio.sense_residual;
12904	msg.scsi.fetd_status = io->io_hdr.port_status;
12905	msg.scsi.residual = io->scsiio.residual;
12906	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12907
12908	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12909		ctl_failover_io(io, /*have_lock*/ have_lock);
12910		return;
12911	}
12912
12913	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12914	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12915		/* XXX do something if this fails */
12916	}
12917
12918}
12919
12920/*
12921 * The DMA to the remote side is done, now we need to tell the other side
12922 * we're done so it can continue with its data movement.
12923 */
12924static void
12925ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12926{
12927	union ctl_io *io;
12928
12929	io = rq->context;
12930
12931	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12932		printf("%s: ISC DMA write failed with error %d", __func__,
12933		       rq->ret);
12934		ctl_set_internal_failure(&io->scsiio,
12935					 /*sks_valid*/ 1,
12936					 /*retry_count*/ rq->ret);
12937	}
12938
12939	ctl_dt_req_free(rq);
12940
12941	/*
12942	 * In this case, we had to malloc the memory locally.  Free it.
12943	 */
12944	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12945		int i;
12946		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12947			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12948	}
12949	/*
12950	 * The data is in local and remote memory, so now we need to send
12951	 * status (good or back) back to the other side.
12952	 */
12953	ctl_send_datamove_done(io, /*have_lock*/ 0);
12954}
12955
12956/*
12957 * We've moved the data from the host/controller into local memory.  Now we
12958 * need to push it over to the remote controller's memory.
12959 */
12960static int
12961ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12962{
12963	int retval;
12964
12965	retval = 0;
12966
12967	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12968					  ctl_datamove_remote_write_cb);
12969
12970	return (retval);
12971}
12972
12973static void
12974ctl_datamove_remote_write(union ctl_io *io)
12975{
12976	int retval;
12977	void (*fe_datamove)(union ctl_io *io);
12978
12979	/*
12980	 * - Get the data from the host/HBA into local memory.
12981	 * - DMA memory from the local controller to the remote controller.
12982	 * - Send status back to the remote controller.
12983	 */
12984
12985	retval = ctl_datamove_remote_sgl_setup(io);
12986	if (retval != 0)
12987		return;
12988
12989	/* Switch the pointer over so the FETD knows what to do */
12990	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12991
12992	/*
12993	 * Use a custom move done callback, since we need to send completion
12994	 * back to the other controller, not to the backend on this side.
12995	 */
12996	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12997
12998	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12999
13000	fe_datamove(io);
13001
13002	return;
13003
13004}
13005
13006static int
13007ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13008{
13009#if 0
13010	char str[256];
13011	char path_str[64];
13012	struct sbuf sb;
13013#endif
13014
13015	/*
13016	 * In this case, we had to malloc the memory locally.  Free it.
13017	 */
13018	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13019		int i;
13020		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13021			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13022	}
13023
13024#if 0
13025	scsi_path_string(io, path_str, sizeof(path_str));
13026	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13027	sbuf_cat(&sb, path_str);
13028	scsi_command_string(&io->scsiio, NULL, &sb);
13029	sbuf_printf(&sb, "\n");
13030	sbuf_cat(&sb, path_str);
13031	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13032		    io->scsiio.tag_num, io->scsiio.tag_type);
13033	sbuf_cat(&sb, path_str);
13034	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13035		    io->io_hdr.flags, io->io_hdr.status);
13036	sbuf_finish(&sb);
13037	printk("%s", sbuf_data(&sb));
13038#endif
13039
13040
13041	/*
13042	 * The read is done, now we need to send status (good or bad) back
13043	 * to the other side.
13044	 */
13045	ctl_send_datamove_done(io, /*have_lock*/ 0);
13046
13047	return (0);
13048}
13049
13050static void
13051ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13052{
13053	union ctl_io *io;
13054	void (*fe_datamove)(union ctl_io *io);
13055
13056	io = rq->context;
13057
13058	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13059		printf("%s: ISC DMA read failed with error %d", __func__,
13060		       rq->ret);
13061		ctl_set_internal_failure(&io->scsiio,
13062					 /*sks_valid*/ 1,
13063					 /*retry_count*/ rq->ret);
13064	}
13065
13066	ctl_dt_req_free(rq);
13067
13068	/* Switch the pointer over so the FETD knows what to do */
13069	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13070
13071	/*
13072	 * Use a custom move done callback, since we need to send completion
13073	 * back to the other controller, not to the backend on this side.
13074	 */
13075	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13076
13077	/* XXX KDM add checks like the ones in ctl_datamove? */
13078
13079	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13080
13081	fe_datamove(io);
13082}
13083
13084static int
13085ctl_datamove_remote_sgl_setup(union ctl_io *io)
13086{
13087	struct ctl_sg_entry *local_sglist, *remote_sglist;
13088	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13089	struct ctl_softc *softc;
13090	int retval;
13091	int i;
13092
13093	retval = 0;
13094	softc = control_softc;
13095
13096	local_sglist = io->io_hdr.local_sglist;
13097	local_dma_sglist = io->io_hdr.local_dma_sglist;
13098	remote_sglist = io->io_hdr.remote_sglist;
13099	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13100
13101	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13102		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13103			local_sglist[i].len = remote_sglist[i].len;
13104
13105			/*
13106			 * XXX Detect the situation where the RS-level I/O
13107			 * redirector on the other side has already read the
13108			 * data off of the AOR RS on this side, and
13109			 * transferred it to remote (mirror) memory on the
13110			 * other side.  Since we already have the data in
13111			 * memory here, we just need to use it.
13112			 *
13113			 * XXX KDM this can probably be removed once we
13114			 * get the cache device code in and take the
13115			 * current AOR implementation out.
13116			 */
13117#ifdef NEEDTOPORT
13118			if ((remote_sglist[i].addr >=
13119			     (void *)vtophys(softc->mirr->addr))
13120			 && (remote_sglist[i].addr <
13121			     ((void *)vtophys(softc->mirr->addr) +
13122			     CacheMirrorOffset))) {
13123				local_sglist[i].addr = remote_sglist[i].addr -
13124					CacheMirrorOffset;
13125				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13126				     CTL_FLAG_DATA_IN)
13127					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13128			} else {
13129				local_sglist[i].addr = remote_sglist[i].addr +
13130					CacheMirrorOffset;
13131			}
13132#endif
13133#if 0
13134			printf("%s: local %p, remote %p, len %d\n",
13135			       __func__, local_sglist[i].addr,
13136			       remote_sglist[i].addr, local_sglist[i].len);
13137#endif
13138		}
13139	} else {
13140		uint32_t len_to_go;
13141
13142		/*
13143		 * In this case, we don't have automatically allocated
13144		 * memory for this I/O on this controller.  This typically
13145		 * happens with internal CTL I/O -- e.g. inquiry, mode
13146		 * sense, etc.  Anything coming from RAIDCore will have
13147		 * a mirror area available.
13148		 */
13149		len_to_go = io->scsiio.kern_data_len;
13150
13151		/*
13152		 * Clear the no datasync flag, we have to use malloced
13153		 * buffers.
13154		 */
13155		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13156
13157		/*
13158		 * The difficult thing here is that the size of the various
13159		 * S/G segments may be different than the size from the
13160		 * remote controller.  That'll make it harder when DMAing
13161		 * the data back to the other side.
13162		 */
13163		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13164		     sizeof(io->io_hdr.remote_sglist[0])) &&
13165		     (len_to_go > 0); i++) {
13166			local_sglist[i].len = ctl_min(len_to_go, 131072);
13167			CTL_SIZE_8B(local_dma_sglist[i].len,
13168				    local_sglist[i].len);
13169			local_sglist[i].addr =
13170				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13171
13172			local_dma_sglist[i].addr = local_sglist[i].addr;
13173
13174			if (local_sglist[i].addr == NULL) {
13175				int j;
13176
13177				printf("malloc failed for %zd bytes!",
13178				       local_dma_sglist[i].len);
13179				for (j = 0; j < i; j++) {
13180					free(local_sglist[j].addr, M_CTL);
13181				}
13182				ctl_set_internal_failure(&io->scsiio,
13183							 /*sks_valid*/ 1,
13184							 /*retry_count*/ 4857);
13185				retval = 1;
13186				goto bailout_error;
13187
13188			}
13189			/* XXX KDM do we need a sync here? */
13190
13191			len_to_go -= local_sglist[i].len;
13192		}
13193		/*
13194		 * Reset the number of S/G entries accordingly.  The
13195		 * original number of S/G entries is available in
13196		 * rem_sg_entries.
13197		 */
13198		io->scsiio.kern_sg_entries = i;
13199
13200#if 0
13201		printf("%s: kern_sg_entries = %d\n", __func__,
13202		       io->scsiio.kern_sg_entries);
13203		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13204			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13205			       local_sglist[i].addr, local_sglist[i].len,
13206			       local_dma_sglist[i].len);
13207#endif
13208	}
13209
13210
13211	return (retval);
13212
13213bailout_error:
13214
13215	ctl_send_datamove_done(io, /*have_lock*/ 0);
13216
13217	return (retval);
13218}
13219
13220static int
13221ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13222			 ctl_ha_dt_cb callback)
13223{
13224	struct ctl_ha_dt_req *rq;
13225	struct ctl_sg_entry *remote_sglist, *local_sglist;
13226	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13227	uint32_t local_used, remote_used, total_used;
13228	int retval;
13229	int i, j;
13230
13231	retval = 0;
13232
13233	rq = ctl_dt_req_alloc();
13234
13235	/*
13236	 * If we failed to allocate the request, and if the DMA didn't fail
13237	 * anyway, set busy status.  This is just a resource allocation
13238	 * failure.
13239	 */
13240	if ((rq == NULL)
13241	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13242		ctl_set_busy(&io->scsiio);
13243
13244	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13245
13246		if (rq != NULL)
13247			ctl_dt_req_free(rq);
13248
13249		/*
13250		 * The data move failed.  We need to return status back
13251		 * to the other controller.  No point in trying to DMA
13252		 * data to the remote controller.
13253		 */
13254
13255		ctl_send_datamove_done(io, /*have_lock*/ 0);
13256
13257		retval = 1;
13258
13259		goto bailout;
13260	}
13261
13262	local_sglist = io->io_hdr.local_sglist;
13263	local_dma_sglist = io->io_hdr.local_dma_sglist;
13264	remote_sglist = io->io_hdr.remote_sglist;
13265	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13266	local_used = 0;
13267	remote_used = 0;
13268	total_used = 0;
13269
13270	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13271		rq->ret = CTL_HA_STATUS_SUCCESS;
13272		rq->context = io;
13273		callback(rq);
13274		goto bailout;
13275	}
13276
13277	/*
13278	 * Pull/push the data over the wire from/to the other controller.
13279	 * This takes into account the possibility that the local and
13280	 * remote sglists may not be identical in terms of the size of
13281	 * the elements and the number of elements.
13282	 *
13283	 * One fundamental assumption here is that the length allocated for
13284	 * both the local and remote sglists is identical.  Otherwise, we've
13285	 * essentially got a coding error of some sort.
13286	 */
13287	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13288		int isc_ret;
13289		uint32_t cur_len, dma_length;
13290		uint8_t *tmp_ptr;
13291
13292		rq->id = CTL_HA_DATA_CTL;
13293		rq->command = command;
13294		rq->context = io;
13295
13296		/*
13297		 * Both pointers should be aligned.  But it is possible
13298		 * that the allocation length is not.  They should both
13299		 * also have enough slack left over at the end, though,
13300		 * to round up to the next 8 byte boundary.
13301		 */
13302		cur_len = ctl_min(local_sglist[i].len - local_used,
13303				  remote_sglist[j].len - remote_used);
13304
13305		/*
13306		 * In this case, we have a size issue and need to decrease
13307		 * the size, except in the case where we actually have less
13308		 * than 8 bytes left.  In that case, we need to increase
13309		 * the DMA length to get the last bit.
13310		 */
13311		if ((cur_len & 0x7) != 0) {
13312			if (cur_len > 0x7) {
13313				cur_len = cur_len - (cur_len & 0x7);
13314				dma_length = cur_len;
13315			} else {
13316				CTL_SIZE_8B(dma_length, cur_len);
13317			}
13318
13319		} else
13320			dma_length = cur_len;
13321
13322		/*
13323		 * If we had to allocate memory for this I/O, instead of using
13324		 * the non-cached mirror memory, we'll need to flush the cache
13325		 * before trying to DMA to the other controller.
13326		 *
13327		 * We could end up doing this multiple times for the same
13328		 * segment if we have a larger local segment than remote
13329		 * segment.  That shouldn't be an issue.
13330		 */
13331		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13332			/*
13333			 * XXX KDM use bus_dmamap_sync() here.
13334			 */
13335		}
13336
13337		rq->size = dma_length;
13338
13339		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13340		tmp_ptr += local_used;
13341
13342		/* Use physical addresses when talking to ISC hardware */
13343		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13344			/* XXX KDM use busdma */
13345#if 0
13346			rq->local = vtophys(tmp_ptr);
13347#endif
13348		} else
13349			rq->local = tmp_ptr;
13350
13351		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13352		tmp_ptr += remote_used;
13353		rq->remote = tmp_ptr;
13354
13355		rq->callback = NULL;
13356
13357		local_used += cur_len;
13358		if (local_used >= local_sglist[i].len) {
13359			i++;
13360			local_used = 0;
13361		}
13362
13363		remote_used += cur_len;
13364		if (remote_used >= remote_sglist[j].len) {
13365			j++;
13366			remote_used = 0;
13367		}
13368		total_used += cur_len;
13369
13370		if (total_used >= io->scsiio.kern_data_len)
13371			rq->callback = callback;
13372
13373		if ((rq->size & 0x7) != 0) {
13374			printf("%s: warning: size %d is not on 8b boundary\n",
13375			       __func__, rq->size);
13376		}
13377		if (((uintptr_t)rq->local & 0x7) != 0) {
13378			printf("%s: warning: local %p not on 8b boundary\n",
13379			       __func__, rq->local);
13380		}
13381		if (((uintptr_t)rq->remote & 0x7) != 0) {
13382			printf("%s: warning: remote %p not on 8b boundary\n",
13383			       __func__, rq->local);
13384		}
13385#if 0
13386		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13387		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13388		       rq->local, rq->remote, rq->size);
13389#endif
13390
13391		isc_ret = ctl_dt_single(rq);
13392		if (isc_ret == CTL_HA_STATUS_WAIT)
13393			continue;
13394
13395		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13396			rq->ret = CTL_HA_STATUS_SUCCESS;
13397		} else {
13398			rq->ret = isc_ret;
13399		}
13400		callback(rq);
13401		goto bailout;
13402	}
13403
13404bailout:
13405	return (retval);
13406
13407}
13408
13409static void
13410ctl_datamove_remote_read(union ctl_io *io)
13411{
13412	int retval;
13413	int i;
13414
13415	/*
13416	 * This will send an error to the other controller in the case of a
13417	 * failure.
13418	 */
13419	retval = ctl_datamove_remote_sgl_setup(io);
13420	if (retval != 0)
13421		return;
13422
13423	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13424					  ctl_datamove_remote_read_cb);
13425	if ((retval != 0)
13426	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13427		/*
13428		 * Make sure we free memory if there was an error..  The
13429		 * ctl_datamove_remote_xfer() function will send the
13430		 * datamove done message, or call the callback with an
13431		 * error if there is a problem.
13432		 */
13433		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13434			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13435	}
13436
13437	return;
13438}
13439
13440/*
13441 * Process a datamove request from the other controller.  This is used for
13442 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13443 * first.  Once that is complete, the data gets DMAed into the remote
13444 * controller's memory.  For reads, we DMA from the remote controller's
13445 * memory into our memory first, and then move it out to the FETD.
13446 */
13447static void
13448ctl_datamove_remote(union ctl_io *io)
13449{
13450	struct ctl_softc *softc;
13451
13452	softc = control_softc;
13453
13454	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13455
13456	/*
13457	 * Note that we look for an aborted I/O here, but don't do some of
13458	 * the other checks that ctl_datamove() normally does.
13459	 * We don't need to run the datamove delay code, since that should
13460	 * have been done if need be on the other controller.
13461	 */
13462	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13463		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13464		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13465		       io->io_hdr.nexus.targ_port,
13466		       io->io_hdr.nexus.targ_target.id,
13467		       io->io_hdr.nexus.targ_lun);
13468		io->io_hdr.port_status = 31338;
13469		ctl_send_datamove_done(io, /*have_lock*/ 0);
13470		return;
13471	}
13472
13473	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13474		ctl_datamove_remote_write(io);
13475	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13476		ctl_datamove_remote_read(io);
13477	} else {
13478		union ctl_ha_msg msg;
13479		struct scsi_sense_data *sense;
13480		uint8_t sks[3];
13481		int retry_count;
13482
13483		memset(&msg, 0, sizeof(msg));
13484
13485		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13486		msg.hdr.status = CTL_SCSI_ERROR;
13487		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13488
13489		retry_count = 4243;
13490
13491		sense = &msg.scsi.sense_data;
13492		sks[0] = SSD_SCS_VALID;
13493		sks[1] = (retry_count >> 8) & 0xff;
13494		sks[2] = retry_count & 0xff;
13495
13496		/* "Internal target failure" */
13497		scsi_set_sense_data(sense,
13498				    /*sense_format*/ SSD_TYPE_NONE,
13499				    /*current_error*/ 1,
13500				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13501				    /*asc*/ 0x44,
13502				    /*ascq*/ 0x00,
13503				    /*type*/ SSD_ELEM_SKS,
13504				    /*size*/ sizeof(sks),
13505				    /*data*/ sks,
13506				    SSD_ELEM_NONE);
13507
13508		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13509		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13510			ctl_failover_io(io, /*have_lock*/ 1);
13511			return;
13512		}
13513
13514		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13515		    CTL_HA_STATUS_SUCCESS) {
13516			/* XXX KDM what to do if this fails? */
13517		}
13518		return;
13519	}
13520
13521}
13522
13523static int
13524ctl_process_done(union ctl_io *io)
13525{
13526	struct ctl_lun *lun;
13527	struct ctl_softc *ctl_softc;
13528	void (*fe_done)(union ctl_io *io);
13529	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13530
13531	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13532
13533	fe_done =
13534	    control_softc->ctl_ports[targ_port]->fe_done;
13535
13536#ifdef CTL_TIME_IO
13537	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13538		char str[256];
13539		char path_str[64];
13540		struct sbuf sb;
13541
13542		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13543		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13544
13545		sbuf_cat(&sb, path_str);
13546		switch (io->io_hdr.io_type) {
13547		case CTL_IO_SCSI:
13548			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13549			sbuf_printf(&sb, "\n");
13550			sbuf_cat(&sb, path_str);
13551			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13552				    io->scsiio.tag_num, io->scsiio.tag_type);
13553			break;
13554		case CTL_IO_TASK:
13555			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13556				    "Tag Type: %d\n", io->taskio.task_action,
13557				    io->taskio.tag_num, io->taskio.tag_type);
13558			break;
13559		default:
13560			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13561			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13562			break;
13563		}
13564		sbuf_cat(&sb, path_str);
13565		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13566			    (intmax_t)time_uptime - io->io_hdr.start_time);
13567		sbuf_finish(&sb);
13568		printf("%s", sbuf_data(&sb));
13569	}
13570#endif /* CTL_TIME_IO */
13571
13572	switch (io->io_hdr.io_type) {
13573	case CTL_IO_SCSI:
13574		break;
13575	case CTL_IO_TASK:
13576		if (bootverbose || verbose > 0)
13577			ctl_io_error_print(io, NULL);
13578		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13579			ctl_free_io(io);
13580		else
13581			fe_done(io);
13582		return (CTL_RETVAL_COMPLETE);
13583		break;
13584	default:
13585		printf("ctl_process_done: invalid io type %d\n",
13586		       io->io_hdr.io_type);
13587		panic("ctl_process_done: invalid io type %d\n",
13588		      io->io_hdr.io_type);
13589		break; /* NOTREACHED */
13590	}
13591
13592	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13593	if (lun == NULL) {
13594		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13595				 io->io_hdr.nexus.targ_mapped_lun));
13596		fe_done(io);
13597		goto bailout;
13598	}
13599	ctl_softc = lun->ctl_softc;
13600
13601	mtx_lock(&lun->lun_lock);
13602
13603	/*
13604	 * Check to see if we have any errors to inject here.  We only
13605	 * inject errors for commands that don't already have errors set.
13606	 */
13607	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13608	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13609		ctl_inject_error(lun, io);
13610
13611	/*
13612	 * XXX KDM how do we treat commands that aren't completed
13613	 * successfully?
13614	 *
13615	 * XXX KDM should we also track I/O latency?
13616	 */
13617	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13618	    io->io_hdr.io_type == CTL_IO_SCSI) {
13619#ifdef CTL_TIME_IO
13620		struct bintime cur_bt;
13621#endif
13622		int type;
13623
13624		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13625		    CTL_FLAG_DATA_IN)
13626			type = CTL_STATS_READ;
13627		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13628		    CTL_FLAG_DATA_OUT)
13629			type = CTL_STATS_WRITE;
13630		else
13631			type = CTL_STATS_NO_IO;
13632
13633		lun->stats.ports[targ_port].bytes[type] +=
13634		    io->scsiio.kern_total_len;
13635		lun->stats.ports[targ_port].operations[type]++;
13636#ifdef CTL_TIME_IO
13637		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13638		   &io->io_hdr.dma_bt);
13639		lun->stats.ports[targ_port].num_dmas[type] +=
13640		    io->io_hdr.num_dmas;
13641		getbintime(&cur_bt);
13642		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13643		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13644#endif
13645	}
13646
13647	/*
13648	 * Remove this from the OOA queue.
13649	 */
13650	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13651
13652	/*
13653	 * Run through the blocked queue on this LUN and see if anything
13654	 * has become unblocked, now that this transaction is done.
13655	 */
13656	ctl_check_blocked(lun);
13657
13658	/*
13659	 * If the LUN has been invalidated, free it if there is nothing
13660	 * left on its OOA queue.
13661	 */
13662	if ((lun->flags & CTL_LUN_INVALID)
13663	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13664		mtx_unlock(&lun->lun_lock);
13665		mtx_lock(&ctl_softc->ctl_lock);
13666		ctl_free_lun(lun);
13667		mtx_unlock(&ctl_softc->ctl_lock);
13668	} else
13669		mtx_unlock(&lun->lun_lock);
13670
13671	/*
13672	 * If this command has been aborted, make sure we set the status
13673	 * properly.  The FETD is responsible for freeing the I/O and doing
13674	 * whatever it needs to do to clean up its state.
13675	 */
13676	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13677		ctl_set_task_aborted(&io->scsiio);
13678
13679	/*
13680	 * We print out status for every task management command.  For SCSI
13681	 * commands, we filter out any unit attention errors; they happen
13682	 * on every boot, and would clutter up the log.  Note:  task
13683	 * management commands aren't printed here, they are printed above,
13684	 * since they should never even make it down here.
13685	 */
13686	switch (io->io_hdr.io_type) {
13687	case CTL_IO_SCSI: {
13688		int error_code, sense_key, asc, ascq;
13689
13690		sense_key = 0;
13691
13692		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13693		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13694			/*
13695			 * Since this is just for printing, no need to
13696			 * show errors here.
13697			 */
13698			scsi_extract_sense_len(&io->scsiio.sense_data,
13699					       io->scsiio.sense_len,
13700					       &error_code,
13701					       &sense_key,
13702					       &asc,
13703					       &ascq,
13704					       /*show_errors*/ 0);
13705		}
13706
13707		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13708		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13709		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13710		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13711
13712			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13713				ctl_softc->skipped_prints++;
13714			} else {
13715				uint32_t skipped_prints;
13716
13717				skipped_prints = ctl_softc->skipped_prints;
13718
13719				ctl_softc->skipped_prints = 0;
13720				ctl_softc->last_print_jiffies = time_uptime;
13721
13722				if (skipped_prints > 0) {
13723#ifdef NEEDTOPORT
13724					csevent_log(CSC_CTL | CSC_SHELF_SW |
13725					    CTL_ERROR_REPORT,
13726					    csevent_LogType_Trace,
13727					    csevent_Severity_Information,
13728					    csevent_AlertLevel_Green,
13729					    csevent_FRU_Firmware,
13730					    csevent_FRU_Unknown,
13731					    "High CTL error volume, %d prints "
13732					    "skipped", skipped_prints);
13733#endif
13734				}
13735				if (bootverbose || verbose > 0)
13736					ctl_io_error_print(io, NULL);
13737			}
13738		}
13739		break;
13740	}
13741	case CTL_IO_TASK:
13742		if (bootverbose || verbose > 0)
13743			ctl_io_error_print(io, NULL);
13744		break;
13745	default:
13746		break;
13747	}
13748
13749	/*
13750	 * Tell the FETD or the other shelf controller we're done with this
13751	 * command.  Note that only SCSI commands get to this point.  Task
13752	 * management commands are completed above.
13753	 *
13754	 * We only send status to the other controller if we're in XFER
13755	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13756	 * received the I/O (from CTL's perspective), and so the status is
13757	 * generated there.
13758	 *
13759	 * XXX KDM if we hold the lock here, we could cause a deadlock
13760	 * if the frontend comes back in in this context to queue
13761	 * something.
13762	 */
13763	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13764	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13765		union ctl_ha_msg msg;
13766
13767		memset(&msg, 0, sizeof(msg));
13768		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13769		msg.hdr.original_sc = io->io_hdr.original_sc;
13770		msg.hdr.nexus = io->io_hdr.nexus;
13771		msg.hdr.status = io->io_hdr.status;
13772		msg.scsi.scsi_status = io->scsiio.scsi_status;
13773		msg.scsi.tag_num = io->scsiio.tag_num;
13774		msg.scsi.tag_type = io->scsiio.tag_type;
13775		msg.scsi.sense_len = io->scsiio.sense_len;
13776		msg.scsi.sense_residual = io->scsiio.sense_residual;
13777		msg.scsi.residual = io->scsiio.residual;
13778		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13779		       sizeof(io->scsiio.sense_data));
13780		/*
13781		 * We copy this whether or not this is an I/O-related
13782		 * command.  Otherwise, we'd have to go and check to see
13783		 * whether it's a read/write command, and it really isn't
13784		 * worth it.
13785		 */
13786		memcpy(&msg.scsi.lbalen,
13787		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13788		       sizeof(msg.scsi.lbalen));
13789
13790		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13791				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13792			/* XXX do something here */
13793		}
13794
13795		ctl_free_io(io);
13796	} else
13797		fe_done(io);
13798
13799bailout:
13800
13801	return (CTL_RETVAL_COMPLETE);
13802}
13803
13804#ifdef CTL_WITH_CA
13805/*
13806 * Front end should call this if it doesn't do autosense.  When the request
13807 * sense comes back in from the initiator, we'll dequeue this and send it.
13808 */
13809int
13810ctl_queue_sense(union ctl_io *io)
13811{
13812	struct ctl_lun *lun;
13813	struct ctl_softc *ctl_softc;
13814	uint32_t initidx, targ_lun;
13815
13816	ctl_softc = control_softc;
13817
13818	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13819
13820	/*
13821	 * LUN lookup will likely move to the ctl_work_thread() once we
13822	 * have our new queueing infrastructure (that doesn't put things on
13823	 * a per-LUN queue initially).  That is so that we can handle
13824	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13825	 * can't deal with that right now.
13826	 */
13827	mtx_lock(&ctl_softc->ctl_lock);
13828
13829	/*
13830	 * If we don't have a LUN for this, just toss the sense
13831	 * information.
13832	 */
13833	targ_lun = io->io_hdr.nexus.targ_lun;
13834	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13835	if ((targ_lun < CTL_MAX_LUNS)
13836	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13837		lun = ctl_softc->ctl_luns[targ_lun];
13838	else
13839		goto bailout;
13840
13841	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13842
13843	mtx_lock(&lun->lun_lock);
13844	/*
13845	 * Already have CA set for this LUN...toss the sense information.
13846	 */
13847	if (ctl_is_set(lun->have_ca, initidx)) {
13848		mtx_unlock(&lun->lun_lock);
13849		goto bailout;
13850	}
13851
13852	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13853	       ctl_min(sizeof(lun->pending_sense[initidx]),
13854	       sizeof(io->scsiio.sense_data)));
13855	ctl_set_mask(lun->have_ca, initidx);
13856	mtx_unlock(&lun->lun_lock);
13857
13858bailout:
13859	mtx_unlock(&ctl_softc->ctl_lock);
13860
13861	ctl_free_io(io);
13862
13863	return (CTL_RETVAL_COMPLETE);
13864}
13865#endif
13866
13867/*
13868 * Primary command inlet from frontend ports.  All SCSI and task I/O
13869 * requests must go through this function.
13870 */
13871int
13872ctl_queue(union ctl_io *io)
13873{
13874	struct ctl_softc *ctl_softc;
13875
13876	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13877
13878	ctl_softc = control_softc;
13879
13880#ifdef CTL_TIME_IO
13881	io->io_hdr.start_time = time_uptime;
13882	getbintime(&io->io_hdr.start_bt);
13883#endif /* CTL_TIME_IO */
13884
13885	/* Map FE-specific LUN ID into global one. */
13886	io->io_hdr.nexus.targ_mapped_lun =
13887	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13888
13889	switch (io->io_hdr.io_type) {
13890	case CTL_IO_SCSI:
13891	case CTL_IO_TASK:
13892		ctl_enqueue_incoming(io);
13893		break;
13894	default:
13895		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13896		return (EINVAL);
13897	}
13898
13899	return (CTL_RETVAL_COMPLETE);
13900}
13901
13902#ifdef CTL_IO_DELAY
13903static void
13904ctl_done_timer_wakeup(void *arg)
13905{
13906	union ctl_io *io;
13907
13908	io = (union ctl_io *)arg;
13909	ctl_done(io);
13910}
13911#endif /* CTL_IO_DELAY */
13912
13913void
13914ctl_done(union ctl_io *io)
13915{
13916	struct ctl_softc *ctl_softc;
13917
13918	ctl_softc = control_softc;
13919
13920	/*
13921	 * Enable this to catch duplicate completion issues.
13922	 */
13923#if 0
13924	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13925		printf("%s: type %d msg %d cdb %x iptl: "
13926		       "%d:%d:%d:%d tag 0x%04x "
13927		       "flag %#x status %x\n",
13928			__func__,
13929			io->io_hdr.io_type,
13930			io->io_hdr.msg_type,
13931			io->scsiio.cdb[0],
13932			io->io_hdr.nexus.initid.id,
13933			io->io_hdr.nexus.targ_port,
13934			io->io_hdr.nexus.targ_target.id,
13935			io->io_hdr.nexus.targ_lun,
13936			(io->io_hdr.io_type ==
13937			CTL_IO_TASK) ?
13938			io->taskio.tag_num :
13939			io->scsiio.tag_num,
13940		        io->io_hdr.flags,
13941			io->io_hdr.status);
13942	} else
13943		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13944#endif
13945
13946	/*
13947	 * This is an internal copy of an I/O, and should not go through
13948	 * the normal done processing logic.
13949	 */
13950	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13951		return;
13952
13953	/*
13954	 * We need to send a msg to the serializing shelf to finish the IO
13955	 * as well.  We don't send a finish message to the other shelf if
13956	 * this is a task management command.  Task management commands
13957	 * aren't serialized in the OOA queue, but rather just executed on
13958	 * both shelf controllers for commands that originated on that
13959	 * controller.
13960	 */
13961	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13962	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13963		union ctl_ha_msg msg_io;
13964
13965		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13966		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13967		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13968		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13969		}
13970		/* continue on to finish IO */
13971	}
13972#ifdef CTL_IO_DELAY
13973	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13974		struct ctl_lun *lun;
13975
13976		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13977
13978		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13979	} else {
13980		struct ctl_lun *lun;
13981
13982		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13983
13984		if ((lun != NULL)
13985		 && (lun->delay_info.done_delay > 0)) {
13986			struct callout *callout;
13987
13988			callout = (struct callout *)&io->io_hdr.timer_bytes;
13989			callout_init(callout, /*mpsafe*/ 1);
13990			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13991			callout_reset(callout,
13992				      lun->delay_info.done_delay * hz,
13993				      ctl_done_timer_wakeup, io);
13994			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13995				lun->delay_info.done_delay = 0;
13996			return;
13997		}
13998	}
13999#endif /* CTL_IO_DELAY */
14000
14001	ctl_enqueue_done(io);
14002}
14003
14004int
14005ctl_isc(struct ctl_scsiio *ctsio)
14006{
14007	struct ctl_lun *lun;
14008	int retval;
14009
14010	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14011
14012	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14013
14014	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14015
14016	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14017
14018	return (retval);
14019}
14020
14021
14022static void
14023ctl_work_thread(void *arg)
14024{
14025	struct ctl_thread *thr = (struct ctl_thread *)arg;
14026	struct ctl_softc *softc = thr->ctl_softc;
14027	union ctl_io *io;
14028	int retval;
14029
14030	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14031
14032	for (;;) {
14033		retval = 0;
14034
14035		/*
14036		 * We handle the queues in this order:
14037		 * - ISC
14038		 * - done queue (to free up resources, unblock other commands)
14039		 * - RtR queue
14040		 * - incoming queue
14041		 *
14042		 * If those queues are empty, we break out of the loop and
14043		 * go to sleep.
14044		 */
14045		mtx_lock(&thr->queue_lock);
14046		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14047		if (io != NULL) {
14048			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14049			mtx_unlock(&thr->queue_lock);
14050			ctl_handle_isc(io);
14051			continue;
14052		}
14053		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14054		if (io != NULL) {
14055			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14056			/* clear any blocked commands, call fe_done */
14057			mtx_unlock(&thr->queue_lock);
14058			retval = ctl_process_done(io);
14059			continue;
14060		}
14061		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14062		if (io != NULL) {
14063			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14064			mtx_unlock(&thr->queue_lock);
14065			if (io->io_hdr.io_type == CTL_IO_TASK)
14066				ctl_run_task(io);
14067			else
14068				ctl_scsiio_precheck(softc, &io->scsiio);
14069			continue;
14070		}
14071		if (!ctl_pause_rtr) {
14072			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14073			if (io != NULL) {
14074				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14075				mtx_unlock(&thr->queue_lock);
14076				retval = ctl_scsiio(&io->scsiio);
14077				if (retval != CTL_RETVAL_COMPLETE)
14078					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14079				continue;
14080			}
14081		}
14082
14083		/* Sleep until we have something to do. */
14084		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14085	}
14086}
14087
14088static void
14089ctl_lun_thread(void *arg)
14090{
14091	struct ctl_softc *softc = (struct ctl_softc *)arg;
14092	struct ctl_be_lun *be_lun;
14093	int retval;
14094
14095	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14096
14097	for (;;) {
14098		retval = 0;
14099		mtx_lock(&softc->ctl_lock);
14100		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14101		if (be_lun != NULL) {
14102			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14103			mtx_unlock(&softc->ctl_lock);
14104			ctl_create_lun(be_lun);
14105			continue;
14106		}
14107
14108		/* Sleep until we have something to do. */
14109		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14110		    PDROP | PRIBIO, "-", 0);
14111	}
14112}
14113
14114static void
14115ctl_enqueue_incoming(union ctl_io *io)
14116{
14117	struct ctl_softc *softc = control_softc;
14118	struct ctl_thread *thr;
14119	u_int idx;
14120
14121	idx = (io->io_hdr.nexus.targ_port * 127 +
14122	       io->io_hdr.nexus.initid.id) % worker_threads;
14123	thr = &softc->threads[idx];
14124	mtx_lock(&thr->queue_lock);
14125	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14126	mtx_unlock(&thr->queue_lock);
14127	wakeup(thr);
14128}
14129
14130static void
14131ctl_enqueue_rtr(union ctl_io *io)
14132{
14133	struct ctl_softc *softc = control_softc;
14134	struct ctl_thread *thr;
14135
14136	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14137	mtx_lock(&thr->queue_lock);
14138	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14139	mtx_unlock(&thr->queue_lock);
14140	wakeup(thr);
14141}
14142
14143static void
14144ctl_enqueue_done(union ctl_io *io)
14145{
14146	struct ctl_softc *softc = control_softc;
14147	struct ctl_thread *thr;
14148
14149	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14150	mtx_lock(&thr->queue_lock);
14151	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14152	mtx_unlock(&thr->queue_lock);
14153	wakeup(thr);
14154}
14155
14156static void
14157ctl_enqueue_isc(union ctl_io *io)
14158{
14159	struct ctl_softc *softc = control_softc;
14160	struct ctl_thread *thr;
14161
14162	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14163	mtx_lock(&thr->queue_lock);
14164	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14165	mtx_unlock(&thr->queue_lock);
14166	wakeup(thr);
14167}
14168
14169/* Initialization and failover */
14170
14171void
14172ctl_init_isc_msg(void)
14173{
14174	printf("CTL: Still calling this thing\n");
14175}
14176
14177/*
14178 * Init component
14179 * 	Initializes component into configuration defined by bootMode
14180 *	(see hasc-sv.c)
14181 *  	returns hasc_Status:
14182 * 		OK
14183 *		ERROR - fatal error
14184 */
14185static ctl_ha_comp_status
14186ctl_isc_init(struct ctl_ha_component *c)
14187{
14188	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14189
14190	c->status = ret;
14191	return ret;
14192}
14193
14194/* Start component
14195 * 	Starts component in state requested. If component starts successfully,
14196 *	it must set its own state to the requestrd state
14197 *	When requested state is HASC_STATE_HA, the component may refine it
14198 * 	by adding _SLAVE or _MASTER flags.
14199 *	Currently allowed state transitions are:
14200 *	UNKNOWN->HA		- initial startup
14201 *	UNKNOWN->SINGLE - initial startup when no parter detected
14202 *	HA->SINGLE		- failover
14203 * returns ctl_ha_comp_status:
14204 * 		OK	- component successfully started in requested state
14205 *		FAILED  - could not start the requested state, failover may
14206 * 			  be possible
14207 *		ERROR	- fatal error detected, no future startup possible
14208 */
14209static ctl_ha_comp_status
14210ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14211{
14212	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14213
14214	printf("%s: go\n", __func__);
14215
14216	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14217	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14218		ctl_is_single = 0;
14219		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14220		    != CTL_HA_STATUS_SUCCESS) {
14221			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14222			ret = CTL_HA_COMP_STATUS_ERROR;
14223		}
14224	} else if (CTL_HA_STATE_IS_HA(c->state)
14225		&& CTL_HA_STATE_IS_SINGLE(state)){
14226		// HA->SINGLE transition
14227	        ctl_failover();
14228		ctl_is_single = 1;
14229	} else {
14230		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14231		       c->state, state);
14232		ret = CTL_HA_COMP_STATUS_ERROR;
14233	}
14234	if (CTL_HA_STATE_IS_SINGLE(state))
14235		ctl_is_single = 1;
14236
14237	c->state = state;
14238	c->status = ret;
14239	return ret;
14240}
14241
14242/*
14243 * Quiesce component
14244 * The component must clear any error conditions (set status to OK) and
14245 * prepare itself to another Start call
14246 * returns ctl_ha_comp_status:
14247 * 	OK
14248 *	ERROR
14249 */
14250static ctl_ha_comp_status
14251ctl_isc_quiesce(struct ctl_ha_component *c)
14252{
14253	int ret = CTL_HA_COMP_STATUS_OK;
14254
14255	ctl_pause_rtr = 1;
14256	c->status = ret;
14257	return ret;
14258}
14259
14260struct ctl_ha_component ctl_ha_component_ctlisc =
14261{
14262	.name = "CTL ISC",
14263	.state = CTL_HA_STATE_UNKNOWN,
14264	.init = ctl_isc_init,
14265	.start = ctl_isc_start,
14266	.quiesce = ctl_isc_quiesce
14267};
14268
14269/*
14270 *  vim: ts=8
14271 */
14272