ctl.c revision 272629
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 272629 2014-10-06 13:18:28Z 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 * Extended INQUIRY Data (0x86), 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	10
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_eid(struct ctl_scsiio *ctsio, int alloc_len);
386static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
387static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
388					 int alloc_len);
389static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
390					 int alloc_len);
391static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
392static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
393static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
394static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
395static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
396static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
397static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
398					 union ctl_io *ooa_io);
399static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
400				union ctl_io *starting_io);
401static int ctl_check_blocked(struct ctl_lun *lun);
402static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
403				struct ctl_lun *lun,
404				const struct ctl_cmd_entry *entry,
405				struct ctl_scsiio *ctsio);
406//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
407static void ctl_failover(void);
408static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
409			       struct ctl_scsiio *ctsio);
410static int ctl_scsiio(struct ctl_scsiio *ctsio);
411
412static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
413static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
414			    ctl_ua_type ua_type);
415static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
416			 ctl_ua_type ua_type);
417static int ctl_abort_task(union ctl_io *io);
418static int ctl_abort_task_set(union ctl_io *io);
419static int ctl_i_t_nexus_reset(union ctl_io *io);
420static void ctl_run_task(union ctl_io *io);
421#ifdef CTL_IO_DELAY
422static void ctl_datamove_timer_wakeup(void *arg);
423static void ctl_done_timer_wakeup(void *arg);
424#endif /* CTL_IO_DELAY */
425
426static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
427static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
428static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
429static void ctl_datamove_remote_write(union ctl_io *io);
430static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
431static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
432static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
433static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
434				    ctl_ha_dt_cb callback);
435static void ctl_datamove_remote_read(union ctl_io *io);
436static void ctl_datamove_remote(union ctl_io *io);
437static int ctl_process_done(union ctl_io *io);
438static void ctl_lun_thread(void *arg);
439static void ctl_work_thread(void *arg);
440static void ctl_enqueue_incoming(union ctl_io *io);
441static void ctl_enqueue_rtr(union ctl_io *io);
442static void ctl_enqueue_done(union ctl_io *io);
443static void ctl_enqueue_isc(union ctl_io *io);
444static const struct ctl_cmd_entry *
445    ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
446static const struct ctl_cmd_entry *
447    ctl_validate_command(struct ctl_scsiio *ctsio);
448static int ctl_cmd_applicable(uint8_t lun_type,
449    const struct ctl_cmd_entry *entry);
450
451/*
452 * Load the serialization table.  This isn't very pretty, but is probably
453 * the easiest way to do it.
454 */
455#include "ctl_ser_table.c"
456
457/*
458 * We only need to define open, close and ioctl routines for this driver.
459 */
460static struct cdevsw ctl_cdevsw = {
461	.d_version =	D_VERSION,
462	.d_flags =	0,
463	.d_open =	ctl_open,
464	.d_close =	ctl_close,
465	.d_ioctl =	ctl_ioctl,
466	.d_name =	"ctl",
467};
468
469
470MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
471MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
472
473static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
474
475static moduledata_t ctl_moduledata = {
476	"ctl",
477	ctl_module_event_handler,
478	NULL
479};
480
481DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
482MODULE_VERSION(ctl, 1);
483
484static struct ctl_frontend ioctl_frontend =
485{
486	.name = "ioctl",
487};
488
489static void
490ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
491			    union ctl_ha_msg *msg_info)
492{
493	struct ctl_scsiio *ctsio;
494
495	if (msg_info->hdr.original_sc == NULL) {
496		printf("%s: original_sc == NULL!\n", __func__);
497		/* XXX KDM now what? */
498		return;
499	}
500
501	ctsio = &msg_info->hdr.original_sc->scsiio;
502	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
503	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
504	ctsio->io_hdr.status = msg_info->hdr.status;
505	ctsio->scsi_status = msg_info->scsi.scsi_status;
506	ctsio->sense_len = msg_info->scsi.sense_len;
507	ctsio->sense_residual = msg_info->scsi.sense_residual;
508	ctsio->residual = msg_info->scsi.residual;
509	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
510	       sizeof(ctsio->sense_data));
511	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
512	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
513	ctl_enqueue_isc((union ctl_io *)ctsio);
514}
515
516static void
517ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
518				union ctl_ha_msg *msg_info)
519{
520	struct ctl_scsiio *ctsio;
521
522	if (msg_info->hdr.serializing_sc == NULL) {
523		printf("%s: serializing_sc == NULL!\n", __func__);
524		/* XXX KDM now what? */
525		return;
526	}
527
528	ctsio = &msg_info->hdr.serializing_sc->scsiio;
529#if 0
530	/*
531	 * Attempt to catch the situation where an I/O has
532	 * been freed, and we're using it again.
533	 */
534	if (ctsio->io_hdr.io_type == 0xff) {
535		union ctl_io *tmp_io;
536		tmp_io = (union ctl_io *)ctsio;
537		printf("%s: %p use after free!\n", __func__,
538		       ctsio);
539		printf("%s: type %d msg %d cdb %x iptl: "
540		       "%d:%d:%d:%d tag 0x%04x "
541		       "flag %#x status %x\n",
542			__func__,
543			tmp_io->io_hdr.io_type,
544			tmp_io->io_hdr.msg_type,
545			tmp_io->scsiio.cdb[0],
546			tmp_io->io_hdr.nexus.initid.id,
547			tmp_io->io_hdr.nexus.targ_port,
548			tmp_io->io_hdr.nexus.targ_target.id,
549			tmp_io->io_hdr.nexus.targ_lun,
550			(tmp_io->io_hdr.io_type ==
551			CTL_IO_TASK) ?
552			tmp_io->taskio.tag_num :
553			tmp_io->scsiio.tag_num,
554		        tmp_io->io_hdr.flags,
555			tmp_io->io_hdr.status);
556	}
557#endif
558	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
559	ctl_enqueue_isc((union ctl_io *)ctsio);
560}
561
562/*
563 * ISC (Inter Shelf Communication) event handler.  Events from the HA
564 * subsystem come in here.
565 */
566static void
567ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
568{
569	struct ctl_softc *ctl_softc;
570	union ctl_io *io;
571	struct ctl_prio *presio;
572	ctl_ha_status isc_status;
573
574	ctl_softc = control_softc;
575	io = NULL;
576
577
578#if 0
579	printf("CTL: Isc Msg event %d\n", event);
580#endif
581	if (event == CTL_HA_EVT_MSG_RECV) {
582		union ctl_ha_msg msg_info;
583
584		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
585					     sizeof(msg_info), /*wait*/ 0);
586#if 0
587		printf("CTL: msg_type %d\n", msg_info.msg_type);
588#endif
589		if (isc_status != 0) {
590			printf("Error receiving message, status = %d\n",
591			       isc_status);
592			return;
593		}
594
595		switch (msg_info.hdr.msg_type) {
596		case CTL_MSG_SERIALIZE:
597#if 0
598			printf("Serialize\n");
599#endif
600			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
601			if (io == NULL) {
602				printf("ctl_isc_event_handler: can't allocate "
603				       "ctl_io!\n");
604				/* Bad Juju */
605				/* Need to set busy and send msg back */
606				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
607				msg_info.hdr.status = CTL_SCSI_ERROR;
608				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
609				msg_info.scsi.sense_len = 0;
610			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
611				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
612				}
613				goto bailout;
614			}
615			ctl_zero_io(io);
616			// populate ctsio from msg_info
617			io->io_hdr.io_type = CTL_IO_SCSI;
618			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
619			io->io_hdr.original_sc = msg_info.hdr.original_sc;
620#if 0
621			printf("pOrig %x\n", (int)msg_info.original_sc);
622#endif
623			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
624					    CTL_FLAG_IO_ACTIVE;
625			/*
626			 * If we're in serialization-only mode, we don't
627			 * want to go through full done processing.  Thus
628			 * the COPY flag.
629			 *
630			 * XXX KDM add another flag that is more specific.
631			 */
632			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
633				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
634			io->io_hdr.nexus = msg_info.hdr.nexus;
635#if 0
636			printf("targ %d, port %d, iid %d, lun %d\n",
637			       io->io_hdr.nexus.targ_target.id,
638			       io->io_hdr.nexus.targ_port,
639			       io->io_hdr.nexus.initid.id,
640			       io->io_hdr.nexus.targ_lun);
641#endif
642			io->scsiio.tag_num = msg_info.scsi.tag_num;
643			io->scsiio.tag_type = msg_info.scsi.tag_type;
644			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
645			       CTL_MAX_CDBLEN);
646			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
647				const struct ctl_cmd_entry *entry;
648
649				entry = ctl_get_cmd_entry(&io->scsiio);
650				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
651				io->io_hdr.flags |=
652					entry->flags & CTL_FLAG_DATA_MASK;
653			}
654			ctl_enqueue_isc(io);
655			break;
656
657		/* Performed on the Originating SC, XFER mode only */
658		case CTL_MSG_DATAMOVE: {
659			struct ctl_sg_entry *sgl;
660			int i, j;
661
662			io = msg_info.hdr.original_sc;
663			if (io == NULL) {
664				printf("%s: original_sc == NULL!\n", __func__);
665				/* XXX KDM do something here */
666				break;
667			}
668			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
669			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
670			/*
671			 * Keep track of this, we need to send it back over
672			 * when the datamove is complete.
673			 */
674			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
675
676			if (msg_info.dt.sg_sequence == 0) {
677				/*
678				 * XXX KDM we use the preallocated S/G list
679				 * here, but we'll need to change this to
680				 * dynamic allocation if we need larger S/G
681				 * lists.
682				 */
683				if (msg_info.dt.kern_sg_entries >
684				    sizeof(io->io_hdr.remote_sglist) /
685				    sizeof(io->io_hdr.remote_sglist[0])) {
686					printf("%s: number of S/G entries "
687					    "needed %u > allocated num %zd\n",
688					    __func__,
689					    msg_info.dt.kern_sg_entries,
690					    sizeof(io->io_hdr.remote_sglist)/
691					    sizeof(io->io_hdr.remote_sglist[0]));
692
693					/*
694					 * XXX KDM send a message back to
695					 * the other side to shut down the
696					 * DMA.  The error will come back
697					 * through via the normal channel.
698					 */
699					break;
700				}
701				sgl = io->io_hdr.remote_sglist;
702				memset(sgl, 0,
703				       sizeof(io->io_hdr.remote_sglist));
704
705				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
706
707				io->scsiio.kern_sg_entries =
708					msg_info.dt.kern_sg_entries;
709				io->scsiio.rem_sg_entries =
710					msg_info.dt.kern_sg_entries;
711				io->scsiio.kern_data_len =
712					msg_info.dt.kern_data_len;
713				io->scsiio.kern_total_len =
714					msg_info.dt.kern_total_len;
715				io->scsiio.kern_data_resid =
716					msg_info.dt.kern_data_resid;
717				io->scsiio.kern_rel_offset =
718					msg_info.dt.kern_rel_offset;
719				/*
720				 * Clear out per-DMA flags.
721				 */
722				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
723				/*
724				 * Add per-DMA flags that are set for this
725				 * particular DMA request.
726				 */
727				io->io_hdr.flags |= msg_info.dt.flags &
728						    CTL_FLAG_RDMA_MASK;
729			} else
730				sgl = (struct ctl_sg_entry *)
731					io->scsiio.kern_data_ptr;
732
733			for (i = msg_info.dt.sent_sg_entries, j = 0;
734			     i < (msg_info.dt.sent_sg_entries +
735			     msg_info.dt.cur_sg_entries); i++, j++) {
736				sgl[i].addr = msg_info.dt.sg_list[j].addr;
737				sgl[i].len = msg_info.dt.sg_list[j].len;
738
739#if 0
740				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
741				       __func__,
742				       msg_info.dt.sg_list[j].addr,
743				       msg_info.dt.sg_list[j].len,
744				       sgl[i].addr, sgl[i].len, j, i);
745#endif
746			}
747#if 0
748			memcpy(&sgl[msg_info.dt.sent_sg_entries],
749			       msg_info.dt.sg_list,
750			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
751#endif
752
753			/*
754			 * If this is the last piece of the I/O, we've got
755			 * the full S/G list.  Queue processing in the thread.
756			 * Otherwise wait for the next piece.
757			 */
758			if (msg_info.dt.sg_last != 0)
759				ctl_enqueue_isc(io);
760			break;
761		}
762		/* Performed on the Serializing (primary) SC, XFER mode only */
763		case CTL_MSG_DATAMOVE_DONE: {
764			if (msg_info.hdr.serializing_sc == NULL) {
765				printf("%s: serializing_sc == NULL!\n",
766				       __func__);
767				/* XXX KDM now what? */
768				break;
769			}
770			/*
771			 * We grab the sense information here in case
772			 * there was a failure, so we can return status
773			 * back to the initiator.
774			 */
775			io = msg_info.hdr.serializing_sc;
776			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
777			io->io_hdr.status = msg_info.hdr.status;
778			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
779			io->scsiio.sense_len = msg_info.scsi.sense_len;
780			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
781			io->io_hdr.port_status = msg_info.scsi.fetd_status;
782			io->scsiio.residual = msg_info.scsi.residual;
783			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
784			       sizeof(io->scsiio.sense_data));
785			ctl_enqueue_isc(io);
786			break;
787		}
788
789		/* Preformed on Originating SC, SER_ONLY mode */
790		case CTL_MSG_R2R:
791			io = msg_info.hdr.original_sc;
792			if (io == NULL) {
793				printf("%s: Major Bummer\n", __func__);
794				return;
795			} else {
796#if 0
797				printf("pOrig %x\n",(int) ctsio);
798#endif
799			}
800			io->io_hdr.msg_type = CTL_MSG_R2R;
801			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
802			ctl_enqueue_isc(io);
803			break;
804
805		/*
806		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
807		 * mode.
808		 * Performed on the Originating (i.e. secondary) SC in XFER
809		 * mode
810		 */
811		case CTL_MSG_FINISH_IO:
812			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
813				ctl_isc_handler_finish_xfer(ctl_softc,
814							    &msg_info);
815			else
816				ctl_isc_handler_finish_ser_only(ctl_softc,
817								&msg_info);
818			break;
819
820		/* Preformed on Originating SC */
821		case CTL_MSG_BAD_JUJU:
822			io = msg_info.hdr.original_sc;
823			if (io == NULL) {
824				printf("%s: Bad JUJU!, original_sc is NULL!\n",
825				       __func__);
826				break;
827			}
828			ctl_copy_sense_data(&msg_info, io);
829			/*
830			 * IO should have already been cleaned up on other
831			 * SC so clear this flag so we won't send a message
832			 * back to finish the IO there.
833			 */
834			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
835			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
836
837			/* io = msg_info.hdr.serializing_sc; */
838			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
839			ctl_enqueue_isc(io);
840			break;
841
842		/* Handle resets sent from the other side */
843		case CTL_MSG_MANAGE_TASKS: {
844			struct ctl_taskio *taskio;
845			taskio = (struct ctl_taskio *)ctl_alloc_io(
846				(void *)ctl_softc->othersc_pool);
847			if (taskio == NULL) {
848				printf("ctl_isc_event_handler: can't allocate "
849				       "ctl_io!\n");
850				/* Bad Juju */
851				/* should I just call the proper reset func
852				   here??? */
853				goto bailout;
854			}
855			ctl_zero_io((union ctl_io *)taskio);
856			taskio->io_hdr.io_type = CTL_IO_TASK;
857			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
858			taskio->io_hdr.nexus = msg_info.hdr.nexus;
859			taskio->task_action = msg_info.task.task_action;
860			taskio->tag_num = msg_info.task.tag_num;
861			taskio->tag_type = msg_info.task.tag_type;
862#ifdef CTL_TIME_IO
863			taskio->io_hdr.start_time = time_uptime;
864			getbintime(&taskio->io_hdr.start_bt);
865#if 0
866			cs_prof_gettime(&taskio->io_hdr.start_ticks);
867#endif
868#endif /* CTL_TIME_IO */
869			ctl_run_task((union ctl_io *)taskio);
870			break;
871		}
872		/* Persistent Reserve action which needs attention */
873		case CTL_MSG_PERS_ACTION:
874			presio = (struct ctl_prio *)ctl_alloc_io(
875				(void *)ctl_softc->othersc_pool);
876			if (presio == NULL) {
877				printf("ctl_isc_event_handler: can't allocate "
878				       "ctl_io!\n");
879				/* Bad Juju */
880				/* Need to set busy and send msg back */
881				goto bailout;
882			}
883			ctl_zero_io((union ctl_io *)presio);
884			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
885			presio->pr_msg = msg_info.pr;
886			ctl_enqueue_isc((union ctl_io *)presio);
887			break;
888		case CTL_MSG_SYNC_FE:
889			rcv_sync_msg = 1;
890			break;
891		case CTL_MSG_APS_LOCK: {
892			// It's quicker to execute this then to
893			// queue it.
894			struct ctl_lun *lun;
895			struct ctl_page_index *page_index;
896			struct copan_aps_subpage *current_sp;
897			uint32_t targ_lun;
898
899			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
900			lun = ctl_softc->ctl_luns[targ_lun];
901			mtx_lock(&lun->lun_lock);
902			page_index = &lun->mode_pages.index[index_to_aps_page];
903			current_sp = (struct copan_aps_subpage *)
904				     (page_index->page_data +
905				     (page_index->page_len * CTL_PAGE_CURRENT));
906
907			current_sp->lock_active = msg_info.aps.lock_flag;
908			mtx_unlock(&lun->lun_lock);
909		        break;
910		}
911		default:
912		        printf("How did I get here?\n");
913		}
914	} else if (event == CTL_HA_EVT_MSG_SENT) {
915		if (param != CTL_HA_STATUS_SUCCESS) {
916			printf("Bad status from ctl_ha_msg_send status %d\n",
917			       param);
918		}
919		return;
920	} else if (event == CTL_HA_EVT_DISCONNECT) {
921		printf("CTL: Got a disconnect from Isc\n");
922		return;
923	} else {
924		printf("ctl_isc_event_handler: Unknown event %d\n", event);
925		return;
926	}
927
928bailout:
929	return;
930}
931
932static void
933ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
934{
935	struct scsi_sense_data *sense;
936
937	sense = &dest->scsiio.sense_data;
938	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
939	dest->scsiio.scsi_status = src->scsi.scsi_status;
940	dest->scsiio.sense_len = src->scsi.sense_len;
941	dest->io_hdr.status = src->hdr.status;
942}
943
944static int
945ctl_init(void)
946{
947	struct ctl_softc *softc;
948	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
949	struct ctl_port *port;
950        uint8_t sc_id =0;
951	int i, error, retval;
952	//int isc_retval;
953
954	retval = 0;
955	ctl_pause_rtr = 0;
956        rcv_sync_msg = 0;
957
958	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
959			       M_WAITOK | M_ZERO);
960	softc = control_softc;
961
962	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
963			      "cam/ctl");
964
965	softc->dev->si_drv1 = softc;
966
967	/*
968	 * By default, return a "bad LUN" peripheral qualifier for unknown
969	 * LUNs.  The user can override this default using the tunable or
970	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
971	 */
972	softc->inquiry_pq_no_lun = 1;
973	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
974			  &softc->inquiry_pq_no_lun);
975	sysctl_ctx_init(&softc->sysctl_ctx);
976	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
977		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
978		CTLFLAG_RD, 0, "CAM Target Layer");
979
980	if (softc->sysctl_tree == NULL) {
981		printf("%s: unable to allocate sysctl tree\n", __func__);
982		destroy_dev(softc->dev);
983		free(control_softc, M_DEVBUF);
984		control_softc = NULL;
985		return (ENOMEM);
986	}
987
988	SYSCTL_ADD_INT(&softc->sysctl_ctx,
989		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
990		       "inquiry_pq_no_lun", CTLFLAG_RW,
991		       &softc->inquiry_pq_no_lun, 0,
992		       "Report no lun possible for invalid LUNs");
993
994	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
995	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
996	softc->open_count = 0;
997
998	/*
999	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1000	 * the drive.
1001	 */
1002	softc->flags = CTL_FLAG_REAL_SYNC;
1003
1004	/*
1005	 * In Copan's HA scheme, the "master" and "slave" roles are
1006	 * figured out through the slot the controller is in.  Although it
1007	 * is an active/active system, someone has to be in charge.
1008 	 */
1009#ifdef NEEDTOPORT
1010        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1011#endif
1012
1013        if (sc_id == 0) {
1014		softc->flags |= CTL_FLAG_MASTER_SHELF;
1015		persis_offset = 0;
1016	} else
1017		persis_offset = CTL_MAX_INITIATORS;
1018
1019	/*
1020	 * XXX KDM need to figure out where we want to get our target ID
1021	 * and WWID.  Is it different on each port?
1022	 */
1023	softc->target.id = 0;
1024	softc->target.wwid[0] = 0x12345678;
1025	softc->target.wwid[1] = 0x87654321;
1026	STAILQ_INIT(&softc->lun_list);
1027	STAILQ_INIT(&softc->pending_lun_queue);
1028	STAILQ_INIT(&softc->fe_list);
1029	STAILQ_INIT(&softc->port_list);
1030	STAILQ_INIT(&softc->be_list);
1031	STAILQ_INIT(&softc->io_pools);
1032	ctl_tpc_init(softc);
1033
1034	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1035			    &internal_pool)!= 0){
1036		printf("ctl: can't allocate %d entry internal pool, "
1037		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1038		return (ENOMEM);
1039	}
1040
1041	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1042			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1043		printf("ctl: can't allocate %d entry emergency pool, "
1044		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1045		ctl_pool_free(internal_pool);
1046		return (ENOMEM);
1047	}
1048
1049	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1050	                    &other_pool) != 0)
1051	{
1052		printf("ctl: can't allocate %d entry other SC pool, "
1053		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1054		ctl_pool_free(internal_pool);
1055		ctl_pool_free(emergency_pool);
1056		return (ENOMEM);
1057	}
1058
1059	softc->internal_pool = internal_pool;
1060	softc->emergency_pool = emergency_pool;
1061	softc->othersc_pool = other_pool;
1062
1063	if (worker_threads <= 0)
1064		worker_threads = max(1, mp_ncpus / 4);
1065	if (worker_threads > CTL_MAX_THREADS)
1066		worker_threads = CTL_MAX_THREADS;
1067
1068	for (i = 0; i < worker_threads; i++) {
1069		struct ctl_thread *thr = &softc->threads[i];
1070
1071		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1072		thr->ctl_softc = softc;
1073		STAILQ_INIT(&thr->incoming_queue);
1074		STAILQ_INIT(&thr->rtr_queue);
1075		STAILQ_INIT(&thr->done_queue);
1076		STAILQ_INIT(&thr->isc_queue);
1077
1078		error = kproc_kthread_add(ctl_work_thread, thr,
1079		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1080		if (error != 0) {
1081			printf("error creating CTL work thread!\n");
1082			ctl_pool_free(internal_pool);
1083			ctl_pool_free(emergency_pool);
1084			ctl_pool_free(other_pool);
1085			return (error);
1086		}
1087	}
1088	error = kproc_kthread_add(ctl_lun_thread, softc,
1089	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1090	if (error != 0) {
1091		printf("error creating CTL lun thread!\n");
1092		ctl_pool_free(internal_pool);
1093		ctl_pool_free(emergency_pool);
1094		ctl_pool_free(other_pool);
1095		return (error);
1096	}
1097	if (bootverbose)
1098		printf("ctl: CAM Target Layer loaded\n");
1099
1100	/*
1101	 * Initialize the ioctl front end.
1102	 */
1103	ctl_frontend_register(&ioctl_frontend);
1104	port = &softc->ioctl_info.port;
1105	port->frontend = &ioctl_frontend;
1106	sprintf(softc->ioctl_info.port_name, "ioctl");
1107	port->port_type = CTL_PORT_IOCTL;
1108	port->num_requested_ctl_io = 100;
1109	port->port_name = softc->ioctl_info.port_name;
1110	port->port_online = ctl_ioctl_online;
1111	port->port_offline = ctl_ioctl_offline;
1112	port->onoff_arg = &softc->ioctl_info;
1113	port->lun_enable = ctl_ioctl_lun_enable;
1114	port->lun_disable = ctl_ioctl_lun_disable;
1115	port->targ_lun_arg = &softc->ioctl_info;
1116	port->fe_datamove = ctl_ioctl_datamove;
1117	port->fe_done = ctl_ioctl_done;
1118	port->max_targets = 15;
1119	port->max_target_id = 15;
1120
1121	if (ctl_port_register(&softc->ioctl_info.port,
1122	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1123		printf("ctl: ioctl front end registration failed, will "
1124		       "continue anyway\n");
1125	}
1126
1127#ifdef CTL_IO_DELAY
1128	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1129		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1130		       sizeof(struct callout), CTL_TIMER_BYTES);
1131		return (EINVAL);
1132	}
1133#endif /* CTL_IO_DELAY */
1134
1135	return (0);
1136}
1137
1138void
1139ctl_shutdown(void)
1140{
1141	struct ctl_softc *softc;
1142	struct ctl_lun *lun, *next_lun;
1143	struct ctl_io_pool *pool;
1144
1145	softc = (struct ctl_softc *)control_softc;
1146
1147	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1148		printf("ctl: ioctl front end deregistration failed\n");
1149
1150	mtx_lock(&softc->ctl_lock);
1151
1152	/*
1153	 * Free up each LUN.
1154	 */
1155	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1156		next_lun = STAILQ_NEXT(lun, links);
1157		ctl_free_lun(lun);
1158	}
1159
1160	mtx_unlock(&softc->ctl_lock);
1161
1162	ctl_frontend_deregister(&ioctl_frontend);
1163
1164	/*
1165	 * This will rip the rug out from under any FETDs or anyone else
1166	 * that has a pool allocated.  Since we increment our module
1167	 * refcount any time someone outside the main CTL module allocates
1168	 * a pool, we shouldn't have any problems here.  The user won't be
1169	 * able to unload the CTL module until client modules have
1170	 * successfully unloaded.
1171	 */
1172	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1173		ctl_pool_free(pool);
1174
1175#if 0
1176	ctl_shutdown_thread(softc->work_thread);
1177	mtx_destroy(&softc->queue_lock);
1178#endif
1179
1180	ctl_tpc_shutdown(softc);
1181	mtx_destroy(&softc->pool_lock);
1182	mtx_destroy(&softc->ctl_lock);
1183
1184	destroy_dev(softc->dev);
1185
1186	sysctl_ctx_free(&softc->sysctl_ctx);
1187
1188	free(control_softc, M_DEVBUF);
1189	control_softc = NULL;
1190
1191	if (bootverbose)
1192		printf("ctl: CAM Target Layer unloaded\n");
1193}
1194
1195static int
1196ctl_module_event_handler(module_t mod, int what, void *arg)
1197{
1198
1199	switch (what) {
1200	case MOD_LOAD:
1201		return (ctl_init());
1202	case MOD_UNLOAD:
1203		return (EBUSY);
1204	default:
1205		return (EOPNOTSUPP);
1206	}
1207}
1208
1209/*
1210 * XXX KDM should we do some access checks here?  Bump a reference count to
1211 * prevent a CTL module from being unloaded while someone has it open?
1212 */
1213static int
1214ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1215{
1216	return (0);
1217}
1218
1219static int
1220ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1221{
1222	return (0);
1223}
1224
1225int
1226ctl_port_enable(ctl_port_type port_type)
1227{
1228	struct ctl_softc *softc;
1229	struct ctl_port *port;
1230
1231	if (ctl_is_single == 0) {
1232		union ctl_ha_msg msg_info;
1233		int isc_retval;
1234
1235#if 0
1236		printf("%s: HA mode, synchronizing frontend enable\n",
1237		        __func__);
1238#endif
1239		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1240	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1241		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1242			printf("Sync msg send error retval %d\n", isc_retval);
1243		}
1244		if (!rcv_sync_msg) {
1245			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1246			        sizeof(msg_info), 1);
1247		}
1248#if 0
1249        	printf("CTL:Frontend Enable\n");
1250	} else {
1251		printf("%s: single mode, skipping frontend synchronization\n",
1252		        __func__);
1253#endif
1254	}
1255
1256	softc = control_softc;
1257
1258	STAILQ_FOREACH(port, &softc->port_list, links) {
1259		if (port_type & port->port_type)
1260		{
1261#if 0
1262			printf("port %d\n", port->targ_port);
1263#endif
1264			ctl_port_online(port);
1265		}
1266	}
1267
1268	return (0);
1269}
1270
1271int
1272ctl_port_disable(ctl_port_type port_type)
1273{
1274	struct ctl_softc *softc;
1275	struct ctl_port *port;
1276
1277	softc = control_softc;
1278
1279	STAILQ_FOREACH(port, &softc->port_list, links) {
1280		if (port_type & port->port_type)
1281			ctl_port_offline(port);
1282	}
1283
1284	return (0);
1285}
1286
1287/*
1288 * Returns 0 for success, 1 for failure.
1289 * Currently the only failure mode is if there aren't enough entries
1290 * allocated.  So, in case of a failure, look at num_entries_dropped,
1291 * reallocate and try again.
1292 */
1293int
1294ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1295	      int *num_entries_filled, int *num_entries_dropped,
1296	      ctl_port_type port_type, int no_virtual)
1297{
1298	struct ctl_softc *softc;
1299	struct ctl_port *port;
1300	int entries_dropped, entries_filled;
1301	int retval;
1302	int i;
1303
1304	softc = control_softc;
1305
1306	retval = 0;
1307	entries_filled = 0;
1308	entries_dropped = 0;
1309
1310	i = 0;
1311	mtx_lock(&softc->ctl_lock);
1312	STAILQ_FOREACH(port, &softc->port_list, links) {
1313		struct ctl_port_entry *entry;
1314
1315		if ((port->port_type & port_type) == 0)
1316			continue;
1317
1318		if ((no_virtual != 0)
1319		 && (port->virtual_port != 0))
1320			continue;
1321
1322		if (entries_filled >= num_entries_alloced) {
1323			entries_dropped++;
1324			continue;
1325		}
1326		entry = &entries[i];
1327
1328		entry->port_type = port->port_type;
1329		strlcpy(entry->port_name, port->port_name,
1330			sizeof(entry->port_name));
1331		entry->physical_port = port->physical_port;
1332		entry->virtual_port = port->virtual_port;
1333		entry->wwnn = port->wwnn;
1334		entry->wwpn = port->wwpn;
1335
1336		i++;
1337		entries_filled++;
1338	}
1339
1340	mtx_unlock(&softc->ctl_lock);
1341
1342	if (entries_dropped > 0)
1343		retval = 1;
1344
1345	*num_entries_dropped = entries_dropped;
1346	*num_entries_filled = entries_filled;
1347
1348	return (retval);
1349}
1350
1351static void
1352ctl_ioctl_online(void *arg)
1353{
1354	struct ctl_ioctl_info *ioctl_info;
1355
1356	ioctl_info = (struct ctl_ioctl_info *)arg;
1357
1358	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1359}
1360
1361static void
1362ctl_ioctl_offline(void *arg)
1363{
1364	struct ctl_ioctl_info *ioctl_info;
1365
1366	ioctl_info = (struct ctl_ioctl_info *)arg;
1367
1368	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1369}
1370
1371/*
1372 * Remove an initiator by port number and initiator ID.
1373 * Returns 0 for success, -1 for failure.
1374 */
1375int
1376ctl_remove_initiator(struct ctl_port *port, int iid)
1377{
1378	struct ctl_softc *softc = control_softc;
1379
1380	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1381
1382	if (iid > CTL_MAX_INIT_PER_PORT) {
1383		printf("%s: initiator ID %u > maximun %u!\n",
1384		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1385		return (-1);
1386	}
1387
1388	mtx_lock(&softc->ctl_lock);
1389	port->wwpn_iid[iid].in_use--;
1390	port->wwpn_iid[iid].last_use = time_uptime;
1391	mtx_unlock(&softc->ctl_lock);
1392
1393	return (0);
1394}
1395
1396/*
1397 * Add an initiator to the initiator map.
1398 * Returns iid for success, < 0 for failure.
1399 */
1400int
1401ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1402{
1403	struct ctl_softc *softc = control_softc;
1404	time_t best_time;
1405	int i, best;
1406
1407	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1408
1409	if (iid >= CTL_MAX_INIT_PER_PORT) {
1410		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1411		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1412		free(name, M_CTL);
1413		return (-1);
1414	}
1415
1416	mtx_lock(&softc->ctl_lock);
1417
1418	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1419		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1420			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1421				iid = i;
1422				break;
1423			}
1424			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1425			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1426				iid = i;
1427				break;
1428			}
1429		}
1430	}
1431
1432	if (iid < 0) {
1433		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1434			if (port->wwpn_iid[i].in_use == 0 &&
1435			    port->wwpn_iid[i].wwpn == 0 &&
1436			    port->wwpn_iid[i].name == NULL) {
1437				iid = i;
1438				break;
1439			}
1440		}
1441	}
1442
1443	if (iid < 0) {
1444		best = -1;
1445		best_time = INT32_MAX;
1446		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1447			if (port->wwpn_iid[i].in_use == 0) {
1448				if (port->wwpn_iid[i].last_use < best_time) {
1449					best = i;
1450					best_time = port->wwpn_iid[i].last_use;
1451				}
1452			}
1453		}
1454		iid = best;
1455	}
1456
1457	if (iid < 0) {
1458		mtx_unlock(&softc->ctl_lock);
1459		free(name, M_CTL);
1460		return (-2);
1461	}
1462
1463	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1464		/*
1465		 * This is not an error yet.
1466		 */
1467		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1468#if 0
1469			printf("%s: port %d iid %u WWPN %#jx arrived"
1470			    " again\n", __func__, port->targ_port,
1471			    iid, (uintmax_t)wwpn);
1472#endif
1473			goto take;
1474		}
1475		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1476		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1477#if 0
1478			printf("%s: port %d iid %u name '%s' arrived"
1479			    " again\n", __func__, port->targ_port,
1480			    iid, name);
1481#endif
1482			goto take;
1483		}
1484
1485		/*
1486		 * This is an error, but what do we do about it?  The
1487		 * driver is telling us we have a new WWPN for this
1488		 * initiator ID, so we pretty much need to use it.
1489		 */
1490		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1491		    " but WWPN %#jx '%s' is still at that address\n",
1492		    __func__, port->targ_port, iid, wwpn, name,
1493		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1494		    port->wwpn_iid[iid].name);
1495
1496		/*
1497		 * XXX KDM clear have_ca and ua_pending on each LUN for
1498		 * this initiator.
1499		 */
1500	}
1501take:
1502	free(port->wwpn_iid[iid].name, M_CTL);
1503	port->wwpn_iid[iid].name = name;
1504	port->wwpn_iid[iid].wwpn = wwpn;
1505	port->wwpn_iid[iid].in_use++;
1506	mtx_unlock(&softc->ctl_lock);
1507
1508	return (iid);
1509}
1510
1511static int
1512ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1513{
1514	int len;
1515
1516	switch (port->port_type) {
1517	case CTL_PORT_FC:
1518	{
1519		struct scsi_transportid_fcp *id =
1520		    (struct scsi_transportid_fcp *)buf;
1521		if (port->wwpn_iid[iid].wwpn == 0)
1522			return (0);
1523		memset(id, 0, sizeof(*id));
1524		id->format_protocol = SCSI_PROTO_FC;
1525		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1526		return (sizeof(*id));
1527	}
1528	case CTL_PORT_ISCSI:
1529	{
1530		struct scsi_transportid_iscsi_port *id =
1531		    (struct scsi_transportid_iscsi_port *)buf;
1532		if (port->wwpn_iid[iid].name == NULL)
1533			return (0);
1534		memset(id, 0, 256);
1535		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1536		    SCSI_PROTO_ISCSI;
1537		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1538		len = roundup2(min(len, 252), 4);
1539		scsi_ulto2b(len, id->additional_length);
1540		return (sizeof(*id) + len);
1541	}
1542	case CTL_PORT_SAS:
1543	{
1544		struct scsi_transportid_sas *id =
1545		    (struct scsi_transportid_sas *)buf;
1546		if (port->wwpn_iid[iid].wwpn == 0)
1547			return (0);
1548		memset(id, 0, sizeof(*id));
1549		id->format_protocol = SCSI_PROTO_SAS;
1550		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1551		return (sizeof(*id));
1552	}
1553	default:
1554	{
1555		struct scsi_transportid_spi *id =
1556		    (struct scsi_transportid_spi *)buf;
1557		memset(id, 0, sizeof(*id));
1558		id->format_protocol = SCSI_PROTO_SPI;
1559		scsi_ulto2b(iid, id->scsi_addr);
1560		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1561		return (sizeof(*id));
1562	}
1563	}
1564}
1565
1566static int
1567ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1568{
1569	return (0);
1570}
1571
1572static int
1573ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1574{
1575	return (0);
1576}
1577
1578/*
1579 * Data movement routine for the CTL ioctl frontend port.
1580 */
1581static int
1582ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1583{
1584	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1585	struct ctl_sg_entry ext_entry, kern_entry;
1586	int ext_sglen, ext_sg_entries, kern_sg_entries;
1587	int ext_sg_start, ext_offset;
1588	int len_to_copy, len_copied;
1589	int kern_watermark, ext_watermark;
1590	int ext_sglist_malloced;
1591	int i, j;
1592
1593	ext_sglist_malloced = 0;
1594	ext_sg_start = 0;
1595	ext_offset = 0;
1596
1597	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1598
1599	/*
1600	 * If this flag is set, fake the data transfer.
1601	 */
1602	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1603		ctsio->ext_data_filled = ctsio->ext_data_len;
1604		goto bailout;
1605	}
1606
1607	/*
1608	 * To simplify things here, if we have a single buffer, stick it in
1609	 * a S/G entry and just make it a single entry S/G list.
1610	 */
1611	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1612		int len_seen;
1613
1614		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1615
1616		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1617							   M_WAITOK);
1618		ext_sglist_malloced = 1;
1619		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1620				   ext_sglen) != 0) {
1621			ctl_set_internal_failure(ctsio,
1622						 /*sks_valid*/ 0,
1623						 /*retry_count*/ 0);
1624			goto bailout;
1625		}
1626		ext_sg_entries = ctsio->ext_sg_entries;
1627		len_seen = 0;
1628		for (i = 0; i < ext_sg_entries; i++) {
1629			if ((len_seen + ext_sglist[i].len) >=
1630			     ctsio->ext_data_filled) {
1631				ext_sg_start = i;
1632				ext_offset = ctsio->ext_data_filled - len_seen;
1633				break;
1634			}
1635			len_seen += ext_sglist[i].len;
1636		}
1637	} else {
1638		ext_sglist = &ext_entry;
1639		ext_sglist->addr = ctsio->ext_data_ptr;
1640		ext_sglist->len = ctsio->ext_data_len;
1641		ext_sg_entries = 1;
1642		ext_sg_start = 0;
1643		ext_offset = ctsio->ext_data_filled;
1644	}
1645
1646	if (ctsio->kern_sg_entries > 0) {
1647		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1648		kern_sg_entries = ctsio->kern_sg_entries;
1649	} else {
1650		kern_sglist = &kern_entry;
1651		kern_sglist->addr = ctsio->kern_data_ptr;
1652		kern_sglist->len = ctsio->kern_data_len;
1653		kern_sg_entries = 1;
1654	}
1655
1656
1657	kern_watermark = 0;
1658	ext_watermark = ext_offset;
1659	len_copied = 0;
1660	for (i = ext_sg_start, j = 0;
1661	     i < ext_sg_entries && j < kern_sg_entries;) {
1662		uint8_t *ext_ptr, *kern_ptr;
1663
1664		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1665				      kern_sglist[j].len - kern_watermark);
1666
1667		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1668		ext_ptr = ext_ptr + ext_watermark;
1669		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1670			/*
1671			 * XXX KDM fix this!
1672			 */
1673			panic("need to implement bus address support");
1674#if 0
1675			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1676#endif
1677		} else
1678			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1679		kern_ptr = kern_ptr + kern_watermark;
1680
1681		kern_watermark += len_to_copy;
1682		ext_watermark += len_to_copy;
1683
1684		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1685		     CTL_FLAG_DATA_IN) {
1686			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1687					 "bytes to user\n", len_to_copy));
1688			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1689					 "to %p\n", kern_ptr, ext_ptr));
1690			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1691				ctl_set_internal_failure(ctsio,
1692							 /*sks_valid*/ 0,
1693							 /*retry_count*/ 0);
1694				goto bailout;
1695			}
1696		} else {
1697			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1698					 "bytes from user\n", len_to_copy));
1699			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1700					 "to %p\n", ext_ptr, kern_ptr));
1701			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1702				ctl_set_internal_failure(ctsio,
1703							 /*sks_valid*/ 0,
1704							 /*retry_count*/0);
1705				goto bailout;
1706			}
1707		}
1708
1709		len_copied += len_to_copy;
1710
1711		if (ext_sglist[i].len == ext_watermark) {
1712			i++;
1713			ext_watermark = 0;
1714		}
1715
1716		if (kern_sglist[j].len == kern_watermark) {
1717			j++;
1718			kern_watermark = 0;
1719		}
1720	}
1721
1722	ctsio->ext_data_filled += len_copied;
1723
1724	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1725			 "kern_sg_entries: %d\n", ext_sg_entries,
1726			 kern_sg_entries));
1727	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1728			 "kern_data_len = %d\n", ctsio->ext_data_len,
1729			 ctsio->kern_data_len));
1730
1731
1732	/* XXX KDM set residual?? */
1733bailout:
1734
1735	if (ext_sglist_malloced != 0)
1736		free(ext_sglist, M_CTL);
1737
1738	return (CTL_RETVAL_COMPLETE);
1739}
1740
1741/*
1742 * Serialize a command that went down the "wrong" side, and so was sent to
1743 * this controller for execution.  The logic is a little different than the
1744 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1745 * sent back to the other side, but in the success case, we execute the
1746 * command on this side (XFER mode) or tell the other side to execute it
1747 * (SER_ONLY mode).
1748 */
1749static int
1750ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1751{
1752	struct ctl_softc *ctl_softc;
1753	union ctl_ha_msg msg_info;
1754	struct ctl_lun *lun;
1755	int retval = 0;
1756	uint32_t targ_lun;
1757
1758	ctl_softc = control_softc;
1759
1760	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1761	lun = ctl_softc->ctl_luns[targ_lun];
1762	if (lun==NULL)
1763	{
1764		/*
1765		 * Why isn't LUN defined? The other side wouldn't
1766		 * send a cmd if the LUN is undefined.
1767		 */
1768		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1769
1770		/* "Logical unit not supported" */
1771		ctl_set_sense_data(&msg_info.scsi.sense_data,
1772				   lun,
1773				   /*sense_format*/SSD_TYPE_NONE,
1774				   /*current_error*/ 1,
1775				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1776				   /*asc*/ 0x25,
1777				   /*ascq*/ 0x00,
1778				   SSD_ELEM_NONE);
1779
1780		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1781		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1782		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1783		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1784		msg_info.hdr.serializing_sc = NULL;
1785		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1786	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1787				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1788		}
1789		return(1);
1790
1791	}
1792
1793	mtx_lock(&lun->lun_lock);
1794    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1795
1796	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1797		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1798		 ooa_links))) {
1799	case CTL_ACTION_BLOCK:
1800		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1801		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1802				  blocked_links);
1803		break;
1804	case CTL_ACTION_PASS:
1805	case CTL_ACTION_SKIP:
1806		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1807			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1808			ctl_enqueue_rtr((union ctl_io *)ctsio);
1809		} else {
1810
1811			/* send msg back to other side */
1812			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1813			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1814			msg_info.hdr.msg_type = CTL_MSG_R2R;
1815#if 0
1816			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1817#endif
1818		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1819			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1820			}
1821		}
1822		break;
1823	case CTL_ACTION_OVERLAP:
1824		/* OVERLAPPED COMMANDS ATTEMPTED */
1825		ctl_set_sense_data(&msg_info.scsi.sense_data,
1826				   lun,
1827				   /*sense_format*/SSD_TYPE_NONE,
1828				   /*current_error*/ 1,
1829				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1830				   /*asc*/ 0x4E,
1831				   /*ascq*/ 0x00,
1832				   SSD_ELEM_NONE);
1833
1834		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1835		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1836		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1837		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1838		msg_info.hdr.serializing_sc = NULL;
1839		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1840#if 0
1841		printf("BAD JUJU:Major Bummer Overlap\n");
1842#endif
1843		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1844		retval = 1;
1845		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1846		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1847		}
1848		break;
1849	case CTL_ACTION_OVERLAP_TAG:
1850		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1851		ctl_set_sense_data(&msg_info.scsi.sense_data,
1852				   lun,
1853				   /*sense_format*/SSD_TYPE_NONE,
1854				   /*current_error*/ 1,
1855				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1856				   /*asc*/ 0x4D,
1857				   /*ascq*/ ctsio->tag_num & 0xff,
1858				   SSD_ELEM_NONE);
1859
1860		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1861		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1862		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1863		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1864		msg_info.hdr.serializing_sc = NULL;
1865		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1866#if 0
1867		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1868#endif
1869		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1870		retval = 1;
1871		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873		}
1874		break;
1875	case CTL_ACTION_ERROR:
1876	default:
1877		/* "Internal target failure" */
1878		ctl_set_sense_data(&msg_info.scsi.sense_data,
1879				   lun,
1880				   /*sense_format*/SSD_TYPE_NONE,
1881				   /*current_error*/ 1,
1882				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1883				   /*asc*/ 0x44,
1884				   /*ascq*/ 0x00,
1885				   SSD_ELEM_NONE);
1886
1887		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1888		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1889		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1890		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1891		msg_info.hdr.serializing_sc = NULL;
1892		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1893#if 0
1894		printf("BAD JUJU:Major Bummer HW Error\n");
1895#endif
1896		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1897		retval = 1;
1898		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1899		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1900		}
1901		break;
1902	}
1903	mtx_unlock(&lun->lun_lock);
1904	return (retval);
1905}
1906
1907static int
1908ctl_ioctl_submit_wait(union ctl_io *io)
1909{
1910	struct ctl_fe_ioctl_params params;
1911	ctl_fe_ioctl_state last_state;
1912	int done, retval;
1913
1914	retval = 0;
1915
1916	bzero(&params, sizeof(params));
1917
1918	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1919	cv_init(&params.sem, "ctlioccv");
1920	params.state = CTL_IOCTL_INPROG;
1921	last_state = params.state;
1922
1923	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1924
1925	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1926
1927	/* This shouldn't happen */
1928	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1929		return (retval);
1930
1931	done = 0;
1932
1933	do {
1934		mtx_lock(&params.ioctl_mtx);
1935		/*
1936		 * Check the state here, and don't sleep if the state has
1937		 * already changed (i.e. wakeup has already occured, but we
1938		 * weren't waiting yet).
1939		 */
1940		if (params.state == last_state) {
1941			/* XXX KDM cv_wait_sig instead? */
1942			cv_wait(&params.sem, &params.ioctl_mtx);
1943		}
1944		last_state = params.state;
1945
1946		switch (params.state) {
1947		case CTL_IOCTL_INPROG:
1948			/* Why did we wake up? */
1949			/* XXX KDM error here? */
1950			mtx_unlock(&params.ioctl_mtx);
1951			break;
1952		case CTL_IOCTL_DATAMOVE:
1953			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1954
1955			/*
1956			 * change last_state back to INPROG to avoid
1957			 * deadlock on subsequent data moves.
1958			 */
1959			params.state = last_state = CTL_IOCTL_INPROG;
1960
1961			mtx_unlock(&params.ioctl_mtx);
1962			ctl_ioctl_do_datamove(&io->scsiio);
1963			/*
1964			 * Note that in some cases, most notably writes,
1965			 * this will queue the I/O and call us back later.
1966			 * In other cases, generally reads, this routine
1967			 * will immediately call back and wake us up,
1968			 * probably using our own context.
1969			 */
1970			io->scsiio.be_move_done(io);
1971			break;
1972		case CTL_IOCTL_DONE:
1973			mtx_unlock(&params.ioctl_mtx);
1974			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1975			done = 1;
1976			break;
1977		default:
1978			mtx_unlock(&params.ioctl_mtx);
1979			/* XXX KDM error here? */
1980			break;
1981		}
1982	} while (done == 0);
1983
1984	mtx_destroy(&params.ioctl_mtx);
1985	cv_destroy(&params.sem);
1986
1987	return (CTL_RETVAL_COMPLETE);
1988}
1989
1990static void
1991ctl_ioctl_datamove(union ctl_io *io)
1992{
1993	struct ctl_fe_ioctl_params *params;
1994
1995	params = (struct ctl_fe_ioctl_params *)
1996		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1997
1998	mtx_lock(&params->ioctl_mtx);
1999	params->state = CTL_IOCTL_DATAMOVE;
2000	cv_broadcast(&params->sem);
2001	mtx_unlock(&params->ioctl_mtx);
2002}
2003
2004static void
2005ctl_ioctl_done(union ctl_io *io)
2006{
2007	struct ctl_fe_ioctl_params *params;
2008
2009	params = (struct ctl_fe_ioctl_params *)
2010		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2011
2012	mtx_lock(&params->ioctl_mtx);
2013	params->state = CTL_IOCTL_DONE;
2014	cv_broadcast(&params->sem);
2015	mtx_unlock(&params->ioctl_mtx);
2016}
2017
2018static void
2019ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2020{
2021	struct ctl_fe_ioctl_startstop_info *sd_info;
2022
2023	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2024
2025	sd_info->hs_info.status = metatask->status;
2026	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2027	sd_info->hs_info.luns_complete =
2028		metatask->taskinfo.startstop.luns_complete;
2029	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2030
2031	cv_broadcast(&sd_info->sem);
2032}
2033
2034static void
2035ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2036{
2037	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2038
2039	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2040
2041	mtx_lock(fe_bbr_info->lock);
2042	fe_bbr_info->bbr_info->status = metatask->status;
2043	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2044	fe_bbr_info->wakeup_done = 1;
2045	mtx_unlock(fe_bbr_info->lock);
2046
2047	cv_broadcast(&fe_bbr_info->sem);
2048}
2049
2050/*
2051 * Returns 0 for success, errno for failure.
2052 */
2053static int
2054ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2055		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2056{
2057	union ctl_io *io;
2058	int retval;
2059
2060	retval = 0;
2061
2062	mtx_lock(&lun->lun_lock);
2063	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2064	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2065	     ooa_links)) {
2066		struct ctl_ooa_entry *entry;
2067
2068		/*
2069		 * If we've got more than we can fit, just count the
2070		 * remaining entries.
2071		 */
2072		if (*cur_fill_num >= ooa_hdr->alloc_num)
2073			continue;
2074
2075		entry = &kern_entries[*cur_fill_num];
2076
2077		entry->tag_num = io->scsiio.tag_num;
2078		entry->lun_num = lun->lun;
2079#ifdef CTL_TIME_IO
2080		entry->start_bt = io->io_hdr.start_bt;
2081#endif
2082		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2083		entry->cdb_len = io->scsiio.cdb_len;
2084		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2085			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2086
2087		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2088			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2089
2090		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2091			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2092
2093		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2094			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2095
2096		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2097			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2098	}
2099	mtx_unlock(&lun->lun_lock);
2100
2101	return (retval);
2102}
2103
2104static void *
2105ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2106		 size_t error_str_len)
2107{
2108	void *kptr;
2109
2110	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2111
2112	if (copyin(user_addr, kptr, len) != 0) {
2113		snprintf(error_str, error_str_len, "Error copying %d bytes "
2114			 "from user address %p to kernel address %p", len,
2115			 user_addr, kptr);
2116		free(kptr, M_CTL);
2117		return (NULL);
2118	}
2119
2120	return (kptr);
2121}
2122
2123static void
2124ctl_free_args(int num_args, struct ctl_be_arg *args)
2125{
2126	int i;
2127
2128	if (args == NULL)
2129		return;
2130
2131	for (i = 0; i < num_args; i++) {
2132		free(args[i].kname, M_CTL);
2133		free(args[i].kvalue, M_CTL);
2134	}
2135
2136	free(args, M_CTL);
2137}
2138
2139static struct ctl_be_arg *
2140ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2141		char *error_str, size_t error_str_len)
2142{
2143	struct ctl_be_arg *args;
2144	int i;
2145
2146	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2147				error_str, error_str_len);
2148
2149	if (args == NULL)
2150		goto bailout;
2151
2152	for (i = 0; i < num_args; i++) {
2153		args[i].kname = NULL;
2154		args[i].kvalue = NULL;
2155	}
2156
2157	for (i = 0; i < num_args; i++) {
2158		uint8_t *tmpptr;
2159
2160		args[i].kname = ctl_copyin_alloc(args[i].name,
2161			args[i].namelen, error_str, error_str_len);
2162		if (args[i].kname == NULL)
2163			goto bailout;
2164
2165		if (args[i].kname[args[i].namelen - 1] != '\0') {
2166			snprintf(error_str, error_str_len, "Argument %d "
2167				 "name is not NUL-terminated", i);
2168			goto bailout;
2169		}
2170
2171		if (args[i].flags & CTL_BEARG_RD) {
2172			tmpptr = ctl_copyin_alloc(args[i].value,
2173				args[i].vallen, error_str, error_str_len);
2174			if (tmpptr == NULL)
2175				goto bailout;
2176			if ((args[i].flags & CTL_BEARG_ASCII)
2177			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2178				snprintf(error_str, error_str_len, "Argument "
2179				    "%d value is not NUL-terminated", i);
2180				goto bailout;
2181			}
2182			args[i].kvalue = tmpptr;
2183		} else {
2184			args[i].kvalue = malloc(args[i].vallen,
2185			    M_CTL, M_WAITOK | M_ZERO);
2186		}
2187	}
2188
2189	return (args);
2190bailout:
2191
2192	ctl_free_args(num_args, args);
2193
2194	return (NULL);
2195}
2196
2197static void
2198ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2199{
2200	int i;
2201
2202	for (i = 0; i < num_args; i++) {
2203		if (args[i].flags & CTL_BEARG_WR)
2204			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2205	}
2206}
2207
2208/*
2209 * Escape characters that are illegal or not recommended in XML.
2210 */
2211int
2212ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2213{
2214	int retval;
2215
2216	retval = 0;
2217
2218	for (; *str; str++) {
2219		switch (*str) {
2220		case '&':
2221			retval = sbuf_printf(sb, "&amp;");
2222			break;
2223		case '>':
2224			retval = sbuf_printf(sb, "&gt;");
2225			break;
2226		case '<':
2227			retval = sbuf_printf(sb, "&lt;");
2228			break;
2229		default:
2230			retval = sbuf_putc(sb, *str);
2231			break;
2232		}
2233
2234		if (retval != 0)
2235			break;
2236
2237	}
2238
2239	return (retval);
2240}
2241
2242static int
2243ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2244	  struct thread *td)
2245{
2246	struct ctl_softc *softc;
2247	int retval;
2248
2249	softc = control_softc;
2250
2251	retval = 0;
2252
2253	switch (cmd) {
2254	case CTL_IO: {
2255		union ctl_io *io;
2256		void *pool_tmp;
2257
2258		/*
2259		 * If we haven't been "enabled", don't allow any SCSI I/O
2260		 * to this FETD.
2261		 */
2262		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2263			retval = EPERM;
2264			break;
2265		}
2266
2267		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2268		if (io == NULL) {
2269			printf("ctl_ioctl: can't allocate ctl_io!\n");
2270			retval = ENOSPC;
2271			break;
2272		}
2273
2274		/*
2275		 * Need to save the pool reference so it doesn't get
2276		 * spammed by the user's ctl_io.
2277		 */
2278		pool_tmp = io->io_hdr.pool;
2279
2280		memcpy(io, (void *)addr, sizeof(*io));
2281
2282		io->io_hdr.pool = pool_tmp;
2283		/*
2284		 * No status yet, so make sure the status is set properly.
2285		 */
2286		io->io_hdr.status = CTL_STATUS_NONE;
2287
2288		/*
2289		 * The user sets the initiator ID, target and LUN IDs.
2290		 */
2291		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2292		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2293		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2294		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2295			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2296
2297		retval = ctl_ioctl_submit_wait(io);
2298
2299		if (retval != 0) {
2300			ctl_free_io(io);
2301			break;
2302		}
2303
2304		memcpy((void *)addr, io, sizeof(*io));
2305
2306		/* return this to our pool */
2307		ctl_free_io(io);
2308
2309		break;
2310	}
2311	case CTL_ENABLE_PORT:
2312	case CTL_DISABLE_PORT:
2313	case CTL_SET_PORT_WWNS: {
2314		struct ctl_port *port;
2315		struct ctl_port_entry *entry;
2316
2317		entry = (struct ctl_port_entry *)addr;
2318
2319		mtx_lock(&softc->ctl_lock);
2320		STAILQ_FOREACH(port, &softc->port_list, links) {
2321			int action, done;
2322
2323			action = 0;
2324			done = 0;
2325
2326			if ((entry->port_type == CTL_PORT_NONE)
2327			 && (entry->targ_port == port->targ_port)) {
2328				/*
2329				 * If the user only wants to enable or
2330				 * disable or set WWNs on a specific port,
2331				 * do the operation and we're done.
2332				 */
2333				action = 1;
2334				done = 1;
2335			} else if (entry->port_type & port->port_type) {
2336				/*
2337				 * Compare the user's type mask with the
2338				 * particular frontend type to see if we
2339				 * have a match.
2340				 */
2341				action = 1;
2342				done = 0;
2343
2344				/*
2345				 * Make sure the user isn't trying to set
2346				 * WWNs on multiple ports at the same time.
2347				 */
2348				if (cmd == CTL_SET_PORT_WWNS) {
2349					printf("%s: Can't set WWNs on "
2350					       "multiple ports\n", __func__);
2351					retval = EINVAL;
2352					break;
2353				}
2354			}
2355			if (action != 0) {
2356				/*
2357				 * XXX KDM we have to drop the lock here,
2358				 * because the online/offline operations
2359				 * can potentially block.  We need to
2360				 * reference count the frontends so they
2361				 * can't go away,
2362				 */
2363				mtx_unlock(&softc->ctl_lock);
2364
2365				if (cmd == CTL_ENABLE_PORT) {
2366					struct ctl_lun *lun;
2367
2368					STAILQ_FOREACH(lun, &softc->lun_list,
2369						       links) {
2370						port->lun_enable(port->targ_lun_arg,
2371						    lun->target,
2372						    lun->lun);
2373					}
2374
2375					ctl_port_online(port);
2376				} else if (cmd == CTL_DISABLE_PORT) {
2377					struct ctl_lun *lun;
2378
2379					ctl_port_offline(port);
2380
2381					STAILQ_FOREACH(lun, &softc->lun_list,
2382						       links) {
2383						port->lun_disable(
2384						    port->targ_lun_arg,
2385						    lun->target,
2386						    lun->lun);
2387					}
2388				}
2389
2390				mtx_lock(&softc->ctl_lock);
2391
2392				if (cmd == CTL_SET_PORT_WWNS)
2393					ctl_port_set_wwns(port,
2394					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2395					    1 : 0, entry->wwnn,
2396					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2397					    1 : 0, entry->wwpn);
2398			}
2399			if (done != 0)
2400				break;
2401		}
2402		mtx_unlock(&softc->ctl_lock);
2403		break;
2404	}
2405	case CTL_GET_PORT_LIST: {
2406		struct ctl_port *port;
2407		struct ctl_port_list *list;
2408		int i;
2409
2410		list = (struct ctl_port_list *)addr;
2411
2412		if (list->alloc_len != (list->alloc_num *
2413		    sizeof(struct ctl_port_entry))) {
2414			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2415			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2416			       "%zu\n", __func__, list->alloc_len,
2417			       list->alloc_num, sizeof(struct ctl_port_entry));
2418			retval = EINVAL;
2419			break;
2420		}
2421		list->fill_len = 0;
2422		list->fill_num = 0;
2423		list->dropped_num = 0;
2424		i = 0;
2425		mtx_lock(&softc->ctl_lock);
2426		STAILQ_FOREACH(port, &softc->port_list, links) {
2427			struct ctl_port_entry entry, *list_entry;
2428
2429			if (list->fill_num >= list->alloc_num) {
2430				list->dropped_num++;
2431				continue;
2432			}
2433
2434			entry.port_type = port->port_type;
2435			strlcpy(entry.port_name, port->port_name,
2436				sizeof(entry.port_name));
2437			entry.targ_port = port->targ_port;
2438			entry.physical_port = port->physical_port;
2439			entry.virtual_port = port->virtual_port;
2440			entry.wwnn = port->wwnn;
2441			entry.wwpn = port->wwpn;
2442			if (port->status & CTL_PORT_STATUS_ONLINE)
2443				entry.online = 1;
2444			else
2445				entry.online = 0;
2446
2447			list_entry = &list->entries[i];
2448
2449			retval = copyout(&entry, list_entry, sizeof(entry));
2450			if (retval != 0) {
2451				printf("%s: CTL_GET_PORT_LIST: copyout "
2452				       "returned %d\n", __func__, retval);
2453				break;
2454			}
2455			i++;
2456			list->fill_num++;
2457			list->fill_len += sizeof(entry);
2458		}
2459		mtx_unlock(&softc->ctl_lock);
2460
2461		/*
2462		 * If this is non-zero, we had a copyout fault, so there's
2463		 * probably no point in attempting to set the status inside
2464		 * the structure.
2465		 */
2466		if (retval != 0)
2467			break;
2468
2469		if (list->dropped_num > 0)
2470			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2471		else
2472			list->status = CTL_PORT_LIST_OK;
2473		break;
2474	}
2475	case CTL_DUMP_OOA: {
2476		struct ctl_lun *lun;
2477		union ctl_io *io;
2478		char printbuf[128];
2479		struct sbuf sb;
2480
2481		mtx_lock(&softc->ctl_lock);
2482		printf("Dumping OOA queues:\n");
2483		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2484			mtx_lock(&lun->lun_lock);
2485			for (io = (union ctl_io *)TAILQ_FIRST(
2486			     &lun->ooa_queue); io != NULL;
2487			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2488			     ooa_links)) {
2489				sbuf_new(&sb, printbuf, sizeof(printbuf),
2490					 SBUF_FIXEDLEN);
2491				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2492					    (intmax_t)lun->lun,
2493					    io->scsiio.tag_num,
2494					    (io->io_hdr.flags &
2495					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2496					    (io->io_hdr.flags &
2497					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2498					    (io->io_hdr.flags &
2499					    CTL_FLAG_ABORT) ? " ABORT" : "",
2500			                    (io->io_hdr.flags &
2501		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2502				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2503				sbuf_finish(&sb);
2504				printf("%s\n", sbuf_data(&sb));
2505			}
2506			mtx_unlock(&lun->lun_lock);
2507		}
2508		printf("OOA queues dump done\n");
2509		mtx_unlock(&softc->ctl_lock);
2510		break;
2511	}
2512	case CTL_GET_OOA: {
2513		struct ctl_lun *lun;
2514		struct ctl_ooa *ooa_hdr;
2515		struct ctl_ooa_entry *entries;
2516		uint32_t cur_fill_num;
2517
2518		ooa_hdr = (struct ctl_ooa *)addr;
2519
2520		if ((ooa_hdr->alloc_len == 0)
2521		 || (ooa_hdr->alloc_num == 0)) {
2522			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2523			       "must be non-zero\n", __func__,
2524			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2525			retval = EINVAL;
2526			break;
2527		}
2528
2529		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2530		    sizeof(struct ctl_ooa_entry))) {
2531			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2532			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2533			       __func__, ooa_hdr->alloc_len,
2534			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2535			retval = EINVAL;
2536			break;
2537		}
2538
2539		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2540		if (entries == NULL) {
2541			printf("%s: could not allocate %d bytes for OOA "
2542			       "dump\n", __func__, ooa_hdr->alloc_len);
2543			retval = ENOMEM;
2544			break;
2545		}
2546
2547		mtx_lock(&softc->ctl_lock);
2548		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2549		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2550		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2551			mtx_unlock(&softc->ctl_lock);
2552			free(entries, M_CTL);
2553			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2554			       __func__, (uintmax_t)ooa_hdr->lun_num);
2555			retval = EINVAL;
2556			break;
2557		}
2558
2559		cur_fill_num = 0;
2560
2561		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2562			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2563				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2564					ooa_hdr, entries);
2565				if (retval != 0)
2566					break;
2567			}
2568			if (retval != 0) {
2569				mtx_unlock(&softc->ctl_lock);
2570				free(entries, M_CTL);
2571				break;
2572			}
2573		} else {
2574			lun = softc->ctl_luns[ooa_hdr->lun_num];
2575
2576			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2577						    entries);
2578		}
2579		mtx_unlock(&softc->ctl_lock);
2580
2581		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2582		ooa_hdr->fill_len = ooa_hdr->fill_num *
2583			sizeof(struct ctl_ooa_entry);
2584		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2585		if (retval != 0) {
2586			printf("%s: error copying out %d bytes for OOA dump\n",
2587			       __func__, ooa_hdr->fill_len);
2588		}
2589
2590		getbintime(&ooa_hdr->cur_bt);
2591
2592		if (cur_fill_num > ooa_hdr->alloc_num) {
2593			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2594			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2595		} else {
2596			ooa_hdr->dropped_num = 0;
2597			ooa_hdr->status = CTL_OOA_OK;
2598		}
2599
2600		free(entries, M_CTL);
2601		break;
2602	}
2603	case CTL_CHECK_OOA: {
2604		union ctl_io *io;
2605		struct ctl_lun *lun;
2606		struct ctl_ooa_info *ooa_info;
2607
2608
2609		ooa_info = (struct ctl_ooa_info *)addr;
2610
2611		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2612			ooa_info->status = CTL_OOA_INVALID_LUN;
2613			break;
2614		}
2615		mtx_lock(&softc->ctl_lock);
2616		lun = softc->ctl_luns[ooa_info->lun_id];
2617		if (lun == NULL) {
2618			mtx_unlock(&softc->ctl_lock);
2619			ooa_info->status = CTL_OOA_INVALID_LUN;
2620			break;
2621		}
2622		mtx_lock(&lun->lun_lock);
2623		mtx_unlock(&softc->ctl_lock);
2624		ooa_info->num_entries = 0;
2625		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2626		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2627		     &io->io_hdr, ooa_links)) {
2628			ooa_info->num_entries++;
2629		}
2630		mtx_unlock(&lun->lun_lock);
2631
2632		ooa_info->status = CTL_OOA_SUCCESS;
2633
2634		break;
2635	}
2636	case CTL_HARD_START:
2637	case CTL_HARD_STOP: {
2638		struct ctl_fe_ioctl_startstop_info ss_info;
2639		struct cfi_metatask *metatask;
2640		struct mtx hs_mtx;
2641
2642		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2643
2644		cv_init(&ss_info.sem, "hard start/stop cv" );
2645
2646		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2647		if (metatask == NULL) {
2648			retval = ENOMEM;
2649			mtx_destroy(&hs_mtx);
2650			break;
2651		}
2652
2653		if (cmd == CTL_HARD_START)
2654			metatask->tasktype = CFI_TASK_STARTUP;
2655		else
2656			metatask->tasktype = CFI_TASK_SHUTDOWN;
2657
2658		metatask->callback = ctl_ioctl_hard_startstop_callback;
2659		metatask->callback_arg = &ss_info;
2660
2661		cfi_action(metatask);
2662
2663		/* Wait for the callback */
2664		mtx_lock(&hs_mtx);
2665		cv_wait_sig(&ss_info.sem, &hs_mtx);
2666		mtx_unlock(&hs_mtx);
2667
2668		/*
2669		 * All information has been copied from the metatask by the
2670		 * time cv_broadcast() is called, so we free the metatask here.
2671		 */
2672		cfi_free_metatask(metatask);
2673
2674		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2675
2676		mtx_destroy(&hs_mtx);
2677		break;
2678	}
2679	case CTL_BBRREAD: {
2680		struct ctl_bbrread_info *bbr_info;
2681		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2682		struct mtx bbr_mtx;
2683		struct cfi_metatask *metatask;
2684
2685		bbr_info = (struct ctl_bbrread_info *)addr;
2686
2687		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2688
2689		bzero(&bbr_mtx, sizeof(bbr_mtx));
2690		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2691
2692		fe_bbr_info.bbr_info = bbr_info;
2693		fe_bbr_info.lock = &bbr_mtx;
2694
2695		cv_init(&fe_bbr_info.sem, "BBR read cv");
2696		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2697
2698		if (metatask == NULL) {
2699			mtx_destroy(&bbr_mtx);
2700			cv_destroy(&fe_bbr_info.sem);
2701			retval = ENOMEM;
2702			break;
2703		}
2704		metatask->tasktype = CFI_TASK_BBRREAD;
2705		metatask->callback = ctl_ioctl_bbrread_callback;
2706		metatask->callback_arg = &fe_bbr_info;
2707		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2708		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2709		metatask->taskinfo.bbrread.len = bbr_info->len;
2710
2711		cfi_action(metatask);
2712
2713		mtx_lock(&bbr_mtx);
2714		while (fe_bbr_info.wakeup_done == 0)
2715			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2716		mtx_unlock(&bbr_mtx);
2717
2718		bbr_info->status = metatask->status;
2719		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2720		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2721		memcpy(&bbr_info->sense_data,
2722		       &metatask->taskinfo.bbrread.sense_data,
2723		       ctl_min(sizeof(bbr_info->sense_data),
2724			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2725
2726		cfi_free_metatask(metatask);
2727
2728		mtx_destroy(&bbr_mtx);
2729		cv_destroy(&fe_bbr_info.sem);
2730
2731		break;
2732	}
2733	case CTL_DELAY_IO: {
2734		struct ctl_io_delay_info *delay_info;
2735#ifdef CTL_IO_DELAY
2736		struct ctl_lun *lun;
2737#endif /* CTL_IO_DELAY */
2738
2739		delay_info = (struct ctl_io_delay_info *)addr;
2740
2741#ifdef CTL_IO_DELAY
2742		mtx_lock(&softc->ctl_lock);
2743
2744		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2745		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2746			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2747		} else {
2748			lun = softc->ctl_luns[delay_info->lun_id];
2749			mtx_lock(&lun->lun_lock);
2750
2751			delay_info->status = CTL_DELAY_STATUS_OK;
2752
2753			switch (delay_info->delay_type) {
2754			case CTL_DELAY_TYPE_CONT:
2755				break;
2756			case CTL_DELAY_TYPE_ONESHOT:
2757				break;
2758			default:
2759				delay_info->status =
2760					CTL_DELAY_STATUS_INVALID_TYPE;
2761				break;
2762			}
2763
2764			switch (delay_info->delay_loc) {
2765			case CTL_DELAY_LOC_DATAMOVE:
2766				lun->delay_info.datamove_type =
2767					delay_info->delay_type;
2768				lun->delay_info.datamove_delay =
2769					delay_info->delay_secs;
2770				break;
2771			case CTL_DELAY_LOC_DONE:
2772				lun->delay_info.done_type =
2773					delay_info->delay_type;
2774				lun->delay_info.done_delay =
2775					delay_info->delay_secs;
2776				break;
2777			default:
2778				delay_info->status =
2779					CTL_DELAY_STATUS_INVALID_LOC;
2780				break;
2781			}
2782			mtx_unlock(&lun->lun_lock);
2783		}
2784
2785		mtx_unlock(&softc->ctl_lock);
2786#else
2787		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2788#endif /* CTL_IO_DELAY */
2789		break;
2790	}
2791	case CTL_REALSYNC_SET: {
2792		int *syncstate;
2793
2794		syncstate = (int *)addr;
2795
2796		mtx_lock(&softc->ctl_lock);
2797		switch (*syncstate) {
2798		case 0:
2799			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2800			break;
2801		case 1:
2802			softc->flags |= CTL_FLAG_REAL_SYNC;
2803			break;
2804		default:
2805			retval = EINVAL;
2806			break;
2807		}
2808		mtx_unlock(&softc->ctl_lock);
2809		break;
2810	}
2811	case CTL_REALSYNC_GET: {
2812		int *syncstate;
2813
2814		syncstate = (int*)addr;
2815
2816		mtx_lock(&softc->ctl_lock);
2817		if (softc->flags & CTL_FLAG_REAL_SYNC)
2818			*syncstate = 1;
2819		else
2820			*syncstate = 0;
2821		mtx_unlock(&softc->ctl_lock);
2822
2823		break;
2824	}
2825	case CTL_SETSYNC:
2826	case CTL_GETSYNC: {
2827		struct ctl_sync_info *sync_info;
2828		struct ctl_lun *lun;
2829
2830		sync_info = (struct ctl_sync_info *)addr;
2831
2832		mtx_lock(&softc->ctl_lock);
2833		lun = softc->ctl_luns[sync_info->lun_id];
2834		if (lun == NULL) {
2835			mtx_unlock(&softc->ctl_lock);
2836			sync_info->status = CTL_GS_SYNC_NO_LUN;
2837		}
2838		/*
2839		 * Get or set the sync interval.  We're not bounds checking
2840		 * in the set case, hopefully the user won't do something
2841		 * silly.
2842		 */
2843		mtx_lock(&lun->lun_lock);
2844		mtx_unlock(&softc->ctl_lock);
2845		if (cmd == CTL_GETSYNC)
2846			sync_info->sync_interval = lun->sync_interval;
2847		else
2848			lun->sync_interval = sync_info->sync_interval;
2849		mtx_unlock(&lun->lun_lock);
2850
2851		sync_info->status = CTL_GS_SYNC_OK;
2852
2853		break;
2854	}
2855	case CTL_GETSTATS: {
2856		struct ctl_stats *stats;
2857		struct ctl_lun *lun;
2858		int i;
2859
2860		stats = (struct ctl_stats *)addr;
2861
2862		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2863		     stats->alloc_len) {
2864			stats->status = CTL_SS_NEED_MORE_SPACE;
2865			stats->num_luns = softc->num_luns;
2866			break;
2867		}
2868		/*
2869		 * XXX KDM no locking here.  If the LUN list changes,
2870		 * things can blow up.
2871		 */
2872		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2873		     i++, lun = STAILQ_NEXT(lun, links)) {
2874			retval = copyout(&lun->stats, &stats->lun_stats[i],
2875					 sizeof(lun->stats));
2876			if (retval != 0)
2877				break;
2878		}
2879		stats->num_luns = softc->num_luns;
2880		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2881				 softc->num_luns;
2882		stats->status = CTL_SS_OK;
2883#ifdef CTL_TIME_IO
2884		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2885#else
2886		stats->flags = CTL_STATS_FLAG_NONE;
2887#endif
2888		getnanouptime(&stats->timestamp);
2889		break;
2890	}
2891	case CTL_ERROR_INJECT: {
2892		struct ctl_error_desc *err_desc, *new_err_desc;
2893		struct ctl_lun *lun;
2894
2895		err_desc = (struct ctl_error_desc *)addr;
2896
2897		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2898				      M_WAITOK | M_ZERO);
2899		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2900
2901		mtx_lock(&softc->ctl_lock);
2902		lun = softc->ctl_luns[err_desc->lun_id];
2903		if (lun == NULL) {
2904			mtx_unlock(&softc->ctl_lock);
2905			free(new_err_desc, M_CTL);
2906			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2907			       __func__, (uintmax_t)err_desc->lun_id);
2908			retval = EINVAL;
2909			break;
2910		}
2911		mtx_lock(&lun->lun_lock);
2912		mtx_unlock(&softc->ctl_lock);
2913
2914		/*
2915		 * We could do some checking here to verify the validity
2916		 * of the request, but given the complexity of error
2917		 * injection requests, the checking logic would be fairly
2918		 * complex.
2919		 *
2920		 * For now, if the request is invalid, it just won't get
2921		 * executed and might get deleted.
2922		 */
2923		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2924
2925		/*
2926		 * XXX KDM check to make sure the serial number is unique,
2927		 * in case we somehow manage to wrap.  That shouldn't
2928		 * happen for a very long time, but it's the right thing to
2929		 * do.
2930		 */
2931		new_err_desc->serial = lun->error_serial;
2932		err_desc->serial = lun->error_serial;
2933		lun->error_serial++;
2934
2935		mtx_unlock(&lun->lun_lock);
2936		break;
2937	}
2938	case CTL_ERROR_INJECT_DELETE: {
2939		struct ctl_error_desc *delete_desc, *desc, *desc2;
2940		struct ctl_lun *lun;
2941		int delete_done;
2942
2943		delete_desc = (struct ctl_error_desc *)addr;
2944		delete_done = 0;
2945
2946		mtx_lock(&softc->ctl_lock);
2947		lun = softc->ctl_luns[delete_desc->lun_id];
2948		if (lun == NULL) {
2949			mtx_unlock(&softc->ctl_lock);
2950			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2951			       __func__, (uintmax_t)delete_desc->lun_id);
2952			retval = EINVAL;
2953			break;
2954		}
2955		mtx_lock(&lun->lun_lock);
2956		mtx_unlock(&softc->ctl_lock);
2957		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2958			if (desc->serial != delete_desc->serial)
2959				continue;
2960
2961			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2962				      links);
2963			free(desc, M_CTL);
2964			delete_done = 1;
2965		}
2966		mtx_unlock(&lun->lun_lock);
2967		if (delete_done == 0) {
2968			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2969			       "error serial %ju on LUN %u\n", __func__,
2970			       delete_desc->serial, delete_desc->lun_id);
2971			retval = EINVAL;
2972			break;
2973		}
2974		break;
2975	}
2976	case CTL_DUMP_STRUCTS: {
2977		int i, j, k, idx;
2978		struct ctl_port *port;
2979		struct ctl_frontend *fe;
2980
2981		mtx_lock(&softc->ctl_lock);
2982		printf("CTL Persistent Reservation information start:\n");
2983		for (i = 0; i < CTL_MAX_LUNS; i++) {
2984			struct ctl_lun *lun;
2985
2986			lun = softc->ctl_luns[i];
2987
2988			if ((lun == NULL)
2989			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2990				continue;
2991
2992			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2993				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2994					idx = j * CTL_MAX_INIT_PER_PORT + k;
2995					if (lun->per_res[idx].registered == 0)
2996						continue;
2997					printf("  LUN %d port %d iid %d key "
2998					       "%#jx\n", i, j, k,
2999					       (uintmax_t)scsi_8btou64(
3000					       lun->per_res[idx].res_key.key));
3001				}
3002			}
3003		}
3004		printf("CTL Persistent Reservation information end\n");
3005		printf("CTL Ports:\n");
3006		STAILQ_FOREACH(port, &softc->port_list, links) {
3007			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3008			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3009			       port->frontend->name, port->port_type,
3010			       port->physical_port, port->virtual_port,
3011			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3012			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3013				if (port->wwpn_iid[j].in_use == 0 &&
3014				    port->wwpn_iid[j].wwpn == 0 &&
3015				    port->wwpn_iid[j].name == NULL)
3016					continue;
3017
3018				printf("    iid %u use %d WWPN %#jx '%s'\n",
3019				    j, port->wwpn_iid[j].in_use,
3020				    (uintmax_t)port->wwpn_iid[j].wwpn,
3021				    port->wwpn_iid[j].name);
3022			}
3023		}
3024		printf("CTL Port information end\n");
3025		mtx_unlock(&softc->ctl_lock);
3026		/*
3027		 * XXX KDM calling this without a lock.  We'd likely want
3028		 * to drop the lock before calling the frontend's dump
3029		 * routine anyway.
3030		 */
3031		printf("CTL Frontends:\n");
3032		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3033			printf("  Frontend '%s'\n", fe->name);
3034			if (fe->fe_dump != NULL)
3035				fe->fe_dump();
3036		}
3037		printf("CTL Frontend information end\n");
3038		break;
3039	}
3040	case CTL_LUN_REQ: {
3041		struct ctl_lun_req *lun_req;
3042		struct ctl_backend_driver *backend;
3043
3044		lun_req = (struct ctl_lun_req *)addr;
3045
3046		backend = ctl_backend_find(lun_req->backend);
3047		if (backend == NULL) {
3048			lun_req->status = CTL_LUN_ERROR;
3049			snprintf(lun_req->error_str,
3050				 sizeof(lun_req->error_str),
3051				 "Backend \"%s\" not found.",
3052				 lun_req->backend);
3053			break;
3054		}
3055		if (lun_req->num_be_args > 0) {
3056			lun_req->kern_be_args = ctl_copyin_args(
3057				lun_req->num_be_args,
3058				lun_req->be_args,
3059				lun_req->error_str,
3060				sizeof(lun_req->error_str));
3061			if (lun_req->kern_be_args == NULL) {
3062				lun_req->status = CTL_LUN_ERROR;
3063				break;
3064			}
3065		}
3066
3067		retval = backend->ioctl(dev, cmd, addr, flag, td);
3068
3069		if (lun_req->num_be_args > 0) {
3070			ctl_copyout_args(lun_req->num_be_args,
3071				      lun_req->kern_be_args);
3072			ctl_free_args(lun_req->num_be_args,
3073				      lun_req->kern_be_args);
3074		}
3075		break;
3076	}
3077	case CTL_LUN_LIST: {
3078		struct sbuf *sb;
3079		struct ctl_lun *lun;
3080		struct ctl_lun_list *list;
3081		struct ctl_option *opt;
3082
3083		list = (struct ctl_lun_list *)addr;
3084
3085		/*
3086		 * Allocate a fixed length sbuf here, based on the length
3087		 * of the user's buffer.  We could allocate an auto-extending
3088		 * buffer, and then tell the user how much larger our
3089		 * amount of data is than his buffer, but that presents
3090		 * some problems:
3091		 *
3092		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3093		 *     we can't hold a lock while calling them with an
3094		 *     auto-extending buffer.
3095 		 *
3096		 * 2.  There is not currently a LUN reference counting
3097		 *     mechanism, outside of outstanding transactions on
3098		 *     the LUN's OOA queue.  So a LUN could go away on us
3099		 *     while we're getting the LUN number, backend-specific
3100		 *     information, etc.  Thus, given the way things
3101		 *     currently work, we need to hold the CTL lock while
3102		 *     grabbing LUN information.
3103		 *
3104		 * So, from the user's standpoint, the best thing to do is
3105		 * allocate what he thinks is a reasonable buffer length,
3106		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3107		 * double the buffer length and try again.  (And repeat
3108		 * that until he succeeds.)
3109		 */
3110		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3111		if (sb == NULL) {
3112			list->status = CTL_LUN_LIST_ERROR;
3113			snprintf(list->error_str, sizeof(list->error_str),
3114				 "Unable to allocate %d bytes for LUN list",
3115				 list->alloc_len);
3116			break;
3117		}
3118
3119		sbuf_printf(sb, "<ctllunlist>\n");
3120
3121		mtx_lock(&softc->ctl_lock);
3122		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3123			mtx_lock(&lun->lun_lock);
3124			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3125					     (uintmax_t)lun->lun);
3126
3127			/*
3128			 * Bail out as soon as we see that we've overfilled
3129			 * the buffer.
3130			 */
3131			if (retval != 0)
3132				break;
3133
3134			retval = sbuf_printf(sb, "\t<backend_type>%s"
3135					     "</backend_type>\n",
3136					     (lun->backend == NULL) ?  "none" :
3137					     lun->backend->name);
3138
3139			if (retval != 0)
3140				break;
3141
3142			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3143					     lun->be_lun->lun_type);
3144
3145			if (retval != 0)
3146				break;
3147
3148			if (lun->backend == NULL) {
3149				retval = sbuf_printf(sb, "</lun>\n");
3150				if (retval != 0)
3151					break;
3152				continue;
3153			}
3154
3155			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3156					     (lun->be_lun->maxlba > 0) ?
3157					     lun->be_lun->maxlba + 1 : 0);
3158
3159			if (retval != 0)
3160				break;
3161
3162			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3163					     lun->be_lun->blocksize);
3164
3165			if (retval != 0)
3166				break;
3167
3168			retval = sbuf_printf(sb, "\t<serial_number>");
3169
3170			if (retval != 0)
3171				break;
3172
3173			retval = ctl_sbuf_printf_esc(sb,
3174						     lun->be_lun->serial_num);
3175
3176			if (retval != 0)
3177				break;
3178
3179			retval = sbuf_printf(sb, "</serial_number>\n");
3180
3181			if (retval != 0)
3182				break;
3183
3184			retval = sbuf_printf(sb, "\t<device_id>");
3185
3186			if (retval != 0)
3187				break;
3188
3189			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3190
3191			if (retval != 0)
3192				break;
3193
3194			retval = sbuf_printf(sb, "</device_id>\n");
3195
3196			if (retval != 0)
3197				break;
3198
3199			if (lun->backend->lun_info != NULL) {
3200				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3201				if (retval != 0)
3202					break;
3203			}
3204			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3205				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3206				    opt->name, opt->value, opt->name);
3207				if (retval != 0)
3208					break;
3209			}
3210
3211			retval = sbuf_printf(sb, "</lun>\n");
3212
3213			if (retval != 0)
3214				break;
3215			mtx_unlock(&lun->lun_lock);
3216		}
3217		if (lun != NULL)
3218			mtx_unlock(&lun->lun_lock);
3219		mtx_unlock(&softc->ctl_lock);
3220
3221		if ((retval != 0)
3222		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3223			retval = 0;
3224			sbuf_delete(sb);
3225			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3226			snprintf(list->error_str, sizeof(list->error_str),
3227				 "Out of space, %d bytes is too small",
3228				 list->alloc_len);
3229			break;
3230		}
3231
3232		sbuf_finish(sb);
3233
3234		retval = copyout(sbuf_data(sb), list->lun_xml,
3235				 sbuf_len(sb) + 1);
3236
3237		list->fill_len = sbuf_len(sb) + 1;
3238		list->status = CTL_LUN_LIST_OK;
3239		sbuf_delete(sb);
3240		break;
3241	}
3242	case CTL_ISCSI: {
3243		struct ctl_iscsi *ci;
3244		struct ctl_frontend *fe;
3245
3246		ci = (struct ctl_iscsi *)addr;
3247
3248		fe = ctl_frontend_find("iscsi");
3249		if (fe == NULL) {
3250			ci->status = CTL_ISCSI_ERROR;
3251			snprintf(ci->error_str, sizeof(ci->error_str),
3252			    "Frontend \"iscsi\" not found.");
3253			break;
3254		}
3255
3256		retval = fe->ioctl(dev, cmd, addr, flag, td);
3257		break;
3258	}
3259	case CTL_PORT_REQ: {
3260		struct ctl_req *req;
3261		struct ctl_frontend *fe;
3262
3263		req = (struct ctl_req *)addr;
3264
3265		fe = ctl_frontend_find(req->driver);
3266		if (fe == NULL) {
3267			req->status = CTL_LUN_ERROR;
3268			snprintf(req->error_str, sizeof(req->error_str),
3269			    "Frontend \"%s\" not found.", req->driver);
3270			break;
3271		}
3272		if (req->num_args > 0) {
3273			req->kern_args = ctl_copyin_args(req->num_args,
3274			    req->args, req->error_str, sizeof(req->error_str));
3275			if (req->kern_args == NULL) {
3276				req->status = CTL_LUN_ERROR;
3277				break;
3278			}
3279		}
3280
3281		retval = fe->ioctl(dev, cmd, addr, flag, td);
3282
3283		if (req->num_args > 0) {
3284			ctl_copyout_args(req->num_args, req->kern_args);
3285			ctl_free_args(req->num_args, req->kern_args);
3286		}
3287		break;
3288	}
3289	case CTL_PORT_LIST: {
3290		struct sbuf *sb;
3291		struct ctl_port *port;
3292		struct ctl_lun_list *list;
3293		struct ctl_option *opt;
3294
3295		list = (struct ctl_lun_list *)addr;
3296
3297		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3298		if (sb == NULL) {
3299			list->status = CTL_LUN_LIST_ERROR;
3300			snprintf(list->error_str, sizeof(list->error_str),
3301				 "Unable to allocate %d bytes for LUN list",
3302				 list->alloc_len);
3303			break;
3304		}
3305
3306		sbuf_printf(sb, "<ctlportlist>\n");
3307
3308		mtx_lock(&softc->ctl_lock);
3309		STAILQ_FOREACH(port, &softc->port_list, links) {
3310			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3311					     (uintmax_t)port->targ_port);
3312
3313			/*
3314			 * Bail out as soon as we see that we've overfilled
3315			 * the buffer.
3316			 */
3317			if (retval != 0)
3318				break;
3319
3320			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3321			    "</frontend_type>\n", port->frontend->name);
3322			if (retval != 0)
3323				break;
3324
3325			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3326					     port->port_type);
3327			if (retval != 0)
3328				break;
3329
3330			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3331			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3332			if (retval != 0)
3333				break;
3334
3335			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3336			    port->port_name);
3337			if (retval != 0)
3338				break;
3339
3340			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3341			    port->physical_port);
3342			if (retval != 0)
3343				break;
3344
3345			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3346			    port->virtual_port);
3347			if (retval != 0)
3348				break;
3349
3350			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3351			    (uintmax_t)port->wwnn);
3352			if (retval != 0)
3353				break;
3354
3355			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3356			    (uintmax_t)port->wwpn);
3357			if (retval != 0)
3358				break;
3359
3360			if (port->port_info != NULL) {
3361				retval = port->port_info(port->onoff_arg, sb);
3362				if (retval != 0)
3363					break;
3364			}
3365			STAILQ_FOREACH(opt, &port->options, links) {
3366				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3367				    opt->name, opt->value, opt->name);
3368				if (retval != 0)
3369					break;
3370			}
3371
3372			retval = sbuf_printf(sb, "</targ_port>\n");
3373			if (retval != 0)
3374				break;
3375		}
3376		mtx_unlock(&softc->ctl_lock);
3377
3378		if ((retval != 0)
3379		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3380			retval = 0;
3381			sbuf_delete(sb);
3382			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3383			snprintf(list->error_str, sizeof(list->error_str),
3384				 "Out of space, %d bytes is too small",
3385				 list->alloc_len);
3386			break;
3387		}
3388
3389		sbuf_finish(sb);
3390
3391		retval = copyout(sbuf_data(sb), list->lun_xml,
3392				 sbuf_len(sb) + 1);
3393
3394		list->fill_len = sbuf_len(sb) + 1;
3395		list->status = CTL_LUN_LIST_OK;
3396		sbuf_delete(sb);
3397		break;
3398	}
3399	default: {
3400		/* XXX KDM should we fix this? */
3401#if 0
3402		struct ctl_backend_driver *backend;
3403		unsigned int type;
3404		int found;
3405
3406		found = 0;
3407
3408		/*
3409		 * We encode the backend type as the ioctl type for backend
3410		 * ioctls.  So parse it out here, and then search for a
3411		 * backend of this type.
3412		 */
3413		type = _IOC_TYPE(cmd);
3414
3415		STAILQ_FOREACH(backend, &softc->be_list, links) {
3416			if (backend->type == type) {
3417				found = 1;
3418				break;
3419			}
3420		}
3421		if (found == 0) {
3422			printf("ctl: unknown ioctl command %#lx or backend "
3423			       "%d\n", cmd, type);
3424			retval = EINVAL;
3425			break;
3426		}
3427		retval = backend->ioctl(dev, cmd, addr, flag, td);
3428#endif
3429		retval = ENOTTY;
3430		break;
3431	}
3432	}
3433	return (retval);
3434}
3435
3436uint32_t
3437ctl_get_initindex(struct ctl_nexus *nexus)
3438{
3439	if (nexus->targ_port < CTL_MAX_PORTS)
3440		return (nexus->initid.id +
3441			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3442	else
3443		return (nexus->initid.id +
3444		       ((nexus->targ_port - CTL_MAX_PORTS) *
3445			CTL_MAX_INIT_PER_PORT));
3446}
3447
3448uint32_t
3449ctl_get_resindex(struct ctl_nexus *nexus)
3450{
3451	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3452}
3453
3454uint32_t
3455ctl_port_idx(int port_num)
3456{
3457	if (port_num < CTL_MAX_PORTS)
3458		return(port_num);
3459	else
3460		return(port_num - CTL_MAX_PORTS);
3461}
3462
3463static uint32_t
3464ctl_map_lun(int port_num, uint32_t lun_id)
3465{
3466	struct ctl_port *port;
3467
3468	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3469	if (port == NULL)
3470		return (UINT32_MAX);
3471	if (port->lun_map == NULL)
3472		return (lun_id);
3473	return (port->lun_map(port->targ_lun_arg, lun_id));
3474}
3475
3476static uint32_t
3477ctl_map_lun_back(int port_num, uint32_t lun_id)
3478{
3479	struct ctl_port *port;
3480	uint32_t i;
3481
3482	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3483	if (port->lun_map == NULL)
3484		return (lun_id);
3485	for (i = 0; i < CTL_MAX_LUNS; i++) {
3486		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3487			return (i);
3488	}
3489	return (UINT32_MAX);
3490}
3491
3492/*
3493 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3494 * that are a power of 2.
3495 */
3496int
3497ctl_ffz(uint32_t *mask, uint32_t size)
3498{
3499	uint32_t num_chunks, num_pieces;
3500	int i, j;
3501
3502	num_chunks = (size >> 5);
3503	if (num_chunks == 0)
3504		num_chunks++;
3505	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3506
3507	for (i = 0; i < num_chunks; i++) {
3508		for (j = 0; j < num_pieces; j++) {
3509			if ((mask[i] & (1 << j)) == 0)
3510				return ((i << 5) + j);
3511		}
3512	}
3513
3514	return (-1);
3515}
3516
3517int
3518ctl_set_mask(uint32_t *mask, uint32_t bit)
3519{
3520	uint32_t chunk, piece;
3521
3522	chunk = bit >> 5;
3523	piece = bit % (sizeof(uint32_t) * 8);
3524
3525	if ((mask[chunk] & (1 << piece)) != 0)
3526		return (-1);
3527	else
3528		mask[chunk] |= (1 << piece);
3529
3530	return (0);
3531}
3532
3533int
3534ctl_clear_mask(uint32_t *mask, uint32_t bit)
3535{
3536	uint32_t chunk, piece;
3537
3538	chunk = bit >> 5;
3539	piece = bit % (sizeof(uint32_t) * 8);
3540
3541	if ((mask[chunk] & (1 << piece)) == 0)
3542		return (-1);
3543	else
3544		mask[chunk] &= ~(1 << piece);
3545
3546	return (0);
3547}
3548
3549int
3550ctl_is_set(uint32_t *mask, uint32_t bit)
3551{
3552	uint32_t chunk, piece;
3553
3554	chunk = bit >> 5;
3555	piece = bit % (sizeof(uint32_t) * 8);
3556
3557	if ((mask[chunk] & (1 << piece)) == 0)
3558		return (0);
3559	else
3560		return (1);
3561}
3562
3563#ifdef unused
3564/*
3565 * The bus, target and lun are optional, they can be filled in later.
3566 * can_wait is used to determine whether we can wait on the malloc or not.
3567 */
3568union ctl_io*
3569ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3570	      uint32_t targ_lun, int can_wait)
3571{
3572	union ctl_io *io;
3573
3574	if (can_wait)
3575		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3576	else
3577		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3578
3579	if (io != NULL) {
3580		io->io_hdr.io_type = io_type;
3581		io->io_hdr.targ_port = targ_port;
3582		/*
3583		 * XXX KDM this needs to change/go away.  We need to move
3584		 * to a preallocated pool of ctl_scsiio structures.
3585		 */
3586		io->io_hdr.nexus.targ_target.id = targ_target;
3587		io->io_hdr.nexus.targ_lun = targ_lun;
3588	}
3589
3590	return (io);
3591}
3592
3593void
3594ctl_kfree_io(union ctl_io *io)
3595{
3596	free(io, M_CTL);
3597}
3598#endif /* unused */
3599
3600/*
3601 * ctl_softc, pool_type, total_ctl_io are passed in.
3602 * npool is passed out.
3603 */
3604int
3605ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3606		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3607{
3608	uint32_t i;
3609	union ctl_io *cur_io, *next_io;
3610	struct ctl_io_pool *pool;
3611	int retval;
3612
3613	retval = 0;
3614
3615	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3616					    M_NOWAIT | M_ZERO);
3617	if (pool == NULL) {
3618		retval = ENOMEM;
3619		goto bailout;
3620	}
3621
3622	pool->type = pool_type;
3623	pool->ctl_softc = ctl_softc;
3624
3625	mtx_lock(&ctl_softc->pool_lock);
3626	pool->id = ctl_softc->cur_pool_id++;
3627	mtx_unlock(&ctl_softc->pool_lock);
3628
3629	pool->flags = CTL_POOL_FLAG_NONE;
3630	pool->refcount = 1;		/* Reference for validity. */
3631	STAILQ_INIT(&pool->free_queue);
3632
3633	/*
3634	 * XXX KDM other options here:
3635	 * - allocate a page at a time
3636	 * - allocate one big chunk of memory.
3637	 * Page allocation might work well, but would take a little more
3638	 * tracking.
3639	 */
3640	for (i = 0; i < total_ctl_io; i++) {
3641		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3642						M_NOWAIT);
3643		if (cur_io == NULL) {
3644			retval = ENOMEM;
3645			break;
3646		}
3647		cur_io->io_hdr.pool = pool;
3648		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3649		pool->total_ctl_io++;
3650		pool->free_ctl_io++;
3651	}
3652
3653	if (retval != 0) {
3654		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3655		     cur_io != NULL; cur_io = next_io) {
3656			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3657							      links);
3658			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3659				      ctl_io_hdr, links);
3660			free(cur_io, M_CTLIO);
3661		}
3662
3663		free(pool, M_CTL);
3664		goto bailout;
3665	}
3666	mtx_lock(&ctl_softc->pool_lock);
3667	ctl_softc->num_pools++;
3668	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3669	/*
3670	 * Increment our usage count if this is an external consumer, so we
3671	 * can't get unloaded until the external consumer (most likely a
3672	 * FETD) unloads and frees his pool.
3673	 *
3674	 * XXX KDM will this increment the caller's module use count, or
3675	 * mine?
3676	 */
3677#if 0
3678	if ((pool_type != CTL_POOL_EMERGENCY)
3679	 && (pool_type != CTL_POOL_INTERNAL)
3680	 && (pool_type != CTL_POOL_4OTHERSC))
3681		MOD_INC_USE_COUNT;
3682#endif
3683
3684	mtx_unlock(&ctl_softc->pool_lock);
3685
3686	*npool = pool;
3687
3688bailout:
3689
3690	return (retval);
3691}
3692
3693static int
3694ctl_pool_acquire(struct ctl_io_pool *pool)
3695{
3696
3697	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3698
3699	if (pool->flags & CTL_POOL_FLAG_INVALID)
3700		return (EINVAL);
3701
3702	pool->refcount++;
3703
3704	return (0);
3705}
3706
3707static void
3708ctl_pool_release(struct ctl_io_pool *pool)
3709{
3710	struct ctl_softc *ctl_softc = pool->ctl_softc;
3711	union ctl_io *io;
3712
3713	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3714
3715	if (--pool->refcount != 0)
3716		return;
3717
3718	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3719		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3720			      links);
3721		free(io, M_CTLIO);
3722	}
3723
3724	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3725	ctl_softc->num_pools--;
3726
3727	/*
3728	 * XXX KDM will this decrement the caller's usage count or mine?
3729	 */
3730#if 0
3731	if ((pool->type != CTL_POOL_EMERGENCY)
3732	 && (pool->type != CTL_POOL_INTERNAL)
3733	 && (pool->type != CTL_POOL_4OTHERSC))
3734		MOD_DEC_USE_COUNT;
3735#endif
3736
3737	free(pool, M_CTL);
3738}
3739
3740void
3741ctl_pool_free(struct ctl_io_pool *pool)
3742{
3743	struct ctl_softc *ctl_softc;
3744
3745	if (pool == NULL)
3746		return;
3747
3748	ctl_softc = pool->ctl_softc;
3749	mtx_lock(&ctl_softc->pool_lock);
3750	pool->flags |= CTL_POOL_FLAG_INVALID;
3751	ctl_pool_release(pool);
3752	mtx_unlock(&ctl_softc->pool_lock);
3753}
3754
3755/*
3756 * This routine does not block (except for spinlocks of course).
3757 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3758 * possible.
3759 */
3760union ctl_io *
3761ctl_alloc_io(void *pool_ref)
3762{
3763	union ctl_io *io;
3764	struct ctl_softc *ctl_softc;
3765	struct ctl_io_pool *pool, *npool;
3766	struct ctl_io_pool *emergency_pool;
3767
3768	pool = (struct ctl_io_pool *)pool_ref;
3769
3770	if (pool == NULL) {
3771		printf("%s: pool is NULL\n", __func__);
3772		return (NULL);
3773	}
3774
3775	emergency_pool = NULL;
3776
3777	ctl_softc = pool->ctl_softc;
3778
3779	mtx_lock(&ctl_softc->pool_lock);
3780	/*
3781	 * First, try to get the io structure from the user's pool.
3782	 */
3783	if (ctl_pool_acquire(pool) == 0) {
3784		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3785		if (io != NULL) {
3786			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3787			pool->total_allocated++;
3788			pool->free_ctl_io--;
3789			mtx_unlock(&ctl_softc->pool_lock);
3790			return (io);
3791		} else
3792			ctl_pool_release(pool);
3793	}
3794	/*
3795	 * If he doesn't have any io structures left, search for an
3796	 * emergency pool and grab one from there.
3797	 */
3798	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3799		if (npool->type != CTL_POOL_EMERGENCY)
3800			continue;
3801
3802		if (ctl_pool_acquire(npool) != 0)
3803			continue;
3804
3805		emergency_pool = npool;
3806
3807		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3808		if (io != NULL) {
3809			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3810			npool->total_allocated++;
3811			npool->free_ctl_io--;
3812			mtx_unlock(&ctl_softc->pool_lock);
3813			return (io);
3814		} else
3815			ctl_pool_release(npool);
3816	}
3817
3818	/* Drop the spinlock before we malloc */
3819	mtx_unlock(&ctl_softc->pool_lock);
3820
3821	/*
3822	 * The emergency pool (if it exists) didn't have one, so try an
3823	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3824	 */
3825	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3826	if (io != NULL) {
3827		/*
3828		 * If the emergency pool exists but is empty, add this
3829		 * ctl_io to its list when it gets freed.
3830		 */
3831		if (emergency_pool != NULL) {
3832			mtx_lock(&ctl_softc->pool_lock);
3833			if (ctl_pool_acquire(emergency_pool) == 0) {
3834				io->io_hdr.pool = emergency_pool;
3835				emergency_pool->total_ctl_io++;
3836				/*
3837				 * Need to bump this, otherwise
3838				 * total_allocated and total_freed won't
3839				 * match when we no longer have anything
3840				 * outstanding.
3841				 */
3842				emergency_pool->total_allocated++;
3843			}
3844			mtx_unlock(&ctl_softc->pool_lock);
3845		} else
3846			io->io_hdr.pool = NULL;
3847	}
3848
3849	return (io);
3850}
3851
3852void
3853ctl_free_io(union ctl_io *io)
3854{
3855	if (io == NULL)
3856		return;
3857
3858	/*
3859	 * If this ctl_io has a pool, return it to that pool.
3860	 */
3861	if (io->io_hdr.pool != NULL) {
3862		struct ctl_io_pool *pool;
3863
3864		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3865		mtx_lock(&pool->ctl_softc->pool_lock);
3866		io->io_hdr.io_type = 0xff;
3867		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3868		pool->total_freed++;
3869		pool->free_ctl_io++;
3870		ctl_pool_release(pool);
3871		mtx_unlock(&pool->ctl_softc->pool_lock);
3872	} else {
3873		/*
3874		 * Otherwise, just free it.  We probably malloced it and
3875		 * the emergency pool wasn't available.
3876		 */
3877		free(io, M_CTLIO);
3878	}
3879
3880}
3881
3882void
3883ctl_zero_io(union ctl_io *io)
3884{
3885	void *pool_ref;
3886
3887	if (io == NULL)
3888		return;
3889
3890	/*
3891	 * May need to preserve linked list pointers at some point too.
3892	 */
3893	pool_ref = io->io_hdr.pool;
3894
3895	memset(io, 0, sizeof(*io));
3896
3897	io->io_hdr.pool = pool_ref;
3898}
3899
3900/*
3901 * This routine is currently used for internal copies of ctl_ios that need
3902 * to persist for some reason after we've already returned status to the
3903 * FETD.  (Thus the flag set.)
3904 *
3905 * XXX XXX
3906 * Note that this makes a blind copy of all fields in the ctl_io, except
3907 * for the pool reference.  This includes any memory that has been
3908 * allocated!  That memory will no longer be valid after done has been
3909 * called, so this would be VERY DANGEROUS for command that actually does
3910 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3911 * start and stop commands, which don't transfer any data, so this is not a
3912 * problem.  If it is used for anything else, the caller would also need to
3913 * allocate data buffer space and this routine would need to be modified to
3914 * copy the data buffer(s) as well.
3915 */
3916void
3917ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3918{
3919	void *pool_ref;
3920
3921	if ((src == NULL)
3922	 || (dest == NULL))
3923		return;
3924
3925	/*
3926	 * May need to preserve linked list pointers at some point too.
3927	 */
3928	pool_ref = dest->io_hdr.pool;
3929
3930	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3931
3932	dest->io_hdr.pool = pool_ref;
3933	/*
3934	 * We need to know that this is an internal copy, and doesn't need
3935	 * to get passed back to the FETD that allocated it.
3936	 */
3937	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3938}
3939
3940#ifdef NEEDTOPORT
3941static void
3942ctl_update_power_subpage(struct copan_power_subpage *page)
3943{
3944	int num_luns, num_partitions, config_type;
3945	struct ctl_softc *softc;
3946	cs_BOOL_t aor_present, shelf_50pct_power;
3947	cs_raidset_personality_t rs_type;
3948	int max_active_luns;
3949
3950	softc = control_softc;
3951
3952	/* subtract out the processor LUN */
3953	num_luns = softc->num_luns - 1;
3954	/*
3955	 * Default to 7 LUNs active, which was the only number we allowed
3956	 * in the past.
3957	 */
3958	max_active_luns = 7;
3959
3960	num_partitions = config_GetRsPartitionInfo();
3961	config_type = config_GetConfigType();
3962	shelf_50pct_power = config_GetShelfPowerMode();
3963	aor_present = config_IsAorRsPresent();
3964
3965	rs_type = ddb_GetRsRaidType(1);
3966	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3967	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3968		EPRINT(0, "Unsupported RS type %d!", rs_type);
3969	}
3970
3971
3972	page->total_luns = num_luns;
3973
3974	switch (config_type) {
3975	case 40:
3976		/*
3977		 * In a 40 drive configuration, it doesn't matter what DC
3978		 * cards we have, whether we have AOR enabled or not,
3979		 * partitioning or not, or what type of RAIDset we have.
3980		 * In that scenario, we can power up every LUN we present
3981		 * to the user.
3982		 */
3983		max_active_luns = num_luns;
3984
3985		break;
3986	case 64:
3987		if (shelf_50pct_power == CS_FALSE) {
3988			/* 25% power */
3989			if (aor_present == CS_TRUE) {
3990				if (rs_type ==
3991				     CS_RAIDSET_PERSONALITY_RAID5) {
3992					max_active_luns = 7;
3993				} else if (rs_type ==
3994					 CS_RAIDSET_PERSONALITY_RAID1){
3995					max_active_luns = 14;
3996				} else {
3997					/* XXX KDM now what?? */
3998				}
3999			} else {
4000				if (rs_type ==
4001				     CS_RAIDSET_PERSONALITY_RAID5) {
4002					max_active_luns = 8;
4003				} else if (rs_type ==
4004					 CS_RAIDSET_PERSONALITY_RAID1){
4005					max_active_luns = 16;
4006				} else {
4007					/* XXX KDM now what?? */
4008				}
4009			}
4010		} else {
4011			/* 50% power */
4012			/*
4013			 * With 50% power in a 64 drive configuration, we
4014			 * can power all LUNs we present.
4015			 */
4016			max_active_luns = num_luns;
4017		}
4018		break;
4019	case 112:
4020		if (shelf_50pct_power == CS_FALSE) {
4021			/* 25% power */
4022			if (aor_present == CS_TRUE) {
4023				if (rs_type ==
4024				     CS_RAIDSET_PERSONALITY_RAID5) {
4025					max_active_luns = 7;
4026				} else if (rs_type ==
4027					 CS_RAIDSET_PERSONALITY_RAID1){
4028					max_active_luns = 14;
4029				} else {
4030					/* XXX KDM now what?? */
4031				}
4032			} else {
4033				if (rs_type ==
4034				     CS_RAIDSET_PERSONALITY_RAID5) {
4035					max_active_luns = 8;
4036				} else if (rs_type ==
4037					 CS_RAIDSET_PERSONALITY_RAID1){
4038					max_active_luns = 16;
4039				} else {
4040					/* XXX KDM now what?? */
4041				}
4042			}
4043		} else {
4044			/* 50% power */
4045			if (aor_present == CS_TRUE) {
4046				if (rs_type ==
4047				     CS_RAIDSET_PERSONALITY_RAID5) {
4048					max_active_luns = 14;
4049				} else if (rs_type ==
4050					 CS_RAIDSET_PERSONALITY_RAID1){
4051					/*
4052					 * We're assuming here that disk
4053					 * caching is enabled, and so we're
4054					 * able to power up half of each
4055					 * LUN, and cache all writes.
4056					 */
4057					max_active_luns = num_luns;
4058				} else {
4059					/* XXX KDM now what?? */
4060				}
4061			} else {
4062				if (rs_type ==
4063				     CS_RAIDSET_PERSONALITY_RAID5) {
4064					max_active_luns = 15;
4065				} else if (rs_type ==
4066					 CS_RAIDSET_PERSONALITY_RAID1){
4067					max_active_luns = 30;
4068				} else {
4069					/* XXX KDM now what?? */
4070				}
4071			}
4072		}
4073		break;
4074	default:
4075		/*
4076		 * In this case, we have an unknown configuration, so we
4077		 * just use the default from above.
4078		 */
4079		break;
4080	}
4081
4082	page->max_active_luns = max_active_luns;
4083#if 0
4084	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4085	       page->total_luns, page->max_active_luns);
4086#endif
4087}
4088#endif /* NEEDTOPORT */
4089
4090/*
4091 * This routine could be used in the future to load default and/or saved
4092 * mode page parameters for a particuar lun.
4093 */
4094static int
4095ctl_init_page_index(struct ctl_lun *lun)
4096{
4097	int i;
4098	struct ctl_page_index *page_index;
4099	struct ctl_softc *softc;
4100	const char *value;
4101
4102	memcpy(&lun->mode_pages.index, page_index_template,
4103	       sizeof(page_index_template));
4104
4105	softc = lun->ctl_softc;
4106
4107	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4108
4109		page_index = &lun->mode_pages.index[i];
4110		/*
4111		 * If this is a disk-only mode page, there's no point in
4112		 * setting it up.  For some pages, we have to have some
4113		 * basic information about the disk in order to calculate the
4114		 * mode page data.
4115		 */
4116		if ((lun->be_lun->lun_type != T_DIRECT)
4117		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4118			continue;
4119
4120		switch (page_index->page_code & SMPH_PC_MASK) {
4121		case SMS_FORMAT_DEVICE_PAGE: {
4122			struct scsi_format_page *format_page;
4123
4124			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4125				panic("subpage is incorrect!");
4126
4127			/*
4128			 * Sectors per track are set above.  Bytes per
4129			 * sector need to be set here on a per-LUN basis.
4130			 */
4131			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4132			       &format_page_default,
4133			       sizeof(format_page_default));
4134			memcpy(&lun->mode_pages.format_page[
4135			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4136			       sizeof(format_page_changeable));
4137			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4138			       &format_page_default,
4139			       sizeof(format_page_default));
4140			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4141			       &format_page_default,
4142			       sizeof(format_page_default));
4143
4144			format_page = &lun->mode_pages.format_page[
4145				CTL_PAGE_CURRENT];
4146			scsi_ulto2b(lun->be_lun->blocksize,
4147				    format_page->bytes_per_sector);
4148
4149			format_page = &lun->mode_pages.format_page[
4150				CTL_PAGE_DEFAULT];
4151			scsi_ulto2b(lun->be_lun->blocksize,
4152				    format_page->bytes_per_sector);
4153
4154			format_page = &lun->mode_pages.format_page[
4155				CTL_PAGE_SAVED];
4156			scsi_ulto2b(lun->be_lun->blocksize,
4157				    format_page->bytes_per_sector);
4158
4159			page_index->page_data =
4160				(uint8_t *)lun->mode_pages.format_page;
4161			break;
4162		}
4163		case SMS_RIGID_DISK_PAGE: {
4164			struct scsi_rigid_disk_page *rigid_disk_page;
4165			uint32_t sectors_per_cylinder;
4166			uint64_t cylinders;
4167#ifndef	__XSCALE__
4168			int shift;
4169#endif /* !__XSCALE__ */
4170
4171			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4172				panic("invalid subpage value %d",
4173				      page_index->subpage);
4174
4175			/*
4176			 * Rotation rate and sectors per track are set
4177			 * above.  We calculate the cylinders here based on
4178			 * capacity.  Due to the number of heads and
4179			 * sectors per track we're using, smaller arrays
4180			 * may turn out to have 0 cylinders.  Linux and
4181			 * FreeBSD don't pay attention to these mode pages
4182			 * to figure out capacity, but Solaris does.  It
4183			 * seems to deal with 0 cylinders just fine, and
4184			 * works out a fake geometry based on the capacity.
4185			 */
4186			memcpy(&lun->mode_pages.rigid_disk_page[
4187			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4188			       sizeof(rigid_disk_page_default));
4189			memcpy(&lun->mode_pages.rigid_disk_page[
4190			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4191			       sizeof(rigid_disk_page_changeable));
4192			memcpy(&lun->mode_pages.rigid_disk_page[
4193			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4194			       sizeof(rigid_disk_page_default));
4195			memcpy(&lun->mode_pages.rigid_disk_page[
4196			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4197			       sizeof(rigid_disk_page_default));
4198
4199			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4200				CTL_DEFAULT_HEADS;
4201
4202			/*
4203			 * The divide method here will be more accurate,
4204			 * probably, but results in floating point being
4205			 * used in the kernel on i386 (__udivdi3()).  On the
4206			 * XScale, though, __udivdi3() is implemented in
4207			 * software.
4208			 *
4209			 * The shift method for cylinder calculation is
4210			 * accurate if sectors_per_cylinder is a power of
4211			 * 2.  Otherwise it might be slightly off -- you
4212			 * might have a bit of a truncation problem.
4213			 */
4214#ifdef	__XSCALE__
4215			cylinders = (lun->be_lun->maxlba + 1) /
4216				sectors_per_cylinder;
4217#else
4218			for (shift = 31; shift > 0; shift--) {
4219				if (sectors_per_cylinder & (1 << shift))
4220					break;
4221			}
4222			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4223#endif
4224
4225			/*
4226			 * We've basically got 3 bytes, or 24 bits for the
4227			 * cylinder size in the mode page.  If we're over,
4228			 * just round down to 2^24.
4229			 */
4230			if (cylinders > 0xffffff)
4231				cylinders = 0xffffff;
4232
4233			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4234				CTL_PAGE_CURRENT];
4235			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4236
4237			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4238				CTL_PAGE_DEFAULT];
4239			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4240
4241			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4242				CTL_PAGE_SAVED];
4243			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4244
4245			page_index->page_data =
4246				(uint8_t *)lun->mode_pages.rigid_disk_page;
4247			break;
4248		}
4249		case SMS_CACHING_PAGE: {
4250			struct scsi_caching_page *caching_page;
4251
4252			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4253				panic("invalid subpage value %d",
4254				      page_index->subpage);
4255			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
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_SAVED],
4262			       &caching_page_default,
4263			       sizeof(caching_page_default));
4264			caching_page = &lun->mode_pages.caching_page[
4265			    CTL_PAGE_SAVED];
4266			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4267			if (value != NULL && strcmp(value, "off") == 0)
4268				caching_page->flags1 &= ~SCP_WCE;
4269			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4270			if (value != NULL && strcmp(value, "off") == 0)
4271				caching_page->flags1 |= SCP_RCD;
4272			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4273			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4274			       sizeof(caching_page_default));
4275			page_index->page_data =
4276				(uint8_t *)lun->mode_pages.caching_page;
4277			break;
4278		}
4279		case SMS_CONTROL_MODE_PAGE: {
4280
4281			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4282				panic("invalid subpage value %d",
4283				      page_index->subpage);
4284
4285			/*
4286			 * Defaults should be okay here, no calculations
4287			 * needed.
4288			 */
4289			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4290			       &control_page_default,
4291			       sizeof(control_page_default));
4292			memcpy(&lun->mode_pages.control_page[
4293			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4294			       sizeof(control_page_changeable));
4295			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4296			       &control_page_default,
4297			       sizeof(control_page_default));
4298			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4299			       &control_page_default,
4300			       sizeof(control_page_default));
4301			page_index->page_data =
4302				(uint8_t *)lun->mode_pages.control_page;
4303			break;
4304
4305		}
4306		case SMS_VENDOR_SPECIFIC_PAGE:{
4307			switch (page_index->subpage) {
4308			case PWR_SUBPAGE_CODE: {
4309				struct copan_power_subpage *current_page,
4310							   *saved_page;
4311
4312				memcpy(&lun->mode_pages.power_subpage[
4313				       CTL_PAGE_CURRENT],
4314				       &power_page_default,
4315				       sizeof(power_page_default));
4316				memcpy(&lun->mode_pages.power_subpage[
4317				       CTL_PAGE_CHANGEABLE],
4318				       &power_page_changeable,
4319				       sizeof(power_page_changeable));
4320				memcpy(&lun->mode_pages.power_subpage[
4321				       CTL_PAGE_DEFAULT],
4322				       &power_page_default,
4323				       sizeof(power_page_default));
4324				memcpy(&lun->mode_pages.power_subpage[
4325				       CTL_PAGE_SAVED],
4326				       &power_page_default,
4327				       sizeof(power_page_default));
4328				page_index->page_data =
4329				    (uint8_t *)lun->mode_pages.power_subpage;
4330
4331				current_page = (struct copan_power_subpage *)
4332					(page_index->page_data +
4333					 (page_index->page_len *
4334					  CTL_PAGE_CURRENT));
4335			        saved_page = (struct copan_power_subpage *)
4336				        (page_index->page_data +
4337					 (page_index->page_len *
4338					  CTL_PAGE_SAVED));
4339				break;
4340			}
4341			case APS_SUBPAGE_CODE: {
4342				struct copan_aps_subpage *current_page,
4343							 *saved_page;
4344
4345				// This gets set multiple times but
4346				// it should always be the same. It's
4347				// only done during init so who cares.
4348				index_to_aps_page = i;
4349
4350				memcpy(&lun->mode_pages.aps_subpage[
4351				       CTL_PAGE_CURRENT],
4352				       &aps_page_default,
4353				       sizeof(aps_page_default));
4354				memcpy(&lun->mode_pages.aps_subpage[
4355				       CTL_PAGE_CHANGEABLE],
4356				       &aps_page_changeable,
4357				       sizeof(aps_page_changeable));
4358				memcpy(&lun->mode_pages.aps_subpage[
4359				       CTL_PAGE_DEFAULT],
4360				       &aps_page_default,
4361				       sizeof(aps_page_default));
4362				memcpy(&lun->mode_pages.aps_subpage[
4363				       CTL_PAGE_SAVED],
4364				       &aps_page_default,
4365				       sizeof(aps_page_default));
4366				page_index->page_data =
4367					(uint8_t *)lun->mode_pages.aps_subpage;
4368
4369				current_page = (struct copan_aps_subpage *)
4370					(page_index->page_data +
4371					 (page_index->page_len *
4372					  CTL_PAGE_CURRENT));
4373				saved_page = (struct copan_aps_subpage *)
4374					(page_index->page_data +
4375					 (page_index->page_len *
4376					  CTL_PAGE_SAVED));
4377				break;
4378			}
4379			case DBGCNF_SUBPAGE_CODE: {
4380				struct copan_debugconf_subpage *current_page,
4381							       *saved_page;
4382
4383				memcpy(&lun->mode_pages.debugconf_subpage[
4384				       CTL_PAGE_CURRENT],
4385				       &debugconf_page_default,
4386				       sizeof(debugconf_page_default));
4387				memcpy(&lun->mode_pages.debugconf_subpage[
4388				       CTL_PAGE_CHANGEABLE],
4389				       &debugconf_page_changeable,
4390				       sizeof(debugconf_page_changeable));
4391				memcpy(&lun->mode_pages.debugconf_subpage[
4392				       CTL_PAGE_DEFAULT],
4393				       &debugconf_page_default,
4394				       sizeof(debugconf_page_default));
4395				memcpy(&lun->mode_pages.debugconf_subpage[
4396				       CTL_PAGE_SAVED],
4397				       &debugconf_page_default,
4398				       sizeof(debugconf_page_default));
4399				page_index->page_data =
4400					(uint8_t *)lun->mode_pages.debugconf_subpage;
4401
4402				current_page = (struct copan_debugconf_subpage *)
4403					(page_index->page_data +
4404					 (page_index->page_len *
4405					  CTL_PAGE_CURRENT));
4406				saved_page = (struct copan_debugconf_subpage *)
4407					(page_index->page_data +
4408					 (page_index->page_len *
4409					  CTL_PAGE_SAVED));
4410				break;
4411			}
4412			default:
4413				panic("invalid subpage value %d",
4414				      page_index->subpage);
4415				break;
4416			}
4417   			break;
4418		}
4419		default:
4420			panic("invalid page value %d",
4421			      page_index->page_code & SMPH_PC_MASK);
4422			break;
4423    	}
4424	}
4425
4426	return (CTL_RETVAL_COMPLETE);
4427}
4428
4429/*
4430 * LUN allocation.
4431 *
4432 * Requirements:
4433 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4434 *   wants us to allocate the LUN and he can block.
4435 * - ctl_softc is always set
4436 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4437 *
4438 * Returns 0 for success, non-zero (errno) for failure.
4439 */
4440static int
4441ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4442	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4443{
4444	struct ctl_lun *nlun, *lun;
4445	struct ctl_port *port;
4446	struct scsi_vpd_id_descriptor *desc;
4447	struct scsi_vpd_id_t10 *t10id;
4448	const char *eui, *naa, *scsiname, *vendor;
4449	int lun_number, i, lun_malloced;
4450	int devidlen, idlen1, idlen2 = 0, len;
4451
4452	if (be_lun == NULL)
4453		return (EINVAL);
4454
4455	/*
4456	 * We currently only support Direct Access or Processor LUN types.
4457	 */
4458	switch (be_lun->lun_type) {
4459	case T_DIRECT:
4460		break;
4461	case T_PROCESSOR:
4462		break;
4463	case T_SEQUENTIAL:
4464	case T_CHANGER:
4465	default:
4466		be_lun->lun_config_status(be_lun->be_lun,
4467					  CTL_LUN_CONFIG_FAILURE);
4468		break;
4469	}
4470	if (ctl_lun == NULL) {
4471		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4472		lun_malloced = 1;
4473	} else {
4474		lun_malloced = 0;
4475		lun = ctl_lun;
4476	}
4477
4478	memset(lun, 0, sizeof(*lun));
4479	if (lun_malloced)
4480		lun->flags = CTL_LUN_MALLOCED;
4481
4482	/* Generate LUN ID. */
4483	devidlen = max(CTL_DEVID_MIN_LEN,
4484	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4485	idlen1 = sizeof(*t10id) + devidlen;
4486	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4487	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4488	if (scsiname != NULL) {
4489		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4490		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4491	}
4492	eui = ctl_get_opt(&be_lun->options, "eui");
4493	if (eui != NULL) {
4494		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4495	}
4496	naa = ctl_get_opt(&be_lun->options, "naa");
4497	if (naa != NULL) {
4498		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4499	}
4500	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4501	    M_CTL, M_WAITOK | M_ZERO);
4502	lun->lun_devid->len = len;
4503	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4504	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4505	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4506	desc->length = idlen1;
4507	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4508	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4509	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4510		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4511	} else {
4512		strncpy(t10id->vendor, vendor,
4513		    min(sizeof(t10id->vendor), strlen(vendor)));
4514	}
4515	strncpy((char *)t10id->vendor_spec_id,
4516	    (char *)be_lun->device_id, devidlen);
4517	if (scsiname != NULL) {
4518		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4519		    desc->length);
4520		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4521		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4522		    SVPD_ID_TYPE_SCSI_NAME;
4523		desc->length = idlen2;
4524		strlcpy(desc->identifier, scsiname, idlen2);
4525	}
4526	if (eui != NULL) {
4527		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4528		    desc->length);
4529		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4530		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4531		    SVPD_ID_TYPE_EUI64;
4532		desc->length = 8;
4533		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4534	}
4535	if (naa != NULL) {
4536		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4537		    desc->length);
4538		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4539		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4540		    SVPD_ID_TYPE_NAA;
4541		desc->length = 8;
4542		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4543	}
4544
4545	mtx_lock(&ctl_softc->ctl_lock);
4546	/*
4547	 * See if the caller requested a particular LUN number.  If so, see
4548	 * if it is available.  Otherwise, allocate the first available LUN.
4549	 */
4550	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4551		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4552		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4553			mtx_unlock(&ctl_softc->ctl_lock);
4554			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4555				printf("ctl: requested LUN ID %d is higher "
4556				       "than CTL_MAX_LUNS - 1 (%d)\n",
4557				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4558			} else {
4559				/*
4560				 * XXX KDM return an error, or just assign
4561				 * another LUN ID in this case??
4562				 */
4563				printf("ctl: requested LUN ID %d is already "
4564				       "in use\n", be_lun->req_lun_id);
4565			}
4566			if (lun->flags & CTL_LUN_MALLOCED)
4567				free(lun, M_CTL);
4568			be_lun->lun_config_status(be_lun->be_lun,
4569						  CTL_LUN_CONFIG_FAILURE);
4570			return (ENOSPC);
4571		}
4572		lun_number = be_lun->req_lun_id;
4573	} else {
4574		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4575		if (lun_number == -1) {
4576			mtx_unlock(&ctl_softc->ctl_lock);
4577			printf("ctl: can't allocate LUN on target %ju, out of "
4578			       "LUNs\n", (uintmax_t)target_id.id);
4579			if (lun->flags & CTL_LUN_MALLOCED)
4580				free(lun, M_CTL);
4581			be_lun->lun_config_status(be_lun->be_lun,
4582						  CTL_LUN_CONFIG_FAILURE);
4583			return (ENOSPC);
4584		}
4585	}
4586	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4587
4588	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4589	lun->target = target_id;
4590	lun->lun = lun_number;
4591	lun->be_lun = be_lun;
4592	/*
4593	 * The processor LUN is always enabled.  Disk LUNs come on line
4594	 * disabled, and must be enabled by the backend.
4595	 */
4596	lun->flags |= CTL_LUN_DISABLED;
4597	lun->backend = be_lun->be;
4598	be_lun->ctl_lun = lun;
4599	be_lun->lun_id = lun_number;
4600	atomic_add_int(&be_lun->be->num_luns, 1);
4601	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4602		lun->flags |= CTL_LUN_STOPPED;
4603
4604	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4605		lun->flags |= CTL_LUN_INOPERABLE;
4606
4607	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4608		lun->flags |= CTL_LUN_PRIMARY_SC;
4609
4610	lun->ctl_softc = ctl_softc;
4611	TAILQ_INIT(&lun->ooa_queue);
4612	TAILQ_INIT(&lun->blocked_queue);
4613	STAILQ_INIT(&lun->error_list);
4614	ctl_tpc_lun_init(lun);
4615
4616	/*
4617	 * Initialize the mode page index.
4618	 */
4619	ctl_init_page_index(lun);
4620
4621	/*
4622	 * Set the poweron UA for all initiators on this LUN only.
4623	 */
4624	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4625		lun->pending_ua[i] = CTL_UA_POWERON;
4626
4627	/*
4628	 * Now, before we insert this lun on the lun list, set the lun
4629	 * inventory changed UA for all other luns.
4630	 */
4631	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4632		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4633			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4634		}
4635	}
4636
4637	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4638
4639	ctl_softc->ctl_luns[lun_number] = lun;
4640
4641	ctl_softc->num_luns++;
4642
4643	/* Setup statistics gathering */
4644	lun->stats.device_type = be_lun->lun_type;
4645	lun->stats.lun_number = lun_number;
4646	if (lun->stats.device_type == T_DIRECT)
4647		lun->stats.blocksize = be_lun->blocksize;
4648	else
4649		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4650	for (i = 0;i < CTL_MAX_PORTS;i++)
4651		lun->stats.ports[i].targ_port = i;
4652
4653	mtx_unlock(&ctl_softc->ctl_lock);
4654
4655	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4656
4657	/*
4658	 * Run through each registered FETD and bring it online if it isn't
4659	 * already.  Enable the target ID if it hasn't been enabled, and
4660	 * enable this particular LUN.
4661	 */
4662	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4663		int retval;
4664
4665		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4666		if (retval != 0) {
4667			printf("ctl_alloc_lun: FETD %s port %d returned error "
4668			       "%d for lun_enable on target %ju lun %d\n",
4669			       port->port_name, port->targ_port, retval,
4670			       (uintmax_t)target_id.id, lun_number);
4671		} else
4672			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4673	}
4674	return (0);
4675}
4676
4677/*
4678 * Delete a LUN.
4679 * Assumptions:
4680 * - LUN has already been marked invalid and any pending I/O has been taken
4681 *   care of.
4682 */
4683static int
4684ctl_free_lun(struct ctl_lun *lun)
4685{
4686	struct ctl_softc *softc;
4687#if 0
4688	struct ctl_port *port;
4689#endif
4690	struct ctl_lun *nlun;
4691	int i;
4692
4693	softc = lun->ctl_softc;
4694
4695	mtx_assert(&softc->ctl_lock, MA_OWNED);
4696
4697	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4698
4699	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4700
4701	softc->ctl_luns[lun->lun] = NULL;
4702
4703	if (!TAILQ_EMPTY(&lun->ooa_queue))
4704		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4705
4706	softc->num_luns--;
4707
4708	/*
4709	 * XXX KDM this scheme only works for a single target/multiple LUN
4710	 * setup.  It needs to be revamped for a multiple target scheme.
4711	 *
4712	 * XXX KDM this results in port->lun_disable() getting called twice,
4713	 * once when ctl_disable_lun() is called, and a second time here.
4714	 * We really need to re-think the LUN disable semantics.  There
4715	 * should probably be several steps/levels to LUN removal:
4716	 *  - disable
4717	 *  - invalidate
4718	 *  - free
4719 	 *
4720	 * Right now we only have a disable method when communicating to
4721	 * the front end ports, at least for individual LUNs.
4722	 */
4723#if 0
4724	STAILQ_FOREACH(port, &softc->port_list, links) {
4725		int retval;
4726
4727		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4728					 lun->lun);
4729		if (retval != 0) {
4730			printf("ctl_free_lun: FETD %s port %d returned error "
4731			       "%d for lun_disable on target %ju lun %jd\n",
4732			       port->port_name, port->targ_port, retval,
4733			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4734		}
4735
4736		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4737			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4738
4739			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4740			if (retval != 0) {
4741				printf("ctl_free_lun: FETD %s port %d "
4742				       "returned error %d for targ_disable on "
4743				       "target %ju\n", port->port_name,
4744				       port->targ_port, retval,
4745				       (uintmax_t)lun->target.id);
4746			} else
4747				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4748
4749			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4750				continue;
4751
4752#if 0
4753			port->port_offline(port->onoff_arg);
4754			port->status &= ~CTL_PORT_STATUS_ONLINE;
4755#endif
4756		}
4757	}
4758#endif
4759
4760	/*
4761	 * Tell the backend to free resources, if this LUN has a backend.
4762	 */
4763	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4764	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4765
4766	ctl_tpc_lun_shutdown(lun);
4767	mtx_destroy(&lun->lun_lock);
4768	free(lun->lun_devid, M_CTL);
4769	if (lun->flags & CTL_LUN_MALLOCED)
4770		free(lun, M_CTL);
4771
4772	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4773		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4774			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4775		}
4776	}
4777
4778	return (0);
4779}
4780
4781static void
4782ctl_create_lun(struct ctl_be_lun *be_lun)
4783{
4784	struct ctl_softc *ctl_softc;
4785
4786	ctl_softc = control_softc;
4787
4788	/*
4789	 * ctl_alloc_lun() should handle all potential failure cases.
4790	 */
4791	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4792}
4793
4794int
4795ctl_add_lun(struct ctl_be_lun *be_lun)
4796{
4797	struct ctl_softc *ctl_softc = control_softc;
4798
4799	mtx_lock(&ctl_softc->ctl_lock);
4800	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4801	mtx_unlock(&ctl_softc->ctl_lock);
4802	wakeup(&ctl_softc->pending_lun_queue);
4803
4804	return (0);
4805}
4806
4807int
4808ctl_enable_lun(struct ctl_be_lun *be_lun)
4809{
4810	struct ctl_softc *ctl_softc;
4811	struct ctl_port *port, *nport;
4812	struct ctl_lun *lun;
4813	int retval;
4814
4815	ctl_softc = control_softc;
4816
4817	lun = (struct ctl_lun *)be_lun->ctl_lun;
4818
4819	mtx_lock(&ctl_softc->ctl_lock);
4820	mtx_lock(&lun->lun_lock);
4821	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4822		/*
4823		 * eh?  Why did we get called if the LUN is already
4824		 * enabled?
4825		 */
4826		mtx_unlock(&lun->lun_lock);
4827		mtx_unlock(&ctl_softc->ctl_lock);
4828		return (0);
4829	}
4830	lun->flags &= ~CTL_LUN_DISABLED;
4831	mtx_unlock(&lun->lun_lock);
4832
4833	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4834		nport = STAILQ_NEXT(port, links);
4835
4836		/*
4837		 * Drop the lock while we call the FETD's enable routine.
4838		 * This can lead to a callback into CTL (at least in the
4839		 * case of the internal initiator frontend.
4840		 */
4841		mtx_unlock(&ctl_softc->ctl_lock);
4842		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4843		mtx_lock(&ctl_softc->ctl_lock);
4844		if (retval != 0) {
4845			printf("%s: FETD %s port %d returned error "
4846			       "%d for lun_enable on target %ju lun %jd\n",
4847			       __func__, port->port_name, port->targ_port, retval,
4848			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4849		}
4850#if 0
4851		 else {
4852            /* NOTE:  TODO:  why does lun enable affect port status? */
4853			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4854		}
4855#endif
4856	}
4857
4858	mtx_unlock(&ctl_softc->ctl_lock);
4859
4860	return (0);
4861}
4862
4863int
4864ctl_disable_lun(struct ctl_be_lun *be_lun)
4865{
4866	struct ctl_softc *ctl_softc;
4867	struct ctl_port *port;
4868	struct ctl_lun *lun;
4869	int retval;
4870
4871	ctl_softc = control_softc;
4872
4873	lun = (struct ctl_lun *)be_lun->ctl_lun;
4874
4875	mtx_lock(&ctl_softc->ctl_lock);
4876	mtx_lock(&lun->lun_lock);
4877	if (lun->flags & CTL_LUN_DISABLED) {
4878		mtx_unlock(&lun->lun_lock);
4879		mtx_unlock(&ctl_softc->ctl_lock);
4880		return (0);
4881	}
4882	lun->flags |= CTL_LUN_DISABLED;
4883	mtx_unlock(&lun->lun_lock);
4884
4885	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4886		mtx_unlock(&ctl_softc->ctl_lock);
4887		/*
4888		 * Drop the lock before we call the frontend's disable
4889		 * routine, to avoid lock order reversals.
4890		 *
4891		 * XXX KDM what happens if the frontend list changes while
4892		 * we're traversing it?  It's unlikely, but should be handled.
4893		 */
4894		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4895					 lun->lun);
4896		mtx_lock(&ctl_softc->ctl_lock);
4897		if (retval != 0) {
4898			printf("ctl_alloc_lun: FETD %s port %d returned error "
4899			       "%d for lun_disable on target %ju lun %jd\n",
4900			       port->port_name, port->targ_port, retval,
4901			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4902		}
4903	}
4904
4905	mtx_unlock(&ctl_softc->ctl_lock);
4906
4907	return (0);
4908}
4909
4910int
4911ctl_start_lun(struct ctl_be_lun *be_lun)
4912{
4913	struct ctl_softc *ctl_softc;
4914	struct ctl_lun *lun;
4915
4916	ctl_softc = control_softc;
4917
4918	lun = (struct ctl_lun *)be_lun->ctl_lun;
4919
4920	mtx_lock(&lun->lun_lock);
4921	lun->flags &= ~CTL_LUN_STOPPED;
4922	mtx_unlock(&lun->lun_lock);
4923
4924	return (0);
4925}
4926
4927int
4928ctl_stop_lun(struct ctl_be_lun *be_lun)
4929{
4930	struct ctl_softc *ctl_softc;
4931	struct ctl_lun *lun;
4932
4933	ctl_softc = control_softc;
4934
4935	lun = (struct ctl_lun *)be_lun->ctl_lun;
4936
4937	mtx_lock(&lun->lun_lock);
4938	lun->flags |= CTL_LUN_STOPPED;
4939	mtx_unlock(&lun->lun_lock);
4940
4941	return (0);
4942}
4943
4944int
4945ctl_lun_offline(struct ctl_be_lun *be_lun)
4946{
4947	struct ctl_softc *ctl_softc;
4948	struct ctl_lun *lun;
4949
4950	ctl_softc = control_softc;
4951
4952	lun = (struct ctl_lun *)be_lun->ctl_lun;
4953
4954	mtx_lock(&lun->lun_lock);
4955	lun->flags |= CTL_LUN_OFFLINE;
4956	mtx_unlock(&lun->lun_lock);
4957
4958	return (0);
4959}
4960
4961int
4962ctl_lun_online(struct ctl_be_lun *be_lun)
4963{
4964	struct ctl_softc *ctl_softc;
4965	struct ctl_lun *lun;
4966
4967	ctl_softc = control_softc;
4968
4969	lun = (struct ctl_lun *)be_lun->ctl_lun;
4970
4971	mtx_lock(&lun->lun_lock);
4972	lun->flags &= ~CTL_LUN_OFFLINE;
4973	mtx_unlock(&lun->lun_lock);
4974
4975	return (0);
4976}
4977
4978int
4979ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4980{
4981	struct ctl_softc *ctl_softc;
4982	struct ctl_lun *lun;
4983
4984	ctl_softc = control_softc;
4985
4986	lun = (struct ctl_lun *)be_lun->ctl_lun;
4987
4988	mtx_lock(&lun->lun_lock);
4989
4990	/*
4991	 * The LUN needs to be disabled before it can be marked invalid.
4992	 */
4993	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4994		mtx_unlock(&lun->lun_lock);
4995		return (-1);
4996	}
4997	/*
4998	 * Mark the LUN invalid.
4999	 */
5000	lun->flags |= CTL_LUN_INVALID;
5001
5002	/*
5003	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5004	 * If we have something in the OOA queue, we'll free it when the
5005	 * last I/O completes.
5006	 */
5007	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5008		mtx_unlock(&lun->lun_lock);
5009		mtx_lock(&ctl_softc->ctl_lock);
5010		ctl_free_lun(lun);
5011		mtx_unlock(&ctl_softc->ctl_lock);
5012	} else
5013		mtx_unlock(&lun->lun_lock);
5014
5015	return (0);
5016}
5017
5018int
5019ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5020{
5021	struct ctl_softc *ctl_softc;
5022	struct ctl_lun *lun;
5023
5024	ctl_softc = control_softc;
5025	lun = (struct ctl_lun *)be_lun->ctl_lun;
5026
5027	mtx_lock(&lun->lun_lock);
5028	lun->flags |= CTL_LUN_INOPERABLE;
5029	mtx_unlock(&lun->lun_lock);
5030
5031	return (0);
5032}
5033
5034int
5035ctl_lun_operable(struct ctl_be_lun *be_lun)
5036{
5037	struct ctl_softc *ctl_softc;
5038	struct ctl_lun *lun;
5039
5040	ctl_softc = control_softc;
5041	lun = (struct ctl_lun *)be_lun->ctl_lun;
5042
5043	mtx_lock(&lun->lun_lock);
5044	lun->flags &= ~CTL_LUN_INOPERABLE;
5045	mtx_unlock(&lun->lun_lock);
5046
5047	return (0);
5048}
5049
5050int
5051ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5052		   int lock)
5053{
5054	struct ctl_softc *softc;
5055	struct ctl_lun *lun;
5056	struct copan_aps_subpage *current_sp;
5057	struct ctl_page_index *page_index;
5058	int i;
5059
5060	softc = control_softc;
5061
5062	mtx_lock(&softc->ctl_lock);
5063
5064	lun = (struct ctl_lun *)be_lun->ctl_lun;
5065	mtx_lock(&lun->lun_lock);
5066
5067	page_index = NULL;
5068	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5069		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5070		     APS_PAGE_CODE)
5071			continue;
5072
5073		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5074			continue;
5075		page_index = &lun->mode_pages.index[i];
5076	}
5077
5078	if (page_index == NULL) {
5079		mtx_unlock(&lun->lun_lock);
5080		mtx_unlock(&softc->ctl_lock);
5081		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5082		       (uintmax_t)lun->lun);
5083		return (1);
5084	}
5085#if 0
5086	if ((softc->aps_locked_lun != 0)
5087	 && (softc->aps_locked_lun != lun->lun)) {
5088		printf("%s: attempt to lock LUN %llu when %llu is already "
5089		       "locked\n");
5090		mtx_unlock(&lun->lun_lock);
5091		mtx_unlock(&softc->ctl_lock);
5092		return (1);
5093	}
5094#endif
5095
5096	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5097		(page_index->page_len * CTL_PAGE_CURRENT));
5098
5099	if (lock != 0) {
5100		current_sp->lock_active = APS_LOCK_ACTIVE;
5101		softc->aps_locked_lun = lun->lun;
5102	} else {
5103		current_sp->lock_active = 0;
5104		softc->aps_locked_lun = 0;
5105	}
5106
5107
5108	/*
5109	 * If we're in HA mode, try to send the lock message to the other
5110	 * side.
5111	 */
5112	if (ctl_is_single == 0) {
5113		int isc_retval;
5114		union ctl_ha_msg lock_msg;
5115
5116		lock_msg.hdr.nexus = *nexus;
5117		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5118		if (lock != 0)
5119			lock_msg.aps.lock_flag = 1;
5120		else
5121			lock_msg.aps.lock_flag = 0;
5122		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5123					 sizeof(lock_msg), 0);
5124		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5125			printf("%s: APS (lock=%d) error returned from "
5126			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5127			mtx_unlock(&lun->lun_lock);
5128			mtx_unlock(&softc->ctl_lock);
5129			return (1);
5130		}
5131	}
5132
5133	mtx_unlock(&lun->lun_lock);
5134	mtx_unlock(&softc->ctl_lock);
5135
5136	return (0);
5137}
5138
5139void
5140ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5141{
5142	struct ctl_lun *lun;
5143	struct ctl_softc *softc;
5144	int i;
5145
5146	softc = control_softc;
5147
5148	lun = (struct ctl_lun *)be_lun->ctl_lun;
5149
5150	mtx_lock(&lun->lun_lock);
5151
5152	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5153		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5154
5155	mtx_unlock(&lun->lun_lock);
5156}
5157
5158/*
5159 * Backend "memory move is complete" callback for requests that never
5160 * make it down to say RAIDCore's configuration code.
5161 */
5162int
5163ctl_config_move_done(union ctl_io *io)
5164{
5165	int retval;
5166
5167	retval = CTL_RETVAL_COMPLETE;
5168
5169
5170	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5171	/*
5172	 * XXX KDM this shouldn't happen, but what if it does?
5173	 */
5174	if (io->io_hdr.io_type != CTL_IO_SCSI)
5175		panic("I/O type isn't CTL_IO_SCSI!");
5176
5177	if ((io->io_hdr.port_status == 0)
5178	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5179	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5180		io->io_hdr.status = CTL_SUCCESS;
5181	else if ((io->io_hdr.port_status != 0)
5182	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5183	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5184		/*
5185		 * For hardware error sense keys, the sense key
5186		 * specific value is defined to be a retry count,
5187		 * but we use it to pass back an internal FETD
5188		 * error code.  XXX KDM  Hopefully the FETD is only
5189		 * using 16 bits for an error code, since that's
5190		 * all the space we have in the sks field.
5191		 */
5192		ctl_set_internal_failure(&io->scsiio,
5193					 /*sks_valid*/ 1,
5194					 /*retry_count*/
5195					 io->io_hdr.port_status);
5196		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5197			free(io->scsiio.kern_data_ptr, M_CTL);
5198		ctl_done(io);
5199		goto bailout;
5200	}
5201
5202	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5203	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5204	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5205		/*
5206		 * XXX KDM just assuming a single pointer here, and not a
5207		 * S/G list.  If we start using S/G lists for config data,
5208		 * we'll need to know how to clean them up here as well.
5209		 */
5210		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5211			free(io->scsiio.kern_data_ptr, M_CTL);
5212		/* Hopefully the user has already set the status... */
5213		ctl_done(io);
5214	} else {
5215		/*
5216		 * XXX KDM now we need to continue data movement.  Some
5217		 * options:
5218		 * - call ctl_scsiio() again?  We don't do this for data
5219		 *   writes, because for those at least we know ahead of
5220		 *   time where the write will go and how long it is.  For
5221		 *   config writes, though, that information is largely
5222		 *   contained within the write itself, thus we need to
5223		 *   parse out the data again.
5224		 *
5225		 * - Call some other function once the data is in?
5226		 */
5227
5228		/*
5229		 * XXX KDM call ctl_scsiio() again for now, and check flag
5230		 * bits to see whether we're allocated or not.
5231		 */
5232		retval = ctl_scsiio(&io->scsiio);
5233	}
5234bailout:
5235	return (retval);
5236}
5237
5238/*
5239 * This gets called by a backend driver when it is done with a
5240 * data_submit method.
5241 */
5242void
5243ctl_data_submit_done(union ctl_io *io)
5244{
5245	/*
5246	 * If the IO_CONT flag is set, we need to call the supplied
5247	 * function to continue processing the I/O, instead of completing
5248	 * the I/O just yet.
5249	 *
5250	 * If there is an error, though, we don't want to keep processing.
5251	 * Instead, just send status back to the initiator.
5252	 */
5253	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5254	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5255	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5256	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5257		io->scsiio.io_cont(io);
5258		return;
5259	}
5260	ctl_done(io);
5261}
5262
5263/*
5264 * This gets called by a backend driver when it is done with a
5265 * configuration write.
5266 */
5267void
5268ctl_config_write_done(union ctl_io *io)
5269{
5270	uint8_t *buf;
5271
5272	/*
5273	 * If the IO_CONT flag is set, we need to call the supplied
5274	 * function to continue processing the I/O, instead of completing
5275	 * the I/O just yet.
5276	 *
5277	 * If there is an error, though, we don't want to keep processing.
5278	 * Instead, just send status back to the initiator.
5279	 */
5280	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5281	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5282	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5283		io->scsiio.io_cont(io);
5284		return;
5285	}
5286	/*
5287	 * Since a configuration write can be done for commands that actually
5288	 * have data allocated, like write buffer, and commands that have
5289	 * no data, like start/stop unit, we need to check here.
5290	 */
5291	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5292		buf = io->scsiio.kern_data_ptr;
5293	else
5294		buf = NULL;
5295	ctl_done(io);
5296	if (buf)
5297		free(buf, M_CTL);
5298}
5299
5300/*
5301 * SCSI release command.
5302 */
5303int
5304ctl_scsi_release(struct ctl_scsiio *ctsio)
5305{
5306	int length, longid, thirdparty_id, resv_id;
5307	struct ctl_softc *ctl_softc;
5308	struct ctl_lun *lun;
5309
5310	length = 0;
5311	resv_id = 0;
5312
5313	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5314
5315	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5316	ctl_softc = control_softc;
5317
5318	switch (ctsio->cdb[0]) {
5319	case RELEASE_10: {
5320		struct scsi_release_10 *cdb;
5321
5322		cdb = (struct scsi_release_10 *)ctsio->cdb;
5323
5324		if (cdb->byte2 & SR10_LONGID)
5325			longid = 1;
5326		else
5327			thirdparty_id = cdb->thirdparty_id;
5328
5329		resv_id = cdb->resv_id;
5330		length = scsi_2btoul(cdb->length);
5331		break;
5332	}
5333	}
5334
5335
5336	/*
5337	 * XXX KDM right now, we only support LUN reservation.  We don't
5338	 * support 3rd party reservations, or extent reservations, which
5339	 * might actually need the parameter list.  If we've gotten this
5340	 * far, we've got a LUN reservation.  Anything else got kicked out
5341	 * above.  So, according to SPC, ignore the length.
5342	 */
5343	length = 0;
5344
5345	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5346	 && (length > 0)) {
5347		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5348		ctsio->kern_data_len = length;
5349		ctsio->kern_total_len = length;
5350		ctsio->kern_data_resid = 0;
5351		ctsio->kern_rel_offset = 0;
5352		ctsio->kern_sg_entries = 0;
5353		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5354		ctsio->be_move_done = ctl_config_move_done;
5355		ctl_datamove((union ctl_io *)ctsio);
5356
5357		return (CTL_RETVAL_COMPLETE);
5358	}
5359
5360	if (length > 0)
5361		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5362
5363	mtx_lock(&lun->lun_lock);
5364
5365	/*
5366	 * According to SPC, it is not an error for an intiator to attempt
5367	 * to release a reservation on a LUN that isn't reserved, or that
5368	 * is reserved by another initiator.  The reservation can only be
5369	 * released, though, by the initiator who made it or by one of
5370	 * several reset type events.
5371	 */
5372	if (lun->flags & CTL_LUN_RESERVED) {
5373		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5374		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5375		 && (ctsio->io_hdr.nexus.targ_target.id ==
5376		     lun->rsv_nexus.targ_target.id)) {
5377			lun->flags &= ~CTL_LUN_RESERVED;
5378		}
5379	}
5380
5381	mtx_unlock(&lun->lun_lock);
5382
5383	ctsio->scsi_status = SCSI_STATUS_OK;
5384	ctsio->io_hdr.status = CTL_SUCCESS;
5385
5386	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5387		free(ctsio->kern_data_ptr, M_CTL);
5388		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5389	}
5390
5391	ctl_done((union ctl_io *)ctsio);
5392	return (CTL_RETVAL_COMPLETE);
5393}
5394
5395int
5396ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5397{
5398	int extent, thirdparty, longid;
5399	int resv_id, length;
5400	uint64_t thirdparty_id;
5401	struct ctl_softc *ctl_softc;
5402	struct ctl_lun *lun;
5403
5404	extent = 0;
5405	thirdparty = 0;
5406	longid = 0;
5407	resv_id = 0;
5408	length = 0;
5409	thirdparty_id = 0;
5410
5411	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5412
5413	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5414	ctl_softc = control_softc;
5415
5416	switch (ctsio->cdb[0]) {
5417	case RESERVE_10: {
5418		struct scsi_reserve_10 *cdb;
5419
5420		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5421
5422		if (cdb->byte2 & SR10_LONGID)
5423			longid = 1;
5424		else
5425			thirdparty_id = cdb->thirdparty_id;
5426
5427		resv_id = cdb->resv_id;
5428		length = scsi_2btoul(cdb->length);
5429		break;
5430	}
5431	}
5432
5433	/*
5434	 * XXX KDM right now, we only support LUN reservation.  We don't
5435	 * support 3rd party reservations, or extent reservations, which
5436	 * might actually need the parameter list.  If we've gotten this
5437	 * far, we've got a LUN reservation.  Anything else got kicked out
5438	 * above.  So, according to SPC, ignore the length.
5439	 */
5440	length = 0;
5441
5442	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5443	 && (length > 0)) {
5444		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5445		ctsio->kern_data_len = length;
5446		ctsio->kern_total_len = length;
5447		ctsio->kern_data_resid = 0;
5448		ctsio->kern_rel_offset = 0;
5449		ctsio->kern_sg_entries = 0;
5450		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5451		ctsio->be_move_done = ctl_config_move_done;
5452		ctl_datamove((union ctl_io *)ctsio);
5453
5454		return (CTL_RETVAL_COMPLETE);
5455	}
5456
5457	if (length > 0)
5458		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5459
5460	mtx_lock(&lun->lun_lock);
5461	if (lun->flags & CTL_LUN_RESERVED) {
5462		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5463		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5464		 || (ctsio->io_hdr.nexus.targ_target.id !=
5465		     lun->rsv_nexus.targ_target.id)) {
5466			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5467			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5468			goto bailout;
5469		}
5470	}
5471
5472	lun->flags |= CTL_LUN_RESERVED;
5473	lun->rsv_nexus = ctsio->io_hdr.nexus;
5474
5475	ctsio->scsi_status = SCSI_STATUS_OK;
5476	ctsio->io_hdr.status = CTL_SUCCESS;
5477
5478bailout:
5479	mtx_unlock(&lun->lun_lock);
5480
5481	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5482		free(ctsio->kern_data_ptr, M_CTL);
5483		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5484	}
5485
5486	ctl_done((union ctl_io *)ctsio);
5487	return (CTL_RETVAL_COMPLETE);
5488}
5489
5490int
5491ctl_start_stop(struct ctl_scsiio *ctsio)
5492{
5493	struct scsi_start_stop_unit *cdb;
5494	struct ctl_lun *lun;
5495	struct ctl_softc *ctl_softc;
5496	int retval;
5497
5498	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5499
5500	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5501	ctl_softc = control_softc;
5502	retval = 0;
5503
5504	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5505
5506	/*
5507	 * XXX KDM
5508	 * We don't support the immediate bit on a stop unit.  In order to
5509	 * do that, we would need to code up a way to know that a stop is
5510	 * pending, and hold off any new commands until it completes, one
5511	 * way or another.  Then we could accept or reject those commands
5512	 * depending on its status.  We would almost need to do the reverse
5513	 * of what we do below for an immediate start -- return the copy of
5514	 * the ctl_io to the FETD with status to send to the host (and to
5515	 * free the copy!) and then free the original I/O once the stop
5516	 * actually completes.  That way, the OOA queue mechanism can work
5517	 * to block commands that shouldn't proceed.  Another alternative
5518	 * would be to put the copy in the queue in place of the original,
5519	 * and return the original back to the caller.  That could be
5520	 * slightly safer..
5521	 */
5522	if ((cdb->byte2 & SSS_IMMED)
5523	 && ((cdb->how & SSS_START) == 0)) {
5524		ctl_set_invalid_field(ctsio,
5525				      /*sks_valid*/ 1,
5526				      /*command*/ 1,
5527				      /*field*/ 1,
5528				      /*bit_valid*/ 1,
5529				      /*bit*/ 0);
5530		ctl_done((union ctl_io *)ctsio);
5531		return (CTL_RETVAL_COMPLETE);
5532	}
5533
5534	if ((lun->flags & CTL_LUN_PR_RESERVED)
5535	 && ((cdb->how & SSS_START)==0)) {
5536		uint32_t residx;
5537
5538		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5539		if (!lun->per_res[residx].registered
5540		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5541
5542			ctl_set_reservation_conflict(ctsio);
5543			ctl_done((union ctl_io *)ctsio);
5544			return (CTL_RETVAL_COMPLETE);
5545		}
5546	}
5547
5548	/*
5549	 * If there is no backend on this device, we can't start or stop
5550	 * it.  In theory we shouldn't get any start/stop commands in the
5551	 * first place at this level if the LUN doesn't have a backend.
5552	 * That should get stopped by the command decode code.
5553	 */
5554	if (lun->backend == NULL) {
5555		ctl_set_invalid_opcode(ctsio);
5556		ctl_done((union ctl_io *)ctsio);
5557		return (CTL_RETVAL_COMPLETE);
5558	}
5559
5560	/*
5561	 * XXX KDM Copan-specific offline behavior.
5562	 * Figure out a reasonable way to port this?
5563	 */
5564#ifdef NEEDTOPORT
5565	mtx_lock(&lun->lun_lock);
5566
5567	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5568	 && (lun->flags & CTL_LUN_OFFLINE)) {
5569		/*
5570		 * If the LUN is offline, and the on/offline bit isn't set,
5571		 * reject the start or stop.  Otherwise, let it through.
5572		 */
5573		mtx_unlock(&lun->lun_lock);
5574		ctl_set_lun_not_ready(ctsio);
5575		ctl_done((union ctl_io *)ctsio);
5576	} else {
5577		mtx_unlock(&lun->lun_lock);
5578#endif /* NEEDTOPORT */
5579		/*
5580		 * This could be a start or a stop when we're online,
5581		 * or a stop/offline or start/online.  A start or stop when
5582		 * we're offline is covered in the case above.
5583		 */
5584		/*
5585		 * In the non-immediate case, we send the request to
5586		 * the backend and return status to the user when
5587		 * it is done.
5588		 *
5589		 * In the immediate case, we allocate a new ctl_io
5590		 * to hold a copy of the request, and send that to
5591		 * the backend.  We then set good status on the
5592		 * user's request and return it immediately.
5593		 */
5594		if (cdb->byte2 & SSS_IMMED) {
5595			union ctl_io *new_io;
5596
5597			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5598			if (new_io == NULL) {
5599				ctl_set_busy(ctsio);
5600				ctl_done((union ctl_io *)ctsio);
5601			} else {
5602				ctl_copy_io((union ctl_io *)ctsio,
5603					    new_io);
5604				retval = lun->backend->config_write(new_io);
5605				ctl_set_success(ctsio);
5606				ctl_done((union ctl_io *)ctsio);
5607			}
5608		} else {
5609			retval = lun->backend->config_write(
5610				(union ctl_io *)ctsio);
5611		}
5612#ifdef NEEDTOPORT
5613	}
5614#endif
5615	return (retval);
5616}
5617
5618/*
5619 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5620 * we don't really do anything with the LBA and length fields if the user
5621 * passes them in.  Instead we'll just flush out the cache for the entire
5622 * LUN.
5623 */
5624int
5625ctl_sync_cache(struct ctl_scsiio *ctsio)
5626{
5627	struct ctl_lun *lun;
5628	struct ctl_softc *ctl_softc;
5629	uint64_t starting_lba;
5630	uint32_t block_count;
5631	int retval;
5632
5633	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5634
5635	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5636	ctl_softc = control_softc;
5637	retval = 0;
5638
5639	switch (ctsio->cdb[0]) {
5640	case SYNCHRONIZE_CACHE: {
5641		struct scsi_sync_cache *cdb;
5642		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5643
5644		starting_lba = scsi_4btoul(cdb->begin_lba);
5645		block_count = scsi_2btoul(cdb->lb_count);
5646		break;
5647	}
5648	case SYNCHRONIZE_CACHE_16: {
5649		struct scsi_sync_cache_16 *cdb;
5650		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5651
5652		starting_lba = scsi_8btou64(cdb->begin_lba);
5653		block_count = scsi_4btoul(cdb->lb_count);
5654		break;
5655	}
5656	default:
5657		ctl_set_invalid_opcode(ctsio);
5658		ctl_done((union ctl_io *)ctsio);
5659		goto bailout;
5660		break; /* NOTREACHED */
5661	}
5662
5663	/*
5664	 * We check the LBA and length, but don't do anything with them.
5665	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5666	 * get flushed.  This check will just help satisfy anyone who wants
5667	 * to see an error for an out of range LBA.
5668	 */
5669	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5670		ctl_set_lba_out_of_range(ctsio);
5671		ctl_done((union ctl_io *)ctsio);
5672		goto bailout;
5673	}
5674
5675	/*
5676	 * If this LUN has no backend, we can't flush the cache anyway.
5677	 */
5678	if (lun->backend == NULL) {
5679		ctl_set_invalid_opcode(ctsio);
5680		ctl_done((union ctl_io *)ctsio);
5681		goto bailout;
5682	}
5683
5684	/*
5685	 * Check to see whether we're configured to send the SYNCHRONIZE
5686	 * CACHE command directly to the back end.
5687	 */
5688	mtx_lock(&lun->lun_lock);
5689	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5690	 && (++(lun->sync_count) >= lun->sync_interval)) {
5691		lun->sync_count = 0;
5692		mtx_unlock(&lun->lun_lock);
5693		retval = lun->backend->config_write((union ctl_io *)ctsio);
5694	} else {
5695		mtx_unlock(&lun->lun_lock);
5696		ctl_set_success(ctsio);
5697		ctl_done((union ctl_io *)ctsio);
5698	}
5699
5700bailout:
5701
5702	return (retval);
5703}
5704
5705int
5706ctl_format(struct ctl_scsiio *ctsio)
5707{
5708	struct scsi_format *cdb;
5709	struct ctl_lun *lun;
5710	struct ctl_softc *ctl_softc;
5711	int length, defect_list_len;
5712
5713	CTL_DEBUG_PRINT(("ctl_format\n"));
5714
5715	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5716	ctl_softc = control_softc;
5717
5718	cdb = (struct scsi_format *)ctsio->cdb;
5719
5720	length = 0;
5721	if (cdb->byte2 & SF_FMTDATA) {
5722		if (cdb->byte2 & SF_LONGLIST)
5723			length = sizeof(struct scsi_format_header_long);
5724		else
5725			length = sizeof(struct scsi_format_header_short);
5726	}
5727
5728	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5729	 && (length > 0)) {
5730		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5731		ctsio->kern_data_len = length;
5732		ctsio->kern_total_len = length;
5733		ctsio->kern_data_resid = 0;
5734		ctsio->kern_rel_offset = 0;
5735		ctsio->kern_sg_entries = 0;
5736		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5737		ctsio->be_move_done = ctl_config_move_done;
5738		ctl_datamove((union ctl_io *)ctsio);
5739
5740		return (CTL_RETVAL_COMPLETE);
5741	}
5742
5743	defect_list_len = 0;
5744
5745	if (cdb->byte2 & SF_FMTDATA) {
5746		if (cdb->byte2 & SF_LONGLIST) {
5747			struct scsi_format_header_long *header;
5748
5749			header = (struct scsi_format_header_long *)
5750				ctsio->kern_data_ptr;
5751
5752			defect_list_len = scsi_4btoul(header->defect_list_len);
5753			if (defect_list_len != 0) {
5754				ctl_set_invalid_field(ctsio,
5755						      /*sks_valid*/ 1,
5756						      /*command*/ 0,
5757						      /*field*/ 2,
5758						      /*bit_valid*/ 0,
5759						      /*bit*/ 0);
5760				goto bailout;
5761			}
5762		} else {
5763			struct scsi_format_header_short *header;
5764
5765			header = (struct scsi_format_header_short *)
5766				ctsio->kern_data_ptr;
5767
5768			defect_list_len = scsi_2btoul(header->defect_list_len);
5769			if (defect_list_len != 0) {
5770				ctl_set_invalid_field(ctsio,
5771						      /*sks_valid*/ 1,
5772						      /*command*/ 0,
5773						      /*field*/ 2,
5774						      /*bit_valid*/ 0,
5775						      /*bit*/ 0);
5776				goto bailout;
5777			}
5778		}
5779	}
5780
5781	/*
5782	 * The format command will clear out the "Medium format corrupted"
5783	 * status if set by the configuration code.  That status is really
5784	 * just a way to notify the host that we have lost the media, and
5785	 * get them to issue a command that will basically make them think
5786	 * they're blowing away the media.
5787	 */
5788	mtx_lock(&lun->lun_lock);
5789	lun->flags &= ~CTL_LUN_INOPERABLE;
5790	mtx_unlock(&lun->lun_lock);
5791
5792	ctsio->scsi_status = SCSI_STATUS_OK;
5793	ctsio->io_hdr.status = CTL_SUCCESS;
5794bailout:
5795
5796	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5797		free(ctsio->kern_data_ptr, M_CTL);
5798		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5799	}
5800
5801	ctl_done((union ctl_io *)ctsio);
5802	return (CTL_RETVAL_COMPLETE);
5803}
5804
5805int
5806ctl_read_buffer(struct ctl_scsiio *ctsio)
5807{
5808	struct scsi_read_buffer *cdb;
5809	struct ctl_lun *lun;
5810	int buffer_offset, len;
5811	static uint8_t descr[4];
5812	static uint8_t echo_descr[4] = { 0 };
5813
5814	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5815
5816	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5817	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5818
5819	if (lun->flags & CTL_LUN_PR_RESERVED) {
5820		uint32_t residx;
5821
5822		/*
5823		 * XXX KDM need a lock here.
5824		 */
5825		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5826		if ((lun->res_type == SPR_TYPE_EX_AC
5827		  && residx != lun->pr_res_idx)
5828		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5829		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5830		  && !lun->per_res[residx].registered)) {
5831			ctl_set_reservation_conflict(ctsio);
5832			ctl_done((union ctl_io *)ctsio);
5833			return (CTL_RETVAL_COMPLETE);
5834	        }
5835	}
5836
5837	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5838	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5839	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5840		ctl_set_invalid_field(ctsio,
5841				      /*sks_valid*/ 1,
5842				      /*command*/ 1,
5843				      /*field*/ 1,
5844				      /*bit_valid*/ 1,
5845				      /*bit*/ 4);
5846		ctl_done((union ctl_io *)ctsio);
5847		return (CTL_RETVAL_COMPLETE);
5848	}
5849
5850	len = scsi_3btoul(cdb->length);
5851	buffer_offset = scsi_3btoul(cdb->offset);
5852
5853	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5854		ctl_set_invalid_field(ctsio,
5855				      /*sks_valid*/ 1,
5856				      /*command*/ 1,
5857				      /*field*/ 6,
5858				      /*bit_valid*/ 0,
5859				      /*bit*/ 0);
5860		ctl_done((union ctl_io *)ctsio);
5861		return (CTL_RETVAL_COMPLETE);
5862	}
5863
5864	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5865		descr[0] = 0;
5866		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5867		ctsio->kern_data_ptr = descr;
5868		len = min(len, sizeof(descr));
5869	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5870		ctsio->kern_data_ptr = echo_descr;
5871		len = min(len, sizeof(echo_descr));
5872	} else
5873		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5874	ctsio->kern_data_len = len;
5875	ctsio->kern_total_len = len;
5876	ctsio->kern_data_resid = 0;
5877	ctsio->kern_rel_offset = 0;
5878	ctsio->kern_sg_entries = 0;
5879	ctsio->be_move_done = ctl_config_move_done;
5880	ctl_datamove((union ctl_io *)ctsio);
5881
5882	return (CTL_RETVAL_COMPLETE);
5883}
5884
5885int
5886ctl_write_buffer(struct ctl_scsiio *ctsio)
5887{
5888	struct scsi_write_buffer *cdb;
5889	struct ctl_lun *lun;
5890	int buffer_offset, len;
5891
5892	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5893
5894	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5895	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5896
5897	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5898		ctl_set_invalid_field(ctsio,
5899				      /*sks_valid*/ 1,
5900				      /*command*/ 1,
5901				      /*field*/ 1,
5902				      /*bit_valid*/ 1,
5903				      /*bit*/ 4);
5904		ctl_done((union ctl_io *)ctsio);
5905		return (CTL_RETVAL_COMPLETE);
5906	}
5907
5908	len = scsi_3btoul(cdb->length);
5909	buffer_offset = scsi_3btoul(cdb->offset);
5910
5911	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5912		ctl_set_invalid_field(ctsio,
5913				      /*sks_valid*/ 1,
5914				      /*command*/ 1,
5915				      /*field*/ 6,
5916				      /*bit_valid*/ 0,
5917				      /*bit*/ 0);
5918		ctl_done((union ctl_io *)ctsio);
5919		return (CTL_RETVAL_COMPLETE);
5920	}
5921
5922	/*
5923	 * If we've got a kernel request that hasn't been malloced yet,
5924	 * malloc it and tell the caller the data buffer is here.
5925	 */
5926	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5927		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5928		ctsio->kern_data_len = len;
5929		ctsio->kern_total_len = len;
5930		ctsio->kern_data_resid = 0;
5931		ctsio->kern_rel_offset = 0;
5932		ctsio->kern_sg_entries = 0;
5933		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5934		ctsio->be_move_done = ctl_config_move_done;
5935		ctl_datamove((union ctl_io *)ctsio);
5936
5937		return (CTL_RETVAL_COMPLETE);
5938	}
5939
5940	ctl_done((union ctl_io *)ctsio);
5941
5942	return (CTL_RETVAL_COMPLETE);
5943}
5944
5945int
5946ctl_write_same(struct ctl_scsiio *ctsio)
5947{
5948	struct ctl_lun *lun;
5949	struct ctl_lba_len_flags *lbalen;
5950	uint64_t lba;
5951	uint32_t num_blocks;
5952	int len, retval;
5953	uint8_t byte2;
5954
5955	retval = CTL_RETVAL_COMPLETE;
5956
5957	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5958
5959	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5960
5961	switch (ctsio->cdb[0]) {
5962	case WRITE_SAME_10: {
5963		struct scsi_write_same_10 *cdb;
5964
5965		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5966
5967		lba = scsi_4btoul(cdb->addr);
5968		num_blocks = scsi_2btoul(cdb->length);
5969		byte2 = cdb->byte2;
5970		break;
5971	}
5972	case WRITE_SAME_16: {
5973		struct scsi_write_same_16 *cdb;
5974
5975		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5976
5977		lba = scsi_8btou64(cdb->addr);
5978		num_blocks = scsi_4btoul(cdb->length);
5979		byte2 = cdb->byte2;
5980		break;
5981	}
5982	default:
5983		/*
5984		 * We got a command we don't support.  This shouldn't
5985		 * happen, commands should be filtered out above us.
5986		 */
5987		ctl_set_invalid_opcode(ctsio);
5988		ctl_done((union ctl_io *)ctsio);
5989
5990		return (CTL_RETVAL_COMPLETE);
5991		break; /* NOTREACHED */
5992	}
5993
5994	/*
5995	 * The first check is to make sure we're in bounds, the second
5996	 * check is to catch wrap-around problems.  If the lba + num blocks
5997	 * is less than the lba, then we've wrapped around and the block
5998	 * range is invalid anyway.
5999	 */
6000	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6001	 || ((lba + num_blocks) < lba)) {
6002		ctl_set_lba_out_of_range(ctsio);
6003		ctl_done((union ctl_io *)ctsio);
6004		return (CTL_RETVAL_COMPLETE);
6005	}
6006
6007	/* Zero number of blocks means "to the last logical block" */
6008	if (num_blocks == 0) {
6009		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6010			ctl_set_invalid_field(ctsio,
6011					      /*sks_valid*/ 0,
6012					      /*command*/ 1,
6013					      /*field*/ 0,
6014					      /*bit_valid*/ 0,
6015					      /*bit*/ 0);
6016			ctl_done((union ctl_io *)ctsio);
6017			return (CTL_RETVAL_COMPLETE);
6018		}
6019		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6020	}
6021
6022	len = lun->be_lun->blocksize;
6023
6024	/*
6025	 * If we've got a kernel request that hasn't been malloced yet,
6026	 * malloc it and tell the caller the data buffer is here.
6027	 */
6028	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6029		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6030		ctsio->kern_data_len = len;
6031		ctsio->kern_total_len = len;
6032		ctsio->kern_data_resid = 0;
6033		ctsio->kern_rel_offset = 0;
6034		ctsio->kern_sg_entries = 0;
6035		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6036		ctsio->be_move_done = ctl_config_move_done;
6037		ctl_datamove((union ctl_io *)ctsio);
6038
6039		return (CTL_RETVAL_COMPLETE);
6040	}
6041
6042	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6043	lbalen->lba = lba;
6044	lbalen->len = num_blocks;
6045	lbalen->flags = byte2;
6046	retval = lun->backend->config_write((union ctl_io *)ctsio);
6047
6048	return (retval);
6049}
6050
6051int
6052ctl_unmap(struct ctl_scsiio *ctsio)
6053{
6054	struct ctl_lun *lun;
6055	struct scsi_unmap *cdb;
6056	struct ctl_ptr_len_flags *ptrlen;
6057	struct scsi_unmap_header *hdr;
6058	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6059	uint64_t lba;
6060	uint32_t num_blocks;
6061	int len, retval;
6062	uint8_t byte2;
6063
6064	retval = CTL_RETVAL_COMPLETE;
6065
6066	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6067
6068	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6069	cdb = (struct scsi_unmap *)ctsio->cdb;
6070
6071	len = scsi_2btoul(cdb->length);
6072	byte2 = cdb->byte2;
6073
6074	/*
6075	 * If we've got a kernel request that hasn't been malloced yet,
6076	 * malloc it and tell the caller the data buffer is here.
6077	 */
6078	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6079		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6080		ctsio->kern_data_len = len;
6081		ctsio->kern_total_len = len;
6082		ctsio->kern_data_resid = 0;
6083		ctsio->kern_rel_offset = 0;
6084		ctsio->kern_sg_entries = 0;
6085		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6086		ctsio->be_move_done = ctl_config_move_done;
6087		ctl_datamove((union ctl_io *)ctsio);
6088
6089		return (CTL_RETVAL_COMPLETE);
6090	}
6091
6092	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6093	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6094	if (len < sizeof (*hdr) ||
6095	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6096	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6097	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6098		ctl_set_invalid_field(ctsio,
6099				      /*sks_valid*/ 0,
6100				      /*command*/ 0,
6101				      /*field*/ 0,
6102				      /*bit_valid*/ 0,
6103				      /*bit*/ 0);
6104		ctl_done((union ctl_io *)ctsio);
6105		return (CTL_RETVAL_COMPLETE);
6106	}
6107	len = scsi_2btoul(hdr->desc_length);
6108	buf = (struct scsi_unmap_desc *)(hdr + 1);
6109	end = buf + len / sizeof(*buf);
6110
6111	endnz = buf;
6112	for (range = buf; range < end; range++) {
6113		lba = scsi_8btou64(range->lba);
6114		num_blocks = scsi_4btoul(range->length);
6115		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6116		 || ((lba + num_blocks) < lba)) {
6117			ctl_set_lba_out_of_range(ctsio);
6118			ctl_done((union ctl_io *)ctsio);
6119			return (CTL_RETVAL_COMPLETE);
6120		}
6121		if (num_blocks != 0)
6122			endnz = range + 1;
6123	}
6124
6125	/*
6126	 * Block backend can not handle zero last range.
6127	 * Filter it out and return if there is nothing left.
6128	 */
6129	len = (uint8_t *)endnz - (uint8_t *)buf;
6130	if (len == 0) {
6131		ctl_set_success(ctsio);
6132		ctl_done((union ctl_io *)ctsio);
6133		return (CTL_RETVAL_COMPLETE);
6134	}
6135
6136	mtx_lock(&lun->lun_lock);
6137	ptrlen = (struct ctl_ptr_len_flags *)
6138	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6139	ptrlen->ptr = (void *)buf;
6140	ptrlen->len = len;
6141	ptrlen->flags = byte2;
6142	ctl_check_blocked(lun);
6143	mtx_unlock(&lun->lun_lock);
6144
6145	retval = lun->backend->config_write((union ctl_io *)ctsio);
6146	return (retval);
6147}
6148
6149/*
6150 * Note that this function currently doesn't actually do anything inside
6151 * CTL to enforce things if the DQue bit is turned on.
6152 *
6153 * Also note that this function can't be used in the default case, because
6154 * the DQue bit isn't set in the changeable mask for the control mode page
6155 * anyway.  This is just here as an example for how to implement a page
6156 * handler, and a placeholder in case we want to allow the user to turn
6157 * tagged queueing on and off.
6158 *
6159 * The D_SENSE bit handling is functional, however, and will turn
6160 * descriptor sense on and off for a given LUN.
6161 */
6162int
6163ctl_control_page_handler(struct ctl_scsiio *ctsio,
6164			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6165{
6166	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6167	struct ctl_lun *lun;
6168	struct ctl_softc *softc;
6169	int set_ua;
6170	uint32_t initidx;
6171
6172	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6173	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6174	set_ua = 0;
6175
6176	user_cp = (struct scsi_control_page *)page_ptr;
6177	current_cp = (struct scsi_control_page *)
6178		(page_index->page_data + (page_index->page_len *
6179		CTL_PAGE_CURRENT));
6180	saved_cp = (struct scsi_control_page *)
6181		(page_index->page_data + (page_index->page_len *
6182		CTL_PAGE_SAVED));
6183
6184	softc = control_softc;
6185
6186	mtx_lock(&lun->lun_lock);
6187	if (((current_cp->rlec & SCP_DSENSE) == 0)
6188	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6189		/*
6190		 * Descriptor sense is currently turned off and the user
6191		 * wants to turn it on.
6192		 */
6193		current_cp->rlec |= SCP_DSENSE;
6194		saved_cp->rlec |= SCP_DSENSE;
6195		lun->flags |= CTL_LUN_SENSE_DESC;
6196		set_ua = 1;
6197	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6198		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6199		/*
6200		 * Descriptor sense is currently turned on, and the user
6201		 * wants to turn it off.
6202		 */
6203		current_cp->rlec &= ~SCP_DSENSE;
6204		saved_cp->rlec &= ~SCP_DSENSE;
6205		lun->flags &= ~CTL_LUN_SENSE_DESC;
6206		set_ua = 1;
6207	}
6208	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6209		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6210#ifdef NEEDTOPORT
6211			csevent_log(CSC_CTL | CSC_SHELF_SW |
6212				    CTL_UNTAG_TO_UNTAG,
6213				    csevent_LogType_Trace,
6214				    csevent_Severity_Information,
6215				    csevent_AlertLevel_Green,
6216				    csevent_FRU_Firmware,
6217				    csevent_FRU_Unknown,
6218				    "Received untagged to untagged transition");
6219#endif /* NEEDTOPORT */
6220		} else {
6221#ifdef NEEDTOPORT
6222			csevent_log(CSC_CTL | CSC_SHELF_SW |
6223				    CTL_UNTAG_TO_TAG,
6224				    csevent_LogType_ConfigChange,
6225				    csevent_Severity_Information,
6226				    csevent_AlertLevel_Green,
6227				    csevent_FRU_Firmware,
6228				    csevent_FRU_Unknown,
6229				    "Received untagged to tagged "
6230				    "queueing transition");
6231#endif /* NEEDTOPORT */
6232
6233			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6234			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6235			set_ua = 1;
6236		}
6237	} else {
6238		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6239#ifdef NEEDTOPORT
6240			csevent_log(CSC_CTL | CSC_SHELF_SW |
6241				    CTL_TAG_TO_UNTAG,
6242				    csevent_LogType_ConfigChange,
6243				    csevent_Severity_Warning,
6244				    csevent_AlertLevel_Yellow,
6245				    csevent_FRU_Firmware,
6246				    csevent_FRU_Unknown,
6247				    "Received tagged queueing to untagged "
6248				    "transition");
6249#endif /* NEEDTOPORT */
6250
6251			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6252			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6253			set_ua = 1;
6254		} else {
6255#ifdef NEEDTOPORT
6256			csevent_log(CSC_CTL | CSC_SHELF_SW |
6257				    CTL_TAG_TO_TAG,
6258				    csevent_LogType_Trace,
6259				    csevent_Severity_Information,
6260				    csevent_AlertLevel_Green,
6261				    csevent_FRU_Firmware,
6262				    csevent_FRU_Unknown,
6263				    "Received tagged queueing to tagged "
6264				    "queueing transition");
6265#endif /* NEEDTOPORT */
6266		}
6267	}
6268	if (set_ua != 0) {
6269		int i;
6270		/*
6271		 * Let other initiators know that the mode
6272		 * parameters for this LUN have changed.
6273		 */
6274		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6275			if (i == initidx)
6276				continue;
6277
6278			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6279		}
6280	}
6281	mtx_unlock(&lun->lun_lock);
6282
6283	return (0);
6284}
6285
6286int
6287ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6288		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6289{
6290	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6291	struct ctl_lun *lun;
6292	int set_ua;
6293	uint32_t initidx;
6294
6295	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6296	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6297	set_ua = 0;
6298
6299	user_cp = (struct scsi_caching_page *)page_ptr;
6300	current_cp = (struct scsi_caching_page *)
6301		(page_index->page_data + (page_index->page_len *
6302		CTL_PAGE_CURRENT));
6303	saved_cp = (struct scsi_caching_page *)
6304		(page_index->page_data + (page_index->page_len *
6305		CTL_PAGE_SAVED));
6306
6307	mtx_lock(&lun->lun_lock);
6308	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6309	    (user_cp->flags1 & (SCP_WCE | SCP_RCD)))
6310		set_ua = 1;
6311	current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6312	current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6313	saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6314	saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6315	if (set_ua != 0) {
6316		int i;
6317		/*
6318		 * Let other initiators know that the mode
6319		 * parameters for this LUN have changed.
6320		 */
6321		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6322			if (i == initidx)
6323				continue;
6324
6325			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6326		}
6327	}
6328	mtx_unlock(&lun->lun_lock);
6329
6330	return (0);
6331}
6332
6333int
6334ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6335		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6336{
6337	return (0);
6338}
6339
6340int
6341ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6342			   struct ctl_page_index *page_index, int pc)
6343{
6344	struct copan_power_subpage *page;
6345
6346	page = (struct copan_power_subpage *)page_index->page_data +
6347		(page_index->page_len * pc);
6348
6349	switch (pc) {
6350	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6351		/*
6352		 * We don't update the changable bits for this page.
6353		 */
6354		break;
6355	case SMS_PAGE_CTRL_CURRENT >> 6:
6356	case SMS_PAGE_CTRL_DEFAULT >> 6:
6357	case SMS_PAGE_CTRL_SAVED >> 6:
6358#ifdef NEEDTOPORT
6359		ctl_update_power_subpage(page);
6360#endif
6361		break;
6362	default:
6363#ifdef NEEDTOPORT
6364		EPRINT(0, "Invalid PC %d!!", pc);
6365#endif
6366		break;
6367	}
6368	return (0);
6369}
6370
6371
6372int
6373ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6374		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6375{
6376	struct copan_aps_subpage *user_sp;
6377	struct copan_aps_subpage *current_sp;
6378	union ctl_modepage_info *modepage_info;
6379	struct ctl_softc *softc;
6380	struct ctl_lun *lun;
6381	int retval;
6382
6383	retval = CTL_RETVAL_COMPLETE;
6384	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6385		     (page_index->page_len * CTL_PAGE_CURRENT));
6386	softc = control_softc;
6387	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6388
6389	user_sp = (struct copan_aps_subpage *)page_ptr;
6390
6391	modepage_info = (union ctl_modepage_info *)
6392		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6393
6394	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6395	modepage_info->header.subpage = page_index->subpage;
6396	modepage_info->aps.lock_active = user_sp->lock_active;
6397
6398	mtx_lock(&softc->ctl_lock);
6399
6400	/*
6401	 * If there is a request to lock the LUN and another LUN is locked
6402	 * this is an error. If the requested LUN is already locked ignore
6403	 * the request. If no LUN is locked attempt to lock it.
6404	 * if there is a request to unlock the LUN and the LUN is currently
6405	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6406	 * if another LUN is locked or no LUN is locked.
6407	 */
6408	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6409		if (softc->aps_locked_lun == lun->lun) {
6410			/*
6411			 * This LUN is already locked, so we're done.
6412			 */
6413			retval = CTL_RETVAL_COMPLETE;
6414		} else if (softc->aps_locked_lun == 0) {
6415			/*
6416			 * No one has the lock, pass the request to the
6417			 * backend.
6418			 */
6419			retval = lun->backend->config_write(
6420				(union ctl_io *)ctsio);
6421		} else {
6422			/*
6423			 * Someone else has the lock, throw out the request.
6424			 */
6425			ctl_set_already_locked(ctsio);
6426			free(ctsio->kern_data_ptr, M_CTL);
6427			ctl_done((union ctl_io *)ctsio);
6428
6429			/*
6430			 * Set the return value so that ctl_do_mode_select()
6431			 * won't try to complete the command.  We already
6432			 * completed it here.
6433			 */
6434			retval = CTL_RETVAL_ERROR;
6435		}
6436	} else if (softc->aps_locked_lun == lun->lun) {
6437		/*
6438		 * This LUN is locked, so pass the unlock request to the
6439		 * backend.
6440		 */
6441		retval = lun->backend->config_write((union ctl_io *)ctsio);
6442	}
6443	mtx_unlock(&softc->ctl_lock);
6444
6445	return (retval);
6446}
6447
6448int
6449ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6450				struct ctl_page_index *page_index,
6451				uint8_t *page_ptr)
6452{
6453	uint8_t *c;
6454	int i;
6455
6456	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6457	ctl_time_io_secs =
6458		(c[0] << 8) |
6459		(c[1] << 0) |
6460		0;
6461	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6462	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6463	printf("page data:");
6464	for (i=0; i<8; i++)
6465		printf(" %.2x",page_ptr[i]);
6466	printf("\n");
6467	return (0);
6468}
6469
6470int
6471ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6472			       struct ctl_page_index *page_index,
6473			       int pc)
6474{
6475	struct copan_debugconf_subpage *page;
6476
6477	page = (struct copan_debugconf_subpage *)page_index->page_data +
6478		(page_index->page_len * pc);
6479
6480	switch (pc) {
6481	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6482	case SMS_PAGE_CTRL_DEFAULT >> 6:
6483	case SMS_PAGE_CTRL_SAVED >> 6:
6484		/*
6485		 * We don't update the changable or default bits for this page.
6486		 */
6487		break;
6488	case SMS_PAGE_CTRL_CURRENT >> 6:
6489		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6490		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6491		break;
6492	default:
6493#ifdef NEEDTOPORT
6494		EPRINT(0, "Invalid PC %d!!", pc);
6495#endif /* NEEDTOPORT */
6496		break;
6497	}
6498	return (0);
6499}
6500
6501
6502static int
6503ctl_do_mode_select(union ctl_io *io)
6504{
6505	struct scsi_mode_page_header *page_header;
6506	struct ctl_page_index *page_index;
6507	struct ctl_scsiio *ctsio;
6508	int control_dev, page_len;
6509	int page_len_offset, page_len_size;
6510	union ctl_modepage_info *modepage_info;
6511	struct ctl_lun *lun;
6512	int *len_left, *len_used;
6513	int retval, i;
6514
6515	ctsio = &io->scsiio;
6516	page_index = NULL;
6517	page_len = 0;
6518	retval = CTL_RETVAL_COMPLETE;
6519
6520	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6521
6522	if (lun->be_lun->lun_type != T_DIRECT)
6523		control_dev = 1;
6524	else
6525		control_dev = 0;
6526
6527	modepage_info = (union ctl_modepage_info *)
6528		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6529	len_left = &modepage_info->header.len_left;
6530	len_used = &modepage_info->header.len_used;
6531
6532do_next_page:
6533
6534	page_header = (struct scsi_mode_page_header *)
6535		(ctsio->kern_data_ptr + *len_used);
6536
6537	if (*len_left == 0) {
6538		free(ctsio->kern_data_ptr, M_CTL);
6539		ctl_set_success(ctsio);
6540		ctl_done((union ctl_io *)ctsio);
6541		return (CTL_RETVAL_COMPLETE);
6542	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6543
6544		free(ctsio->kern_data_ptr, M_CTL);
6545		ctl_set_param_len_error(ctsio);
6546		ctl_done((union ctl_io *)ctsio);
6547		return (CTL_RETVAL_COMPLETE);
6548
6549	} else if ((page_header->page_code & SMPH_SPF)
6550		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6551
6552		free(ctsio->kern_data_ptr, M_CTL);
6553		ctl_set_param_len_error(ctsio);
6554		ctl_done((union ctl_io *)ctsio);
6555		return (CTL_RETVAL_COMPLETE);
6556	}
6557
6558
6559	/*
6560	 * XXX KDM should we do something with the block descriptor?
6561	 */
6562	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6563
6564		if ((control_dev != 0)
6565		 && (lun->mode_pages.index[i].page_flags &
6566		     CTL_PAGE_FLAG_DISK_ONLY))
6567			continue;
6568
6569		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6570		    (page_header->page_code & SMPH_PC_MASK))
6571			continue;
6572
6573		/*
6574		 * If neither page has a subpage code, then we've got a
6575		 * match.
6576		 */
6577		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6578		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6579			page_index = &lun->mode_pages.index[i];
6580			page_len = page_header->page_length;
6581			break;
6582		}
6583
6584		/*
6585		 * If both pages have subpages, then the subpage numbers
6586		 * have to match.
6587		 */
6588		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6589		  && (page_header->page_code & SMPH_SPF)) {
6590			struct scsi_mode_page_header_sp *sph;
6591
6592			sph = (struct scsi_mode_page_header_sp *)page_header;
6593
6594			if (lun->mode_pages.index[i].subpage ==
6595			    sph->subpage) {
6596				page_index = &lun->mode_pages.index[i];
6597				page_len = scsi_2btoul(sph->page_length);
6598				break;
6599			}
6600		}
6601	}
6602
6603	/*
6604	 * If we couldn't find the page, or if we don't have a mode select
6605	 * handler for it, send back an error to the user.
6606	 */
6607	if ((page_index == NULL)
6608	 || (page_index->select_handler == NULL)) {
6609		ctl_set_invalid_field(ctsio,
6610				      /*sks_valid*/ 1,
6611				      /*command*/ 0,
6612				      /*field*/ *len_used,
6613				      /*bit_valid*/ 0,
6614				      /*bit*/ 0);
6615		free(ctsio->kern_data_ptr, M_CTL);
6616		ctl_done((union ctl_io *)ctsio);
6617		return (CTL_RETVAL_COMPLETE);
6618	}
6619
6620	if (page_index->page_code & SMPH_SPF) {
6621		page_len_offset = 2;
6622		page_len_size = 2;
6623	} else {
6624		page_len_size = 1;
6625		page_len_offset = 1;
6626	}
6627
6628	/*
6629	 * If the length the initiator gives us isn't the one we specify in
6630	 * the mode page header, or if they didn't specify enough data in
6631	 * the CDB to avoid truncating this page, kick out the request.
6632	 */
6633	if ((page_len != (page_index->page_len - page_len_offset -
6634			  page_len_size))
6635	 || (*len_left < page_index->page_len)) {
6636
6637
6638		ctl_set_invalid_field(ctsio,
6639				      /*sks_valid*/ 1,
6640				      /*command*/ 0,
6641				      /*field*/ *len_used + page_len_offset,
6642				      /*bit_valid*/ 0,
6643				      /*bit*/ 0);
6644		free(ctsio->kern_data_ptr, M_CTL);
6645		ctl_done((union ctl_io *)ctsio);
6646		return (CTL_RETVAL_COMPLETE);
6647	}
6648
6649	/*
6650	 * Run through the mode page, checking to make sure that the bits
6651	 * the user changed are actually legal for him to change.
6652	 */
6653	for (i = 0; i < page_index->page_len; i++) {
6654		uint8_t *user_byte, *change_mask, *current_byte;
6655		int bad_bit;
6656		int j;
6657
6658		user_byte = (uint8_t *)page_header + i;
6659		change_mask = page_index->page_data +
6660			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6661		current_byte = page_index->page_data +
6662			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6663
6664		/*
6665		 * Check to see whether the user set any bits in this byte
6666		 * that he is not allowed to set.
6667		 */
6668		if ((*user_byte & ~(*change_mask)) ==
6669		    (*current_byte & ~(*change_mask)))
6670			continue;
6671
6672		/*
6673		 * Go through bit by bit to determine which one is illegal.
6674		 */
6675		bad_bit = 0;
6676		for (j = 7; j >= 0; j--) {
6677			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6678			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6679				bad_bit = i;
6680				break;
6681			}
6682		}
6683		ctl_set_invalid_field(ctsio,
6684				      /*sks_valid*/ 1,
6685				      /*command*/ 0,
6686				      /*field*/ *len_used + i,
6687				      /*bit_valid*/ 1,
6688				      /*bit*/ bad_bit);
6689		free(ctsio->kern_data_ptr, M_CTL);
6690		ctl_done((union ctl_io *)ctsio);
6691		return (CTL_RETVAL_COMPLETE);
6692	}
6693
6694	/*
6695	 * Decrement these before we call the page handler, since we may
6696	 * end up getting called back one way or another before the handler
6697	 * returns to this context.
6698	 */
6699	*len_left -= page_index->page_len;
6700	*len_used += page_index->page_len;
6701
6702	retval = page_index->select_handler(ctsio, page_index,
6703					    (uint8_t *)page_header);
6704
6705	/*
6706	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6707	 * wait until this queued command completes to finish processing
6708	 * the mode page.  If it returns anything other than
6709	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6710	 * already set the sense information, freed the data pointer, and
6711	 * completed the io for us.
6712	 */
6713	if (retval != CTL_RETVAL_COMPLETE)
6714		goto bailout_no_done;
6715
6716	/*
6717	 * If the initiator sent us more than one page, parse the next one.
6718	 */
6719	if (*len_left > 0)
6720		goto do_next_page;
6721
6722	ctl_set_success(ctsio);
6723	free(ctsio->kern_data_ptr, M_CTL);
6724	ctl_done((union ctl_io *)ctsio);
6725
6726bailout_no_done:
6727
6728	return (CTL_RETVAL_COMPLETE);
6729
6730}
6731
6732int
6733ctl_mode_select(struct ctl_scsiio *ctsio)
6734{
6735	int param_len, pf, sp;
6736	int header_size, bd_len;
6737	int len_left, len_used;
6738	struct ctl_page_index *page_index;
6739	struct ctl_lun *lun;
6740	int control_dev, page_len;
6741	union ctl_modepage_info *modepage_info;
6742	int retval;
6743
6744	pf = 0;
6745	sp = 0;
6746	page_len = 0;
6747	len_used = 0;
6748	len_left = 0;
6749	retval = 0;
6750	bd_len = 0;
6751	page_index = NULL;
6752
6753	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6754
6755	if (lun->be_lun->lun_type != T_DIRECT)
6756		control_dev = 1;
6757	else
6758		control_dev = 0;
6759
6760	switch (ctsio->cdb[0]) {
6761	case MODE_SELECT_6: {
6762		struct scsi_mode_select_6 *cdb;
6763
6764		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6765
6766		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6767		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6768
6769		param_len = cdb->length;
6770		header_size = sizeof(struct scsi_mode_header_6);
6771		break;
6772	}
6773	case MODE_SELECT_10: {
6774		struct scsi_mode_select_10 *cdb;
6775
6776		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6777
6778		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6779		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6780
6781		param_len = scsi_2btoul(cdb->length);
6782		header_size = sizeof(struct scsi_mode_header_10);
6783		break;
6784	}
6785	default:
6786		ctl_set_invalid_opcode(ctsio);
6787		ctl_done((union ctl_io *)ctsio);
6788		return (CTL_RETVAL_COMPLETE);
6789		break; /* NOTREACHED */
6790	}
6791
6792	/*
6793	 * From SPC-3:
6794	 * "A parameter list length of zero indicates that the Data-Out Buffer
6795	 * shall be empty. This condition shall not be considered as an error."
6796	 */
6797	if (param_len == 0) {
6798		ctl_set_success(ctsio);
6799		ctl_done((union ctl_io *)ctsio);
6800		return (CTL_RETVAL_COMPLETE);
6801	}
6802
6803	/*
6804	 * Since we'll hit this the first time through, prior to
6805	 * allocation, we don't need to free a data buffer here.
6806	 */
6807	if (param_len < header_size) {
6808		ctl_set_param_len_error(ctsio);
6809		ctl_done((union ctl_io *)ctsio);
6810		return (CTL_RETVAL_COMPLETE);
6811	}
6812
6813	/*
6814	 * Allocate the data buffer and grab the user's data.  In theory,
6815	 * we shouldn't have to sanity check the parameter list length here
6816	 * because the maximum size is 64K.  We should be able to malloc
6817	 * that much without too many problems.
6818	 */
6819	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6820		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6821		ctsio->kern_data_len = param_len;
6822		ctsio->kern_total_len = param_len;
6823		ctsio->kern_data_resid = 0;
6824		ctsio->kern_rel_offset = 0;
6825		ctsio->kern_sg_entries = 0;
6826		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6827		ctsio->be_move_done = ctl_config_move_done;
6828		ctl_datamove((union ctl_io *)ctsio);
6829
6830		return (CTL_RETVAL_COMPLETE);
6831	}
6832
6833	switch (ctsio->cdb[0]) {
6834	case MODE_SELECT_6: {
6835		struct scsi_mode_header_6 *mh6;
6836
6837		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6838		bd_len = mh6->blk_desc_len;
6839		break;
6840	}
6841	case MODE_SELECT_10: {
6842		struct scsi_mode_header_10 *mh10;
6843
6844		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6845		bd_len = scsi_2btoul(mh10->blk_desc_len);
6846		break;
6847	}
6848	default:
6849		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6850		break;
6851	}
6852
6853	if (param_len < (header_size + bd_len)) {
6854		free(ctsio->kern_data_ptr, M_CTL);
6855		ctl_set_param_len_error(ctsio);
6856		ctl_done((union ctl_io *)ctsio);
6857		return (CTL_RETVAL_COMPLETE);
6858	}
6859
6860	/*
6861	 * Set the IO_CONT flag, so that if this I/O gets passed to
6862	 * ctl_config_write_done(), it'll get passed back to
6863	 * ctl_do_mode_select() for further processing, or completion if
6864	 * we're all done.
6865	 */
6866	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6867	ctsio->io_cont = ctl_do_mode_select;
6868
6869	modepage_info = (union ctl_modepage_info *)
6870		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6871
6872	memset(modepage_info, 0, sizeof(*modepage_info));
6873
6874	len_left = param_len - header_size - bd_len;
6875	len_used = header_size + bd_len;
6876
6877	modepage_info->header.len_left = len_left;
6878	modepage_info->header.len_used = len_used;
6879
6880	return (ctl_do_mode_select((union ctl_io *)ctsio));
6881}
6882
6883int
6884ctl_mode_sense(struct ctl_scsiio *ctsio)
6885{
6886	struct ctl_lun *lun;
6887	int pc, page_code, dbd, llba, subpage;
6888	int alloc_len, page_len, header_len, total_len;
6889	struct scsi_mode_block_descr *block_desc;
6890	struct ctl_page_index *page_index;
6891	int control_dev;
6892
6893	dbd = 0;
6894	llba = 0;
6895	block_desc = NULL;
6896	page_index = NULL;
6897
6898	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6899
6900	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6901
6902	if (lun->be_lun->lun_type != T_DIRECT)
6903		control_dev = 1;
6904	else
6905		control_dev = 0;
6906
6907	if (lun->flags & CTL_LUN_PR_RESERVED) {
6908		uint32_t residx;
6909
6910		/*
6911		 * XXX KDM need a lock here.
6912		 */
6913		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6914		if ((lun->res_type == SPR_TYPE_EX_AC
6915		  && residx != lun->pr_res_idx)
6916		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6917		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6918		  && !lun->per_res[residx].registered)) {
6919			ctl_set_reservation_conflict(ctsio);
6920			ctl_done((union ctl_io *)ctsio);
6921			return (CTL_RETVAL_COMPLETE);
6922		}
6923	}
6924
6925	switch (ctsio->cdb[0]) {
6926	case MODE_SENSE_6: {
6927		struct scsi_mode_sense_6 *cdb;
6928
6929		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6930
6931		header_len = sizeof(struct scsi_mode_hdr_6);
6932		if (cdb->byte2 & SMS_DBD)
6933			dbd = 1;
6934		else
6935			header_len += sizeof(struct scsi_mode_block_descr);
6936
6937		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6938		page_code = cdb->page & SMS_PAGE_CODE;
6939		subpage = cdb->subpage;
6940		alloc_len = cdb->length;
6941		break;
6942	}
6943	case MODE_SENSE_10: {
6944		struct scsi_mode_sense_10 *cdb;
6945
6946		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6947
6948		header_len = sizeof(struct scsi_mode_hdr_10);
6949
6950		if (cdb->byte2 & SMS_DBD)
6951			dbd = 1;
6952		else
6953			header_len += sizeof(struct scsi_mode_block_descr);
6954		if (cdb->byte2 & SMS10_LLBAA)
6955			llba = 1;
6956		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6957		page_code = cdb->page & SMS_PAGE_CODE;
6958		subpage = cdb->subpage;
6959		alloc_len = scsi_2btoul(cdb->length);
6960		break;
6961	}
6962	default:
6963		ctl_set_invalid_opcode(ctsio);
6964		ctl_done((union ctl_io *)ctsio);
6965		return (CTL_RETVAL_COMPLETE);
6966		break; /* NOTREACHED */
6967	}
6968
6969	/*
6970	 * We have to make a first pass through to calculate the size of
6971	 * the pages that match the user's query.  Then we allocate enough
6972	 * memory to hold it, and actually copy the data into the buffer.
6973	 */
6974	switch (page_code) {
6975	case SMS_ALL_PAGES_PAGE: {
6976		int i;
6977
6978		page_len = 0;
6979
6980		/*
6981		 * At the moment, values other than 0 and 0xff here are
6982		 * reserved according to SPC-3.
6983		 */
6984		if ((subpage != SMS_SUBPAGE_PAGE_0)
6985		 && (subpage != SMS_SUBPAGE_ALL)) {
6986			ctl_set_invalid_field(ctsio,
6987					      /*sks_valid*/ 1,
6988					      /*command*/ 1,
6989					      /*field*/ 3,
6990					      /*bit_valid*/ 0,
6991					      /*bit*/ 0);
6992			ctl_done((union ctl_io *)ctsio);
6993			return (CTL_RETVAL_COMPLETE);
6994		}
6995
6996		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6997			if ((control_dev != 0)
6998			 && (lun->mode_pages.index[i].page_flags &
6999			     CTL_PAGE_FLAG_DISK_ONLY))
7000				continue;
7001
7002			/*
7003			 * We don't use this subpage if the user didn't
7004			 * request all subpages.
7005			 */
7006			if ((lun->mode_pages.index[i].subpage != 0)
7007			 && (subpage == SMS_SUBPAGE_PAGE_0))
7008				continue;
7009
7010#if 0
7011			printf("found page %#x len %d\n",
7012			       lun->mode_pages.index[i].page_code &
7013			       SMPH_PC_MASK,
7014			       lun->mode_pages.index[i].page_len);
7015#endif
7016			page_len += lun->mode_pages.index[i].page_len;
7017		}
7018		break;
7019	}
7020	default: {
7021		int i;
7022
7023		page_len = 0;
7024
7025		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7026			/* Look for the right page code */
7027			if ((lun->mode_pages.index[i].page_code &
7028			     SMPH_PC_MASK) != page_code)
7029				continue;
7030
7031			/* Look for the right subpage or the subpage wildcard*/
7032			if ((lun->mode_pages.index[i].subpage != subpage)
7033			 && (subpage != SMS_SUBPAGE_ALL))
7034				continue;
7035
7036			/* Make sure the page is supported for this dev type */
7037			if ((control_dev != 0)
7038			 && (lun->mode_pages.index[i].page_flags &
7039			     CTL_PAGE_FLAG_DISK_ONLY))
7040				continue;
7041
7042#if 0
7043			printf("found page %#x len %d\n",
7044			       lun->mode_pages.index[i].page_code &
7045			       SMPH_PC_MASK,
7046			       lun->mode_pages.index[i].page_len);
7047#endif
7048
7049			page_len += lun->mode_pages.index[i].page_len;
7050		}
7051
7052		if (page_len == 0) {
7053			ctl_set_invalid_field(ctsio,
7054					      /*sks_valid*/ 1,
7055					      /*command*/ 1,
7056					      /*field*/ 2,
7057					      /*bit_valid*/ 1,
7058					      /*bit*/ 5);
7059			ctl_done((union ctl_io *)ctsio);
7060			return (CTL_RETVAL_COMPLETE);
7061		}
7062		break;
7063	}
7064	}
7065
7066	total_len = header_len + page_len;
7067#if 0
7068	printf("header_len = %d, page_len = %d, total_len = %d\n",
7069	       header_len, page_len, total_len);
7070#endif
7071
7072	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7073	ctsio->kern_sg_entries = 0;
7074	ctsio->kern_data_resid = 0;
7075	ctsio->kern_rel_offset = 0;
7076	if (total_len < alloc_len) {
7077		ctsio->residual = alloc_len - total_len;
7078		ctsio->kern_data_len = total_len;
7079		ctsio->kern_total_len = total_len;
7080	} else {
7081		ctsio->residual = 0;
7082		ctsio->kern_data_len = alloc_len;
7083		ctsio->kern_total_len = alloc_len;
7084	}
7085
7086	switch (ctsio->cdb[0]) {
7087	case MODE_SENSE_6: {
7088		struct scsi_mode_hdr_6 *header;
7089
7090		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7091
7092		header->datalen = ctl_min(total_len - 1, 254);
7093		if (control_dev == 0)
7094			header->dev_specific = 0x10; /* DPOFUA */
7095		if (dbd)
7096			header->block_descr_len = 0;
7097		else
7098			header->block_descr_len =
7099				sizeof(struct scsi_mode_block_descr);
7100		block_desc = (struct scsi_mode_block_descr *)&header[1];
7101		break;
7102	}
7103	case MODE_SENSE_10: {
7104		struct scsi_mode_hdr_10 *header;
7105		int datalen;
7106
7107		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7108
7109		datalen = ctl_min(total_len - 2, 65533);
7110		scsi_ulto2b(datalen, header->datalen);
7111		if (control_dev == 0)
7112			header->dev_specific = 0x10; /* DPOFUA */
7113		if (dbd)
7114			scsi_ulto2b(0, header->block_descr_len);
7115		else
7116			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7117				    header->block_descr_len);
7118		block_desc = (struct scsi_mode_block_descr *)&header[1];
7119		break;
7120	}
7121	default:
7122		panic("invalid CDB type %#x", ctsio->cdb[0]);
7123		break; /* NOTREACHED */
7124	}
7125
7126	/*
7127	 * If we've got a disk, use its blocksize in the block
7128	 * descriptor.  Otherwise, just set it to 0.
7129	 */
7130	if (dbd == 0) {
7131		if (control_dev != 0)
7132			scsi_ulto3b(lun->be_lun->blocksize,
7133				    block_desc->block_len);
7134		else
7135			scsi_ulto3b(0, block_desc->block_len);
7136	}
7137
7138	switch (page_code) {
7139	case SMS_ALL_PAGES_PAGE: {
7140		int i, data_used;
7141
7142		data_used = header_len;
7143		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7144			struct ctl_page_index *page_index;
7145
7146			page_index = &lun->mode_pages.index[i];
7147
7148			if ((control_dev != 0)
7149			 && (page_index->page_flags &
7150			    CTL_PAGE_FLAG_DISK_ONLY))
7151				continue;
7152
7153			/*
7154			 * We don't use this subpage if the user didn't
7155			 * request all subpages.  We already checked (above)
7156			 * to make sure the user only specified a subpage
7157			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7158			 */
7159			if ((page_index->subpage != 0)
7160			 && (subpage == SMS_SUBPAGE_PAGE_0))
7161				continue;
7162
7163			/*
7164			 * Call the handler, if it exists, to update the
7165			 * page to the latest values.
7166			 */
7167			if (page_index->sense_handler != NULL)
7168				page_index->sense_handler(ctsio, page_index,pc);
7169
7170			memcpy(ctsio->kern_data_ptr + data_used,
7171			       page_index->page_data +
7172			       (page_index->page_len * pc),
7173			       page_index->page_len);
7174			data_used += page_index->page_len;
7175		}
7176		break;
7177	}
7178	default: {
7179		int i, data_used;
7180
7181		data_used = header_len;
7182
7183		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7184			struct ctl_page_index *page_index;
7185
7186			page_index = &lun->mode_pages.index[i];
7187
7188			/* Look for the right page code */
7189			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7190				continue;
7191
7192			/* Look for the right subpage or the subpage wildcard*/
7193			if ((page_index->subpage != subpage)
7194			 && (subpage != SMS_SUBPAGE_ALL))
7195				continue;
7196
7197			/* Make sure the page is supported for this dev type */
7198			if ((control_dev != 0)
7199			 && (page_index->page_flags &
7200			     CTL_PAGE_FLAG_DISK_ONLY))
7201				continue;
7202
7203			/*
7204			 * Call the handler, if it exists, to update the
7205			 * page to the latest values.
7206			 */
7207			if (page_index->sense_handler != NULL)
7208				page_index->sense_handler(ctsio, page_index,pc);
7209
7210			memcpy(ctsio->kern_data_ptr + data_used,
7211			       page_index->page_data +
7212			       (page_index->page_len * pc),
7213			       page_index->page_len);
7214			data_used += page_index->page_len;
7215		}
7216		break;
7217	}
7218	}
7219
7220	ctsio->scsi_status = SCSI_STATUS_OK;
7221
7222	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7223	ctsio->be_move_done = ctl_config_move_done;
7224	ctl_datamove((union ctl_io *)ctsio);
7225
7226	return (CTL_RETVAL_COMPLETE);
7227}
7228
7229int
7230ctl_read_capacity(struct ctl_scsiio *ctsio)
7231{
7232	struct scsi_read_capacity *cdb;
7233	struct scsi_read_capacity_data *data;
7234	struct ctl_lun *lun;
7235	uint32_t lba;
7236
7237	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7238
7239	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7240
7241	lba = scsi_4btoul(cdb->addr);
7242	if (((cdb->pmi & SRC_PMI) == 0)
7243	 && (lba != 0)) {
7244		ctl_set_invalid_field(/*ctsio*/ ctsio,
7245				      /*sks_valid*/ 1,
7246				      /*command*/ 1,
7247				      /*field*/ 2,
7248				      /*bit_valid*/ 0,
7249				      /*bit*/ 0);
7250		ctl_done((union ctl_io *)ctsio);
7251		return (CTL_RETVAL_COMPLETE);
7252	}
7253
7254	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7255
7256	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7257	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7258	ctsio->residual = 0;
7259	ctsio->kern_data_len = sizeof(*data);
7260	ctsio->kern_total_len = sizeof(*data);
7261	ctsio->kern_data_resid = 0;
7262	ctsio->kern_rel_offset = 0;
7263	ctsio->kern_sg_entries = 0;
7264
7265	/*
7266	 * If the maximum LBA is greater than 0xfffffffe, the user must
7267	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7268	 * serivce action set.
7269	 */
7270	if (lun->be_lun->maxlba > 0xfffffffe)
7271		scsi_ulto4b(0xffffffff, data->addr);
7272	else
7273		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7274
7275	/*
7276	 * XXX KDM this may not be 512 bytes...
7277	 */
7278	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7279
7280	ctsio->scsi_status = SCSI_STATUS_OK;
7281
7282	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7283	ctsio->be_move_done = ctl_config_move_done;
7284	ctl_datamove((union ctl_io *)ctsio);
7285
7286	return (CTL_RETVAL_COMPLETE);
7287}
7288
7289int
7290ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7291{
7292	struct scsi_read_capacity_16 *cdb;
7293	struct scsi_read_capacity_data_long *data;
7294	struct ctl_lun *lun;
7295	uint64_t lba;
7296	uint32_t alloc_len;
7297
7298	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7299
7300	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7301
7302	alloc_len = scsi_4btoul(cdb->alloc_len);
7303	lba = scsi_8btou64(cdb->addr);
7304
7305	if ((cdb->reladr & SRC16_PMI)
7306	 && (lba != 0)) {
7307		ctl_set_invalid_field(/*ctsio*/ ctsio,
7308				      /*sks_valid*/ 1,
7309				      /*command*/ 1,
7310				      /*field*/ 2,
7311				      /*bit_valid*/ 0,
7312				      /*bit*/ 0);
7313		ctl_done((union ctl_io *)ctsio);
7314		return (CTL_RETVAL_COMPLETE);
7315	}
7316
7317	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7318
7319	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7320	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7321
7322	if (sizeof(*data) < alloc_len) {
7323		ctsio->residual = alloc_len - sizeof(*data);
7324		ctsio->kern_data_len = sizeof(*data);
7325		ctsio->kern_total_len = sizeof(*data);
7326	} else {
7327		ctsio->residual = 0;
7328		ctsio->kern_data_len = alloc_len;
7329		ctsio->kern_total_len = alloc_len;
7330	}
7331	ctsio->kern_data_resid = 0;
7332	ctsio->kern_rel_offset = 0;
7333	ctsio->kern_sg_entries = 0;
7334
7335	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7336	/* XXX KDM this may not be 512 bytes... */
7337	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7338	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7339	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7340	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7341		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7342
7343	ctsio->scsi_status = SCSI_STATUS_OK;
7344
7345	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7346	ctsio->be_move_done = ctl_config_move_done;
7347	ctl_datamove((union ctl_io *)ctsio);
7348
7349	return (CTL_RETVAL_COMPLETE);
7350}
7351
7352int
7353ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7354{
7355	struct scsi_maintenance_in *cdb;
7356	int retval;
7357	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7358	int num_target_port_groups, num_target_ports, single;
7359	struct ctl_lun *lun;
7360	struct ctl_softc *softc;
7361	struct ctl_port *port;
7362	struct scsi_target_group_data *rtg_ptr;
7363	struct scsi_target_group_data_extended *rtg_ext_ptr;
7364	struct scsi_target_port_group_descriptor *tpg_desc;
7365
7366	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7367
7368	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7369	softc = control_softc;
7370	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7371
7372	retval = CTL_RETVAL_COMPLETE;
7373
7374	switch (cdb->byte2 & STG_PDF_MASK) {
7375	case STG_PDF_LENGTH:
7376		ext = 0;
7377		break;
7378	case STG_PDF_EXTENDED:
7379		ext = 1;
7380		break;
7381	default:
7382		ctl_set_invalid_field(/*ctsio*/ ctsio,
7383				      /*sks_valid*/ 1,
7384				      /*command*/ 1,
7385				      /*field*/ 2,
7386				      /*bit_valid*/ 1,
7387				      /*bit*/ 5);
7388		ctl_done((union ctl_io *)ctsio);
7389		return(retval);
7390	}
7391
7392	single = ctl_is_single;
7393	if (single)
7394		num_target_port_groups = 1;
7395	else
7396		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7397	num_target_ports = 0;
7398	mtx_lock(&softc->ctl_lock);
7399	STAILQ_FOREACH(port, &softc->port_list, links) {
7400		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7401			continue;
7402		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7403			continue;
7404		num_target_ports++;
7405	}
7406	mtx_unlock(&softc->ctl_lock);
7407
7408	if (ext)
7409		total_len = sizeof(struct scsi_target_group_data_extended);
7410	else
7411		total_len = sizeof(struct scsi_target_group_data);
7412	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7413		num_target_port_groups +
7414	    sizeof(struct scsi_target_port_descriptor) *
7415		num_target_ports * num_target_port_groups;
7416
7417	alloc_len = scsi_4btoul(cdb->length);
7418
7419	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7420
7421	ctsio->kern_sg_entries = 0;
7422
7423	if (total_len < alloc_len) {
7424		ctsio->residual = alloc_len - total_len;
7425		ctsio->kern_data_len = total_len;
7426		ctsio->kern_total_len = total_len;
7427	} else {
7428		ctsio->residual = 0;
7429		ctsio->kern_data_len = alloc_len;
7430		ctsio->kern_total_len = alloc_len;
7431	}
7432	ctsio->kern_data_resid = 0;
7433	ctsio->kern_rel_offset = 0;
7434
7435	if (ext) {
7436		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7437		    ctsio->kern_data_ptr;
7438		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7439		rtg_ext_ptr->format_type = 0x10;
7440		rtg_ext_ptr->implicit_transition_time = 0;
7441		tpg_desc = &rtg_ext_ptr->groups[0];
7442	} else {
7443		rtg_ptr = (struct scsi_target_group_data *)
7444		    ctsio->kern_data_ptr;
7445		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7446		tpg_desc = &rtg_ptr->groups[0];
7447	}
7448
7449	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7450	mtx_lock(&softc->ctl_lock);
7451	for (g = 0; g < num_target_port_groups; g++) {
7452		if (g == pg)
7453			tpg_desc->pref_state = TPG_PRIMARY |
7454			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7455		else
7456			tpg_desc->pref_state =
7457			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7458		tpg_desc->support = TPG_AO_SUP;
7459		if (!single)
7460			tpg_desc->support |= TPG_AN_SUP;
7461		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7462		tpg_desc->status = TPG_IMPLICIT;
7463		pc = 0;
7464		STAILQ_FOREACH(port, &softc->port_list, links) {
7465			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7466				continue;
7467			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7468			    CTL_MAX_LUNS)
7469				continue;
7470			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7471			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7472			    relative_target_port_identifier);
7473			pc++;
7474		}
7475		tpg_desc->target_port_count = pc;
7476		tpg_desc = (struct scsi_target_port_group_descriptor *)
7477		    &tpg_desc->descriptors[pc];
7478	}
7479	mtx_unlock(&softc->ctl_lock);
7480
7481	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7482	ctsio->be_move_done = ctl_config_move_done;
7483
7484	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7485			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7486			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7487			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7488			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7489
7490	ctl_datamove((union ctl_io *)ctsio);
7491	return(retval);
7492}
7493
7494int
7495ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7496{
7497	struct ctl_lun *lun;
7498	struct scsi_report_supported_opcodes *cdb;
7499	const struct ctl_cmd_entry *entry, *sentry;
7500	struct scsi_report_supported_opcodes_all *all;
7501	struct scsi_report_supported_opcodes_descr *descr;
7502	struct scsi_report_supported_opcodes_one *one;
7503	int retval;
7504	int alloc_len, total_len;
7505	int opcode, service_action, i, j, num;
7506
7507	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7508
7509	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7510	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7511
7512	retval = CTL_RETVAL_COMPLETE;
7513
7514	opcode = cdb->requested_opcode;
7515	service_action = scsi_2btoul(cdb->requested_service_action);
7516	switch (cdb->options & RSO_OPTIONS_MASK) {
7517	case RSO_OPTIONS_ALL:
7518		num = 0;
7519		for (i = 0; i < 256; i++) {
7520			entry = &ctl_cmd_table[i];
7521			if (entry->flags & CTL_CMD_FLAG_SA5) {
7522				for (j = 0; j < 32; j++) {
7523					sentry = &((const struct ctl_cmd_entry *)
7524					    entry->execute)[j];
7525					if (ctl_cmd_applicable(
7526					    lun->be_lun->lun_type, sentry))
7527						num++;
7528				}
7529			} else {
7530				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7531				    entry))
7532					num++;
7533			}
7534		}
7535		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7536		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7537		break;
7538	case RSO_OPTIONS_OC:
7539		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7540			ctl_set_invalid_field(/*ctsio*/ ctsio,
7541					      /*sks_valid*/ 1,
7542					      /*command*/ 1,
7543					      /*field*/ 2,
7544					      /*bit_valid*/ 1,
7545					      /*bit*/ 2);
7546			ctl_done((union ctl_io *)ctsio);
7547			return (CTL_RETVAL_COMPLETE);
7548		}
7549		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7550		break;
7551	case RSO_OPTIONS_OC_SA:
7552		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7553		    service_action >= 32) {
7554			ctl_set_invalid_field(/*ctsio*/ ctsio,
7555					      /*sks_valid*/ 1,
7556					      /*command*/ 1,
7557					      /*field*/ 2,
7558					      /*bit_valid*/ 1,
7559					      /*bit*/ 2);
7560			ctl_done((union ctl_io *)ctsio);
7561			return (CTL_RETVAL_COMPLETE);
7562		}
7563		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7564		break;
7565	default:
7566		ctl_set_invalid_field(/*ctsio*/ ctsio,
7567				      /*sks_valid*/ 1,
7568				      /*command*/ 1,
7569				      /*field*/ 2,
7570				      /*bit_valid*/ 1,
7571				      /*bit*/ 2);
7572		ctl_done((union ctl_io *)ctsio);
7573		return (CTL_RETVAL_COMPLETE);
7574	}
7575
7576	alloc_len = scsi_4btoul(cdb->length);
7577
7578	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7579
7580	ctsio->kern_sg_entries = 0;
7581
7582	if (total_len < alloc_len) {
7583		ctsio->residual = alloc_len - total_len;
7584		ctsio->kern_data_len = total_len;
7585		ctsio->kern_total_len = total_len;
7586	} else {
7587		ctsio->residual = 0;
7588		ctsio->kern_data_len = alloc_len;
7589		ctsio->kern_total_len = alloc_len;
7590	}
7591	ctsio->kern_data_resid = 0;
7592	ctsio->kern_rel_offset = 0;
7593
7594	switch (cdb->options & RSO_OPTIONS_MASK) {
7595	case RSO_OPTIONS_ALL:
7596		all = (struct scsi_report_supported_opcodes_all *)
7597		    ctsio->kern_data_ptr;
7598		num = 0;
7599		for (i = 0; i < 256; i++) {
7600			entry = &ctl_cmd_table[i];
7601			if (entry->flags & CTL_CMD_FLAG_SA5) {
7602				for (j = 0; j < 32; j++) {
7603					sentry = &((const struct ctl_cmd_entry *)
7604					    entry->execute)[j];
7605					if (!ctl_cmd_applicable(
7606					    lun->be_lun->lun_type, sentry))
7607						continue;
7608					descr = &all->descr[num++];
7609					descr->opcode = i;
7610					scsi_ulto2b(j, descr->service_action);
7611					descr->flags = RSO_SERVACTV;
7612					scsi_ulto2b(sentry->length,
7613					    descr->cdb_length);
7614				}
7615			} else {
7616				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7617				    entry))
7618					continue;
7619				descr = &all->descr[num++];
7620				descr->opcode = i;
7621				scsi_ulto2b(0, descr->service_action);
7622				descr->flags = 0;
7623				scsi_ulto2b(entry->length, descr->cdb_length);
7624			}
7625		}
7626		scsi_ulto4b(
7627		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7628		    all->length);
7629		break;
7630	case RSO_OPTIONS_OC:
7631		one = (struct scsi_report_supported_opcodes_one *)
7632		    ctsio->kern_data_ptr;
7633		entry = &ctl_cmd_table[opcode];
7634		goto fill_one;
7635	case RSO_OPTIONS_OC_SA:
7636		one = (struct scsi_report_supported_opcodes_one *)
7637		    ctsio->kern_data_ptr;
7638		entry = &ctl_cmd_table[opcode];
7639		entry = &((const struct ctl_cmd_entry *)
7640		    entry->execute)[service_action];
7641fill_one:
7642		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7643			one->support = 3;
7644			scsi_ulto2b(entry->length, one->cdb_length);
7645			one->cdb_usage[0] = opcode;
7646			memcpy(&one->cdb_usage[1], entry->usage,
7647			    entry->length - 1);
7648		} else
7649			one->support = 1;
7650		break;
7651	}
7652
7653	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7654	ctsio->be_move_done = ctl_config_move_done;
7655
7656	ctl_datamove((union ctl_io *)ctsio);
7657	return(retval);
7658}
7659
7660int
7661ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7662{
7663	struct ctl_lun *lun;
7664	struct scsi_report_supported_tmf *cdb;
7665	struct scsi_report_supported_tmf_data *data;
7666	int retval;
7667	int alloc_len, total_len;
7668
7669	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7670
7671	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7672	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7673
7674	retval = CTL_RETVAL_COMPLETE;
7675
7676	total_len = sizeof(struct scsi_report_supported_tmf_data);
7677	alloc_len = scsi_4btoul(cdb->length);
7678
7679	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7680
7681	ctsio->kern_sg_entries = 0;
7682
7683	if (total_len < alloc_len) {
7684		ctsio->residual = alloc_len - total_len;
7685		ctsio->kern_data_len = total_len;
7686		ctsio->kern_total_len = total_len;
7687	} else {
7688		ctsio->residual = 0;
7689		ctsio->kern_data_len = alloc_len;
7690		ctsio->kern_total_len = alloc_len;
7691	}
7692	ctsio->kern_data_resid = 0;
7693	ctsio->kern_rel_offset = 0;
7694
7695	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7696	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7697	data->byte2 |= RST_ITNRS;
7698
7699	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7700	ctsio->be_move_done = ctl_config_move_done;
7701
7702	ctl_datamove((union ctl_io *)ctsio);
7703	return (retval);
7704}
7705
7706int
7707ctl_report_timestamp(struct ctl_scsiio *ctsio)
7708{
7709	struct ctl_lun *lun;
7710	struct scsi_report_timestamp *cdb;
7711	struct scsi_report_timestamp_data *data;
7712	struct timeval tv;
7713	int64_t timestamp;
7714	int retval;
7715	int alloc_len, total_len;
7716
7717	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7718
7719	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7720	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7721
7722	retval = CTL_RETVAL_COMPLETE;
7723
7724	total_len = sizeof(struct scsi_report_timestamp_data);
7725	alloc_len = scsi_4btoul(cdb->length);
7726
7727	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7728
7729	ctsio->kern_sg_entries = 0;
7730
7731	if (total_len < alloc_len) {
7732		ctsio->residual = alloc_len - total_len;
7733		ctsio->kern_data_len = total_len;
7734		ctsio->kern_total_len = total_len;
7735	} else {
7736		ctsio->residual = 0;
7737		ctsio->kern_data_len = alloc_len;
7738		ctsio->kern_total_len = alloc_len;
7739	}
7740	ctsio->kern_data_resid = 0;
7741	ctsio->kern_rel_offset = 0;
7742
7743	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7744	scsi_ulto2b(sizeof(*data) - 2, data->length);
7745	data->origin = RTS_ORIG_OUTSIDE;
7746	getmicrotime(&tv);
7747	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7748	scsi_ulto4b(timestamp >> 16, data->timestamp);
7749	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7750
7751	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7752	ctsio->be_move_done = ctl_config_move_done;
7753
7754	ctl_datamove((union ctl_io *)ctsio);
7755	return (retval);
7756}
7757
7758int
7759ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7760{
7761	struct scsi_per_res_in *cdb;
7762	int alloc_len, total_len = 0;
7763	/* struct scsi_per_res_in_rsrv in_data; */
7764	struct ctl_lun *lun;
7765	struct ctl_softc *softc;
7766
7767	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7768
7769	softc = control_softc;
7770
7771	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7772
7773	alloc_len = scsi_2btoul(cdb->length);
7774
7775	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7776
7777retry:
7778	mtx_lock(&lun->lun_lock);
7779	switch (cdb->action) {
7780	case SPRI_RK: /* read keys */
7781		total_len = sizeof(struct scsi_per_res_in_keys) +
7782			lun->pr_key_count *
7783			sizeof(struct scsi_per_res_key);
7784		break;
7785	case SPRI_RR: /* read reservation */
7786		if (lun->flags & CTL_LUN_PR_RESERVED)
7787			total_len = sizeof(struct scsi_per_res_in_rsrv);
7788		else
7789			total_len = sizeof(struct scsi_per_res_in_header);
7790		break;
7791	case SPRI_RC: /* report capabilities */
7792		total_len = sizeof(struct scsi_per_res_cap);
7793		break;
7794	case SPRI_RS: /* read full status */
7795		total_len = sizeof(struct scsi_per_res_in_header) +
7796		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7797		    lun->pr_key_count;
7798		break;
7799	default:
7800		panic("Invalid PR type %x", cdb->action);
7801	}
7802	mtx_unlock(&lun->lun_lock);
7803
7804	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7805
7806	if (total_len < alloc_len) {
7807		ctsio->residual = alloc_len - total_len;
7808		ctsio->kern_data_len = total_len;
7809		ctsio->kern_total_len = total_len;
7810	} else {
7811		ctsio->residual = 0;
7812		ctsio->kern_data_len = alloc_len;
7813		ctsio->kern_total_len = alloc_len;
7814	}
7815
7816	ctsio->kern_data_resid = 0;
7817	ctsio->kern_rel_offset = 0;
7818	ctsio->kern_sg_entries = 0;
7819
7820	mtx_lock(&lun->lun_lock);
7821	switch (cdb->action) {
7822	case SPRI_RK: { // read keys
7823        struct scsi_per_res_in_keys *res_keys;
7824		int i, key_count;
7825
7826		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7827
7828		/*
7829		 * We had to drop the lock to allocate our buffer, which
7830		 * leaves time for someone to come in with another
7831		 * persistent reservation.  (That is unlikely, though,
7832		 * since this should be the only persistent reservation
7833		 * command active right now.)
7834		 */
7835		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7836		    (lun->pr_key_count *
7837		     sizeof(struct scsi_per_res_key)))){
7838			mtx_unlock(&lun->lun_lock);
7839			free(ctsio->kern_data_ptr, M_CTL);
7840			printf("%s: reservation length changed, retrying\n",
7841			       __func__);
7842			goto retry;
7843		}
7844
7845		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7846
7847		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7848			     lun->pr_key_count, res_keys->header.length);
7849
7850		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7851			if (!lun->per_res[i].registered)
7852				continue;
7853
7854			/*
7855			 * We used lun->pr_key_count to calculate the
7856			 * size to allocate.  If it turns out the number of
7857			 * initiators with the registered flag set is
7858			 * larger than that (i.e. they haven't been kept in
7859			 * sync), we've got a problem.
7860			 */
7861			if (key_count >= lun->pr_key_count) {
7862#ifdef NEEDTOPORT
7863				csevent_log(CSC_CTL | CSC_SHELF_SW |
7864					    CTL_PR_ERROR,
7865					    csevent_LogType_Fault,
7866					    csevent_AlertLevel_Yellow,
7867					    csevent_FRU_ShelfController,
7868					    csevent_FRU_Firmware,
7869				        csevent_FRU_Unknown,
7870					    "registered keys %d >= key "
7871					    "count %d", key_count,
7872					    lun->pr_key_count);
7873#endif
7874				key_count++;
7875				continue;
7876			}
7877			memcpy(res_keys->keys[key_count].key,
7878			       lun->per_res[i].res_key.key,
7879			       ctl_min(sizeof(res_keys->keys[key_count].key),
7880			       sizeof(lun->per_res[i].res_key)));
7881			key_count++;
7882		}
7883		break;
7884	}
7885	case SPRI_RR: { // read reservation
7886		struct scsi_per_res_in_rsrv *res;
7887		int tmp_len, header_only;
7888
7889		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7890
7891		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7892
7893		if (lun->flags & CTL_LUN_PR_RESERVED)
7894		{
7895			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7896			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7897				    res->header.length);
7898			header_only = 0;
7899		} else {
7900			tmp_len = sizeof(struct scsi_per_res_in_header);
7901			scsi_ulto4b(0, res->header.length);
7902			header_only = 1;
7903		}
7904
7905		/*
7906		 * We had to drop the lock to allocate our buffer, which
7907		 * leaves time for someone to come in with another
7908		 * persistent reservation.  (That is unlikely, though,
7909		 * since this should be the only persistent reservation
7910		 * command active right now.)
7911		 */
7912		if (tmp_len != total_len) {
7913			mtx_unlock(&lun->lun_lock);
7914			free(ctsio->kern_data_ptr, M_CTL);
7915			printf("%s: reservation status changed, retrying\n",
7916			       __func__);
7917			goto retry;
7918		}
7919
7920		/*
7921		 * No reservation held, so we're done.
7922		 */
7923		if (header_only != 0)
7924			break;
7925
7926		/*
7927		 * If the registration is an All Registrants type, the key
7928		 * is 0, since it doesn't really matter.
7929		 */
7930		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7931			memcpy(res->data.reservation,
7932			       &lun->per_res[lun->pr_res_idx].res_key,
7933			       sizeof(struct scsi_per_res_key));
7934		}
7935		res->data.scopetype = lun->res_type;
7936		break;
7937	}
7938	case SPRI_RC:     //report capabilities
7939	{
7940		struct scsi_per_res_cap *res_cap;
7941		uint16_t type_mask;
7942
7943		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7944		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7945		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7946		type_mask = SPRI_TM_WR_EX_AR |
7947			    SPRI_TM_EX_AC_RO |
7948			    SPRI_TM_WR_EX_RO |
7949			    SPRI_TM_EX_AC |
7950			    SPRI_TM_WR_EX |
7951			    SPRI_TM_EX_AC_AR;
7952		scsi_ulto2b(type_mask, res_cap->type_mask);
7953		break;
7954	}
7955	case SPRI_RS: { // read full status
7956		struct scsi_per_res_in_full *res_status;
7957		struct scsi_per_res_in_full_desc *res_desc;
7958		struct ctl_port *port;
7959		int i, len;
7960
7961		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7962
7963		/*
7964		 * We had to drop the lock to allocate our buffer, which
7965		 * leaves time for someone to come in with another
7966		 * persistent reservation.  (That is unlikely, though,
7967		 * since this should be the only persistent reservation
7968		 * command active right now.)
7969		 */
7970		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7971		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7972		     lun->pr_key_count)){
7973			mtx_unlock(&lun->lun_lock);
7974			free(ctsio->kern_data_ptr, M_CTL);
7975			printf("%s: reservation length changed, retrying\n",
7976			       __func__);
7977			goto retry;
7978		}
7979
7980		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7981
7982		res_desc = &res_status->desc[0];
7983		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7984			if (!lun->per_res[i].registered)
7985				continue;
7986
7987			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7988			    sizeof(res_desc->res_key));
7989			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7990			    (lun->pr_res_idx == i ||
7991			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7992				res_desc->flags = SPRI_FULL_R_HOLDER;
7993				res_desc->scopetype = lun->res_type;
7994			}
7995			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7996			    res_desc->rel_trgt_port_id);
7997			len = 0;
7998			port = softc->ctl_ports[
7999			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8000			if (port != NULL)
8001				len = ctl_create_iid(port,
8002				    i % CTL_MAX_INIT_PER_PORT,
8003				    res_desc->transport_id);
8004			scsi_ulto4b(len, res_desc->additional_length);
8005			res_desc = (struct scsi_per_res_in_full_desc *)
8006			    &res_desc->transport_id[len];
8007		}
8008		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8009		    res_status->header.length);
8010		break;
8011	}
8012	default:
8013		/*
8014		 * This is a bug, because we just checked for this above,
8015		 * and should have returned an error.
8016		 */
8017		panic("Invalid PR type %x", cdb->action);
8018		break; /* NOTREACHED */
8019	}
8020	mtx_unlock(&lun->lun_lock);
8021
8022	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8023	ctsio->be_move_done = ctl_config_move_done;
8024
8025	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8026			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8027			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8028			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8029			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8030
8031	ctl_datamove((union ctl_io *)ctsio);
8032
8033	return (CTL_RETVAL_COMPLETE);
8034}
8035
8036/*
8037 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8038 * it should return.
8039 */
8040static int
8041ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8042		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8043		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8044		struct scsi_per_res_out_parms* param)
8045{
8046	union ctl_ha_msg persis_io;
8047	int retval, i;
8048	int isc_retval;
8049
8050	retval = 0;
8051
8052	mtx_lock(&lun->lun_lock);
8053	if (sa_res_key == 0) {
8054		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8055			/* validate scope and type */
8056			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8057			     SPR_LU_SCOPE) {
8058				mtx_unlock(&lun->lun_lock);
8059				ctl_set_invalid_field(/*ctsio*/ ctsio,
8060						      /*sks_valid*/ 1,
8061						      /*command*/ 1,
8062						      /*field*/ 2,
8063						      /*bit_valid*/ 1,
8064						      /*bit*/ 4);
8065				ctl_done((union ctl_io *)ctsio);
8066				return (1);
8067			}
8068
8069		        if (type>8 || type==2 || type==4 || type==0) {
8070				mtx_unlock(&lun->lun_lock);
8071				ctl_set_invalid_field(/*ctsio*/ ctsio,
8072       	           				      /*sks_valid*/ 1,
8073						      /*command*/ 1,
8074						      /*field*/ 2,
8075						      /*bit_valid*/ 1,
8076						      /*bit*/ 0);
8077				ctl_done((union ctl_io *)ctsio);
8078				return (1);
8079		        }
8080
8081			/* temporarily unregister this nexus */
8082			lun->per_res[residx].registered = 0;
8083
8084			/*
8085			 * Unregister everybody else and build UA for
8086			 * them
8087			 */
8088			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8089				if (lun->per_res[i].registered == 0)
8090					continue;
8091
8092				if (!persis_offset
8093				 && i <CTL_MAX_INITIATORS)
8094					lun->pending_ua[i] |=
8095						CTL_UA_REG_PREEMPT;
8096				else if (persis_offset
8097				      && i >= persis_offset)
8098					lun->pending_ua[i-persis_offset] |=
8099						CTL_UA_REG_PREEMPT;
8100				lun->per_res[i].registered = 0;
8101				memset(&lun->per_res[i].res_key, 0,
8102				       sizeof(struct scsi_per_res_key));
8103			}
8104			lun->per_res[residx].registered = 1;
8105			lun->pr_key_count = 1;
8106			lun->res_type = type;
8107			if (lun->res_type != SPR_TYPE_WR_EX_AR
8108			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8109				lun->pr_res_idx = residx;
8110
8111			/* send msg to other side */
8112			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8113			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8114			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8115			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8116			persis_io.pr.pr_info.res_type = type;
8117			memcpy(persis_io.pr.pr_info.sa_res_key,
8118			       param->serv_act_res_key,
8119			       sizeof(param->serv_act_res_key));
8120			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8121			     &persis_io, sizeof(persis_io), 0)) >
8122			     CTL_HA_STATUS_SUCCESS) {
8123				printf("CTL:Persis Out error returned "
8124				       "from ctl_ha_msg_send %d\n",
8125				       isc_retval);
8126			}
8127		} else {
8128			/* not all registrants */
8129			mtx_unlock(&lun->lun_lock);
8130			free(ctsio->kern_data_ptr, M_CTL);
8131			ctl_set_invalid_field(ctsio,
8132					      /*sks_valid*/ 1,
8133					      /*command*/ 0,
8134					      /*field*/ 8,
8135					      /*bit_valid*/ 0,
8136					      /*bit*/ 0);
8137			ctl_done((union ctl_io *)ctsio);
8138			return (1);
8139		}
8140	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8141		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8142		int found = 0;
8143
8144		if (res_key == sa_res_key) {
8145			/* special case */
8146			/*
8147			 * The spec implies this is not good but doesn't
8148			 * say what to do. There are two choices either
8149			 * generate a res conflict or check condition
8150			 * with illegal field in parameter data. Since
8151			 * that is what is done when the sa_res_key is
8152			 * zero I'll take that approach since this has
8153			 * to do with the sa_res_key.
8154			 */
8155			mtx_unlock(&lun->lun_lock);
8156			free(ctsio->kern_data_ptr, M_CTL);
8157			ctl_set_invalid_field(ctsio,
8158					      /*sks_valid*/ 1,
8159					      /*command*/ 0,
8160					      /*field*/ 8,
8161					      /*bit_valid*/ 0,
8162					      /*bit*/ 0);
8163			ctl_done((union ctl_io *)ctsio);
8164			return (1);
8165		}
8166
8167		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8168			if (lun->per_res[i].registered
8169			 && memcmp(param->serv_act_res_key,
8170			    lun->per_res[i].res_key.key,
8171			    sizeof(struct scsi_per_res_key)) != 0)
8172				continue;
8173
8174			found = 1;
8175			lun->per_res[i].registered = 0;
8176			memset(&lun->per_res[i].res_key, 0,
8177			       sizeof(struct scsi_per_res_key));
8178			lun->pr_key_count--;
8179
8180			if (!persis_offset && i < CTL_MAX_INITIATORS)
8181				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8182			else if (persis_offset && i >= persis_offset)
8183				lun->pending_ua[i-persis_offset] |=
8184					CTL_UA_REG_PREEMPT;
8185		}
8186		if (!found) {
8187			mtx_unlock(&lun->lun_lock);
8188			free(ctsio->kern_data_ptr, M_CTL);
8189			ctl_set_reservation_conflict(ctsio);
8190			ctl_done((union ctl_io *)ctsio);
8191			return (CTL_RETVAL_COMPLETE);
8192		}
8193		/* send msg to other side */
8194		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8195		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8196		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8197		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8198		persis_io.pr.pr_info.res_type = type;
8199		memcpy(persis_io.pr.pr_info.sa_res_key,
8200		       param->serv_act_res_key,
8201		       sizeof(param->serv_act_res_key));
8202		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8203		     &persis_io, sizeof(persis_io), 0)) >
8204		     CTL_HA_STATUS_SUCCESS) {
8205			printf("CTL:Persis Out error returned from "
8206			       "ctl_ha_msg_send %d\n", isc_retval);
8207		}
8208	} else {
8209		/* Reserved but not all registrants */
8210		/* sa_res_key is res holder */
8211		if (memcmp(param->serv_act_res_key,
8212                   lun->per_res[lun->pr_res_idx].res_key.key,
8213                   sizeof(struct scsi_per_res_key)) == 0) {
8214			/* validate scope and type */
8215			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8216			     SPR_LU_SCOPE) {
8217				mtx_unlock(&lun->lun_lock);
8218				ctl_set_invalid_field(/*ctsio*/ ctsio,
8219						      /*sks_valid*/ 1,
8220						      /*command*/ 1,
8221						      /*field*/ 2,
8222						      /*bit_valid*/ 1,
8223						      /*bit*/ 4);
8224				ctl_done((union ctl_io *)ctsio);
8225				return (1);
8226			}
8227
8228			if (type>8 || type==2 || type==4 || type==0) {
8229				mtx_unlock(&lun->lun_lock);
8230				ctl_set_invalid_field(/*ctsio*/ ctsio,
8231						      /*sks_valid*/ 1,
8232						      /*command*/ 1,
8233						      /*field*/ 2,
8234						      /*bit_valid*/ 1,
8235						      /*bit*/ 0);
8236				ctl_done((union ctl_io *)ctsio);
8237				return (1);
8238			}
8239
8240			/*
8241			 * Do the following:
8242			 * if sa_res_key != res_key remove all
8243			 * registrants w/sa_res_key and generate UA
8244			 * for these registrants(Registrations
8245			 * Preempted) if it wasn't an exclusive
8246			 * reservation generate UA(Reservations
8247			 * Preempted) for all other registered nexuses
8248			 * if the type has changed. Establish the new
8249			 * reservation and holder. If res_key and
8250			 * sa_res_key are the same do the above
8251			 * except don't unregister the res holder.
8252			 */
8253
8254			/*
8255			 * Temporarily unregister so it won't get
8256			 * removed or UA generated
8257			 */
8258			lun->per_res[residx].registered = 0;
8259			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8260				if (lun->per_res[i].registered == 0)
8261					continue;
8262
8263				if (memcmp(param->serv_act_res_key,
8264				    lun->per_res[i].res_key.key,
8265				    sizeof(struct scsi_per_res_key)) == 0) {
8266					lun->per_res[i].registered = 0;
8267					memset(&lun->per_res[i].res_key,
8268					       0,
8269					       sizeof(struct scsi_per_res_key));
8270					lun->pr_key_count--;
8271
8272					if (!persis_offset
8273					 && i < CTL_MAX_INITIATORS)
8274						lun->pending_ua[i] |=
8275							CTL_UA_REG_PREEMPT;
8276					else if (persis_offset
8277					      && i >= persis_offset)
8278						lun->pending_ua[i-persis_offset] |=
8279						  CTL_UA_REG_PREEMPT;
8280				} else if (type != lun->res_type
8281					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8282					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8283						if (!persis_offset
8284						 && i < CTL_MAX_INITIATORS)
8285							lun->pending_ua[i] |=
8286							CTL_UA_RES_RELEASE;
8287						else if (persis_offset
8288						      && i >= persis_offset)
8289							lun->pending_ua[
8290							i-persis_offset] |=
8291							CTL_UA_RES_RELEASE;
8292				}
8293			}
8294			lun->per_res[residx].registered = 1;
8295			lun->res_type = type;
8296			if (lun->res_type != SPR_TYPE_WR_EX_AR
8297			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8298				lun->pr_res_idx = residx;
8299			else
8300				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8301
8302			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8303			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8304			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8305			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8306			persis_io.pr.pr_info.res_type = type;
8307			memcpy(persis_io.pr.pr_info.sa_res_key,
8308			       param->serv_act_res_key,
8309			       sizeof(param->serv_act_res_key));
8310			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8311			     &persis_io, sizeof(persis_io), 0)) >
8312			     CTL_HA_STATUS_SUCCESS) {
8313				printf("CTL:Persis Out error returned "
8314				       "from ctl_ha_msg_send %d\n",
8315				       isc_retval);
8316			}
8317		} else {
8318			/*
8319			 * sa_res_key is not the res holder just
8320			 * remove registrants
8321			 */
8322			int found=0;
8323
8324			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8325				if (memcmp(param->serv_act_res_key,
8326				    lun->per_res[i].res_key.key,
8327				    sizeof(struct scsi_per_res_key)) != 0)
8328					continue;
8329
8330				found = 1;
8331				lun->per_res[i].registered = 0;
8332				memset(&lun->per_res[i].res_key, 0,
8333				       sizeof(struct scsi_per_res_key));
8334				lun->pr_key_count--;
8335
8336				if (!persis_offset
8337				 && i < CTL_MAX_INITIATORS)
8338					lun->pending_ua[i] |=
8339						CTL_UA_REG_PREEMPT;
8340				else if (persis_offset
8341				      && i >= persis_offset)
8342					lun->pending_ua[i-persis_offset] |=
8343						CTL_UA_REG_PREEMPT;
8344			}
8345
8346			if (!found) {
8347				mtx_unlock(&lun->lun_lock);
8348				free(ctsio->kern_data_ptr, M_CTL);
8349				ctl_set_reservation_conflict(ctsio);
8350				ctl_done((union ctl_io *)ctsio);
8351		        	return (1);
8352			}
8353			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8354			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8355			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8356			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8357			persis_io.pr.pr_info.res_type = type;
8358			memcpy(persis_io.pr.pr_info.sa_res_key,
8359			       param->serv_act_res_key,
8360			       sizeof(param->serv_act_res_key));
8361			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8362			     &persis_io, sizeof(persis_io), 0)) >
8363			     CTL_HA_STATUS_SUCCESS) {
8364				printf("CTL:Persis Out error returned "
8365				       "from ctl_ha_msg_send %d\n",
8366				isc_retval);
8367			}
8368		}
8369	}
8370
8371	lun->PRGeneration++;
8372	mtx_unlock(&lun->lun_lock);
8373
8374	return (retval);
8375}
8376
8377static void
8378ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8379{
8380	int i;
8381
8382	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8383	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8384	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8385		   msg->pr.pr_info.sa_res_key,
8386		   sizeof(struct scsi_per_res_key)) != 0) {
8387		uint64_t sa_res_key;
8388		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8389
8390		if (sa_res_key == 0) {
8391			/* temporarily unregister this nexus */
8392			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8393
8394			/*
8395			 * Unregister everybody else and build UA for
8396			 * them
8397			 */
8398			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8399				if (lun->per_res[i].registered == 0)
8400					continue;
8401
8402				if (!persis_offset
8403				 && i < CTL_MAX_INITIATORS)
8404					lun->pending_ua[i] |=
8405						CTL_UA_REG_PREEMPT;
8406				else if (persis_offset && i >= persis_offset)
8407					lun->pending_ua[i - persis_offset] |=
8408						CTL_UA_REG_PREEMPT;
8409				lun->per_res[i].registered = 0;
8410				memset(&lun->per_res[i].res_key, 0,
8411				       sizeof(struct scsi_per_res_key));
8412			}
8413
8414			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8415			lun->pr_key_count = 1;
8416			lun->res_type = msg->pr.pr_info.res_type;
8417			if (lun->res_type != SPR_TYPE_WR_EX_AR
8418			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8419				lun->pr_res_idx = msg->pr.pr_info.residx;
8420		} else {
8421		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8422				if (memcmp(msg->pr.pr_info.sa_res_key,
8423		                   lun->per_res[i].res_key.key,
8424		                   sizeof(struct scsi_per_res_key)) != 0)
8425					continue;
8426
8427				lun->per_res[i].registered = 0;
8428				memset(&lun->per_res[i].res_key, 0,
8429				       sizeof(struct scsi_per_res_key));
8430				lun->pr_key_count--;
8431
8432				if (!persis_offset
8433				 && i < persis_offset)
8434					lun->pending_ua[i] |=
8435						CTL_UA_REG_PREEMPT;
8436				else if (persis_offset
8437				      && i >= persis_offset)
8438					lun->pending_ua[i - persis_offset] |=
8439						CTL_UA_REG_PREEMPT;
8440			}
8441		}
8442	} else {
8443		/*
8444		 * Temporarily unregister so it won't get removed
8445		 * or UA generated
8446		 */
8447		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8448		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8449			if (lun->per_res[i].registered == 0)
8450				continue;
8451
8452			if (memcmp(msg->pr.pr_info.sa_res_key,
8453	                   lun->per_res[i].res_key.key,
8454	                   sizeof(struct scsi_per_res_key)) == 0) {
8455				lun->per_res[i].registered = 0;
8456				memset(&lun->per_res[i].res_key, 0,
8457				       sizeof(struct scsi_per_res_key));
8458				lun->pr_key_count--;
8459				if (!persis_offset
8460				 && i < CTL_MAX_INITIATORS)
8461					lun->pending_ua[i] |=
8462						CTL_UA_REG_PREEMPT;
8463				else if (persis_offset
8464				      && i >= persis_offset)
8465					lun->pending_ua[i - persis_offset] |=
8466						CTL_UA_REG_PREEMPT;
8467			} else if (msg->pr.pr_info.res_type != lun->res_type
8468				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8469				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8470					if (!persis_offset
8471					 && i < persis_offset)
8472						lun->pending_ua[i] |=
8473							CTL_UA_RES_RELEASE;
8474					else if (persis_offset
8475					      && i >= persis_offset)
8476					lun->pending_ua[i - persis_offset] |=
8477						CTL_UA_RES_RELEASE;
8478			}
8479		}
8480		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8481		lun->res_type = msg->pr.pr_info.res_type;
8482		if (lun->res_type != SPR_TYPE_WR_EX_AR
8483		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8484			lun->pr_res_idx = msg->pr.pr_info.residx;
8485		else
8486			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8487	}
8488	lun->PRGeneration++;
8489
8490}
8491
8492
8493int
8494ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8495{
8496	int retval;
8497	int isc_retval;
8498	u_int32_t param_len;
8499	struct scsi_per_res_out *cdb;
8500	struct ctl_lun *lun;
8501	struct scsi_per_res_out_parms* param;
8502	struct ctl_softc *softc;
8503	uint32_t residx;
8504	uint64_t res_key, sa_res_key;
8505	uint8_t type;
8506	union ctl_ha_msg persis_io;
8507	int    i;
8508
8509	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8510
8511	retval = CTL_RETVAL_COMPLETE;
8512
8513	softc = control_softc;
8514
8515	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8516	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8517
8518	/*
8519	 * We only support whole-LUN scope.  The scope & type are ignored for
8520	 * register, register and ignore existing key and clear.
8521	 * We sometimes ignore scope and type on preempts too!!
8522	 * Verify reservation type here as well.
8523	 */
8524	type = cdb->scope_type & SPR_TYPE_MASK;
8525	if ((cdb->action == SPRO_RESERVE)
8526	 || (cdb->action == SPRO_RELEASE)) {
8527		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8528			ctl_set_invalid_field(/*ctsio*/ ctsio,
8529					      /*sks_valid*/ 1,
8530					      /*command*/ 1,
8531					      /*field*/ 2,
8532					      /*bit_valid*/ 1,
8533					      /*bit*/ 4);
8534			ctl_done((union ctl_io *)ctsio);
8535			return (CTL_RETVAL_COMPLETE);
8536		}
8537
8538		if (type>8 || type==2 || type==4 || type==0) {
8539			ctl_set_invalid_field(/*ctsio*/ ctsio,
8540					      /*sks_valid*/ 1,
8541					      /*command*/ 1,
8542					      /*field*/ 2,
8543					      /*bit_valid*/ 1,
8544					      /*bit*/ 0);
8545			ctl_done((union ctl_io *)ctsio);
8546			return (CTL_RETVAL_COMPLETE);
8547		}
8548	}
8549
8550	param_len = scsi_4btoul(cdb->length);
8551
8552	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8553		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8554		ctsio->kern_data_len = param_len;
8555		ctsio->kern_total_len = param_len;
8556		ctsio->kern_data_resid = 0;
8557		ctsio->kern_rel_offset = 0;
8558		ctsio->kern_sg_entries = 0;
8559		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8560		ctsio->be_move_done = ctl_config_move_done;
8561		ctl_datamove((union ctl_io *)ctsio);
8562
8563		return (CTL_RETVAL_COMPLETE);
8564	}
8565
8566	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8567
8568	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8569	res_key = scsi_8btou64(param->res_key.key);
8570	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8571
8572	/*
8573	 * Validate the reservation key here except for SPRO_REG_IGNO
8574	 * This must be done for all other service actions
8575	 */
8576	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8577		mtx_lock(&lun->lun_lock);
8578		if (lun->per_res[residx].registered) {
8579		    if (memcmp(param->res_key.key,
8580			       lun->per_res[residx].res_key.key,
8581			       ctl_min(sizeof(param->res_key),
8582			       sizeof(lun->per_res[residx].res_key))) != 0) {
8583				/*
8584				 * The current key passed in doesn't match
8585				 * the one the initiator previously
8586				 * registered.
8587				 */
8588				mtx_unlock(&lun->lun_lock);
8589				free(ctsio->kern_data_ptr, M_CTL);
8590				ctl_set_reservation_conflict(ctsio);
8591				ctl_done((union ctl_io *)ctsio);
8592				return (CTL_RETVAL_COMPLETE);
8593			}
8594		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8595			/*
8596			 * We are not registered
8597			 */
8598			mtx_unlock(&lun->lun_lock);
8599			free(ctsio->kern_data_ptr, M_CTL);
8600			ctl_set_reservation_conflict(ctsio);
8601			ctl_done((union ctl_io *)ctsio);
8602			return (CTL_RETVAL_COMPLETE);
8603		} else if (res_key != 0) {
8604			/*
8605			 * We are not registered and trying to register but
8606			 * the register key isn't zero.
8607			 */
8608			mtx_unlock(&lun->lun_lock);
8609			free(ctsio->kern_data_ptr, M_CTL);
8610			ctl_set_reservation_conflict(ctsio);
8611			ctl_done((union ctl_io *)ctsio);
8612			return (CTL_RETVAL_COMPLETE);
8613		}
8614		mtx_unlock(&lun->lun_lock);
8615	}
8616
8617	switch (cdb->action & SPRO_ACTION_MASK) {
8618	case SPRO_REGISTER:
8619	case SPRO_REG_IGNO: {
8620
8621#if 0
8622		printf("Registration received\n");
8623#endif
8624
8625		/*
8626		 * We don't support any of these options, as we report in
8627		 * the read capabilities request (see
8628		 * ctl_persistent_reserve_in(), above).
8629		 */
8630		if ((param->flags & SPR_SPEC_I_PT)
8631		 || (param->flags & SPR_ALL_TG_PT)
8632		 || (param->flags & SPR_APTPL)) {
8633			int bit_ptr;
8634
8635			if (param->flags & SPR_APTPL)
8636				bit_ptr = 0;
8637			else if (param->flags & SPR_ALL_TG_PT)
8638				bit_ptr = 2;
8639			else /* SPR_SPEC_I_PT */
8640				bit_ptr = 3;
8641
8642			free(ctsio->kern_data_ptr, M_CTL);
8643			ctl_set_invalid_field(ctsio,
8644					      /*sks_valid*/ 1,
8645					      /*command*/ 0,
8646					      /*field*/ 20,
8647					      /*bit_valid*/ 1,
8648					      /*bit*/ bit_ptr);
8649			ctl_done((union ctl_io *)ctsio);
8650			return (CTL_RETVAL_COMPLETE);
8651		}
8652
8653		mtx_lock(&lun->lun_lock);
8654
8655		/*
8656		 * The initiator wants to clear the
8657		 * key/unregister.
8658		 */
8659		if (sa_res_key == 0) {
8660			if ((res_key == 0
8661			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8662			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8663			  && !lun->per_res[residx].registered)) {
8664				mtx_unlock(&lun->lun_lock);
8665				goto done;
8666			}
8667
8668			lun->per_res[residx].registered = 0;
8669			memset(&lun->per_res[residx].res_key,
8670			       0, sizeof(lun->per_res[residx].res_key));
8671			lun->pr_key_count--;
8672
8673			if (residx == lun->pr_res_idx) {
8674				lun->flags &= ~CTL_LUN_PR_RESERVED;
8675				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8676
8677				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8678				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8679				 && lun->pr_key_count) {
8680					/*
8681					 * If the reservation is a registrants
8682					 * only type we need to generate a UA
8683					 * for other registered inits.  The
8684					 * sense code should be RESERVATIONS
8685					 * RELEASED
8686					 */
8687
8688					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8689						if (lun->per_res[
8690						    i+persis_offset].registered
8691						    == 0)
8692							continue;
8693						lun->pending_ua[i] |=
8694							CTL_UA_RES_RELEASE;
8695					}
8696				}
8697				lun->res_type = 0;
8698			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8699				if (lun->pr_key_count==0) {
8700					lun->flags &= ~CTL_LUN_PR_RESERVED;
8701					lun->res_type = 0;
8702					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8703				}
8704			}
8705			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8706			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8707			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8708			persis_io.pr.pr_info.residx = residx;
8709			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8710			     &persis_io, sizeof(persis_io), 0 )) >
8711			     CTL_HA_STATUS_SUCCESS) {
8712				printf("CTL:Persis Out error returned from "
8713				       "ctl_ha_msg_send %d\n", isc_retval);
8714			}
8715		} else /* sa_res_key != 0 */ {
8716
8717			/*
8718			 * If we aren't registered currently then increment
8719			 * the key count and set the registered flag.
8720			 */
8721			if (!lun->per_res[residx].registered) {
8722				lun->pr_key_count++;
8723				lun->per_res[residx].registered = 1;
8724			}
8725
8726			memcpy(&lun->per_res[residx].res_key,
8727			       param->serv_act_res_key,
8728			       ctl_min(sizeof(param->serv_act_res_key),
8729			       sizeof(lun->per_res[residx].res_key)));
8730
8731			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8732			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8733			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8734			persis_io.pr.pr_info.residx = residx;
8735			memcpy(persis_io.pr.pr_info.sa_res_key,
8736			       param->serv_act_res_key,
8737			       sizeof(param->serv_act_res_key));
8738			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8739			     &persis_io, sizeof(persis_io), 0)) >
8740			     CTL_HA_STATUS_SUCCESS) {
8741				printf("CTL:Persis Out error returned from "
8742				       "ctl_ha_msg_send %d\n", isc_retval);
8743			}
8744		}
8745		lun->PRGeneration++;
8746		mtx_unlock(&lun->lun_lock);
8747
8748		break;
8749	}
8750	case SPRO_RESERVE:
8751#if 0
8752                printf("Reserve executed type %d\n", type);
8753#endif
8754		mtx_lock(&lun->lun_lock);
8755		if (lun->flags & CTL_LUN_PR_RESERVED) {
8756			/*
8757			 * if this isn't the reservation holder and it's
8758			 * not a "all registrants" type or if the type is
8759			 * different then we have a conflict
8760			 */
8761			if ((lun->pr_res_idx != residx
8762			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8763			 || lun->res_type != type) {
8764				mtx_unlock(&lun->lun_lock);
8765				free(ctsio->kern_data_ptr, M_CTL);
8766				ctl_set_reservation_conflict(ctsio);
8767				ctl_done((union ctl_io *)ctsio);
8768				return (CTL_RETVAL_COMPLETE);
8769			}
8770			mtx_unlock(&lun->lun_lock);
8771		} else /* create a reservation */ {
8772			/*
8773			 * If it's not an "all registrants" type record
8774			 * reservation holder
8775			 */
8776			if (type != SPR_TYPE_WR_EX_AR
8777			 && type != SPR_TYPE_EX_AC_AR)
8778				lun->pr_res_idx = residx; /* Res holder */
8779			else
8780				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8781
8782			lun->flags |= CTL_LUN_PR_RESERVED;
8783			lun->res_type = type;
8784
8785			mtx_unlock(&lun->lun_lock);
8786
8787			/* send msg to other side */
8788			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8789			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8790			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8791			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8792			persis_io.pr.pr_info.res_type = type;
8793			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8794			     &persis_io, sizeof(persis_io), 0)) >
8795			     CTL_HA_STATUS_SUCCESS) {
8796				printf("CTL:Persis Out error returned from "
8797				       "ctl_ha_msg_send %d\n", isc_retval);
8798			}
8799		}
8800		break;
8801
8802	case SPRO_RELEASE:
8803		mtx_lock(&lun->lun_lock);
8804		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8805			/* No reservation exists return good status */
8806			mtx_unlock(&lun->lun_lock);
8807			goto done;
8808		}
8809		/*
8810		 * Is this nexus a reservation holder?
8811		 */
8812		if (lun->pr_res_idx != residx
8813		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8814			/*
8815			 * not a res holder return good status but
8816			 * do nothing
8817			 */
8818			mtx_unlock(&lun->lun_lock);
8819			goto done;
8820		}
8821
8822		if (lun->res_type != type) {
8823			mtx_unlock(&lun->lun_lock);
8824			free(ctsio->kern_data_ptr, M_CTL);
8825			ctl_set_illegal_pr_release(ctsio);
8826			ctl_done((union ctl_io *)ctsio);
8827			return (CTL_RETVAL_COMPLETE);
8828		}
8829
8830		/* okay to release */
8831		lun->flags &= ~CTL_LUN_PR_RESERVED;
8832		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8833		lun->res_type = 0;
8834
8835		/*
8836		 * if this isn't an exclusive access
8837		 * res generate UA for all other
8838		 * registrants.
8839		 */
8840		if (type != SPR_TYPE_EX_AC
8841		 && type != SPR_TYPE_WR_EX) {
8842			/*
8843			 * temporarily unregister so we don't generate UA
8844			 */
8845			lun->per_res[residx].registered = 0;
8846
8847			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8848				if (lun->per_res[i+persis_offset].registered
8849				    == 0)
8850					continue;
8851				lun->pending_ua[i] |=
8852					CTL_UA_RES_RELEASE;
8853			}
8854
8855			lun->per_res[residx].registered = 1;
8856		}
8857		mtx_unlock(&lun->lun_lock);
8858		/* Send msg to other side */
8859		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8860		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8861		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8862		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8863		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8864			printf("CTL:Persis Out error returned from "
8865			       "ctl_ha_msg_send %d\n", isc_retval);
8866		}
8867		break;
8868
8869	case SPRO_CLEAR:
8870		/* send msg to other side */
8871
8872		mtx_lock(&lun->lun_lock);
8873		lun->flags &= ~CTL_LUN_PR_RESERVED;
8874		lun->res_type = 0;
8875		lun->pr_key_count = 0;
8876		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8877
8878
8879		memset(&lun->per_res[residx].res_key,
8880		       0, sizeof(lun->per_res[residx].res_key));
8881		lun->per_res[residx].registered = 0;
8882
8883		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8884			if (lun->per_res[i].registered) {
8885				if (!persis_offset && i < CTL_MAX_INITIATORS)
8886					lun->pending_ua[i] |=
8887						CTL_UA_RES_PREEMPT;
8888				else if (persis_offset && i >= persis_offset)
8889					lun->pending_ua[i-persis_offset] |=
8890					    CTL_UA_RES_PREEMPT;
8891
8892				memset(&lun->per_res[i].res_key,
8893				       0, sizeof(struct scsi_per_res_key));
8894				lun->per_res[i].registered = 0;
8895			}
8896		lun->PRGeneration++;
8897		mtx_unlock(&lun->lun_lock);
8898		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8899		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8900		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8901		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8902		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8903			printf("CTL:Persis Out error returned from "
8904			       "ctl_ha_msg_send %d\n", isc_retval);
8905		}
8906		break;
8907
8908	case SPRO_PREEMPT: {
8909		int nretval;
8910
8911		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8912					  residx, ctsio, cdb, param);
8913		if (nretval != 0)
8914			return (CTL_RETVAL_COMPLETE);
8915		break;
8916	}
8917	default:
8918		panic("Invalid PR type %x", cdb->action);
8919	}
8920
8921done:
8922	free(ctsio->kern_data_ptr, M_CTL);
8923	ctl_set_success(ctsio);
8924	ctl_done((union ctl_io *)ctsio);
8925
8926	return (retval);
8927}
8928
8929/*
8930 * This routine is for handling a message from the other SC pertaining to
8931 * persistent reserve out. All the error checking will have been done
8932 * so only perorming the action need be done here to keep the two
8933 * in sync.
8934 */
8935static void
8936ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8937{
8938	struct ctl_lun *lun;
8939	struct ctl_softc *softc;
8940	int i;
8941	uint32_t targ_lun;
8942
8943	softc = control_softc;
8944
8945	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8946	lun = softc->ctl_luns[targ_lun];
8947	mtx_lock(&lun->lun_lock);
8948	switch(msg->pr.pr_info.action) {
8949	case CTL_PR_REG_KEY:
8950		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8951			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8952			lun->pr_key_count++;
8953		}
8954		lun->PRGeneration++;
8955		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8956		       msg->pr.pr_info.sa_res_key,
8957		       sizeof(struct scsi_per_res_key));
8958		break;
8959
8960	case CTL_PR_UNREG_KEY:
8961		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8962		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8963		       0, sizeof(struct scsi_per_res_key));
8964		lun->pr_key_count--;
8965
8966		/* XXX Need to see if the reservation has been released */
8967		/* if so do we need to generate UA? */
8968		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8969			lun->flags &= ~CTL_LUN_PR_RESERVED;
8970			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8971
8972			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8973			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8974			 && lun->pr_key_count) {
8975				/*
8976				 * If the reservation is a registrants
8977				 * only type we need to generate a UA
8978				 * for other registered inits.  The
8979				 * sense code should be RESERVATIONS
8980				 * RELEASED
8981				 */
8982
8983				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8984					if (lun->per_res[i+
8985					    persis_offset].registered == 0)
8986						continue;
8987
8988					lun->pending_ua[i] |=
8989						CTL_UA_RES_RELEASE;
8990				}
8991			}
8992			lun->res_type = 0;
8993		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8994			if (lun->pr_key_count==0) {
8995				lun->flags &= ~CTL_LUN_PR_RESERVED;
8996				lun->res_type = 0;
8997				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8998			}
8999		}
9000		lun->PRGeneration++;
9001		break;
9002
9003	case CTL_PR_RESERVE:
9004		lun->flags |= CTL_LUN_PR_RESERVED;
9005		lun->res_type = msg->pr.pr_info.res_type;
9006		lun->pr_res_idx = msg->pr.pr_info.residx;
9007
9008		break;
9009
9010	case CTL_PR_RELEASE:
9011		/*
9012		 * if this isn't an exclusive access res generate UA for all
9013		 * other registrants.
9014		 */
9015		if (lun->res_type != SPR_TYPE_EX_AC
9016		 && lun->res_type != SPR_TYPE_WR_EX) {
9017			for (i = 0; i < CTL_MAX_INITIATORS; i++)
9018				if (lun->per_res[i+persis_offset].registered)
9019					lun->pending_ua[i] |=
9020						CTL_UA_RES_RELEASE;
9021		}
9022
9023		lun->flags &= ~CTL_LUN_PR_RESERVED;
9024		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9025		lun->res_type = 0;
9026		break;
9027
9028	case CTL_PR_PREEMPT:
9029		ctl_pro_preempt_other(lun, msg);
9030		break;
9031	case CTL_PR_CLEAR:
9032		lun->flags &= ~CTL_LUN_PR_RESERVED;
9033		lun->res_type = 0;
9034		lun->pr_key_count = 0;
9035		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9036
9037		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9038			if (lun->per_res[i].registered == 0)
9039				continue;
9040			if (!persis_offset
9041			 && i < CTL_MAX_INITIATORS)
9042				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9043			else if (persis_offset
9044			      && i >= persis_offset)
9045				lun->pending_ua[i-persis_offset] |=
9046					CTL_UA_RES_PREEMPT;
9047			memset(&lun->per_res[i].res_key, 0,
9048			       sizeof(struct scsi_per_res_key));
9049			lun->per_res[i].registered = 0;
9050		}
9051		lun->PRGeneration++;
9052		break;
9053	}
9054
9055	mtx_unlock(&lun->lun_lock);
9056}
9057
9058int
9059ctl_read_write(struct ctl_scsiio *ctsio)
9060{
9061	struct ctl_lun *lun;
9062	struct ctl_lba_len_flags *lbalen;
9063	uint64_t lba;
9064	uint32_t num_blocks;
9065	int flags, retval;
9066	int isread;
9067
9068	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9069
9070	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9071
9072	flags = 0;
9073	retval = CTL_RETVAL_COMPLETE;
9074
9075	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9076	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9077	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9078		uint32_t residx;
9079
9080		/*
9081		 * XXX KDM need a lock here.
9082		 */
9083		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9084		if ((lun->res_type == SPR_TYPE_EX_AC
9085		  && residx != lun->pr_res_idx)
9086		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9087		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9088		  && !lun->per_res[residx].registered)) {
9089			ctl_set_reservation_conflict(ctsio);
9090			ctl_done((union ctl_io *)ctsio);
9091			return (CTL_RETVAL_COMPLETE);
9092	        }
9093	}
9094
9095	switch (ctsio->cdb[0]) {
9096	case READ_6:
9097	case WRITE_6: {
9098		struct scsi_rw_6 *cdb;
9099
9100		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9101
9102		lba = scsi_3btoul(cdb->addr);
9103		/* only 5 bits are valid in the most significant address byte */
9104		lba &= 0x1fffff;
9105		num_blocks = cdb->length;
9106		/*
9107		 * This is correct according to SBC-2.
9108		 */
9109		if (num_blocks == 0)
9110			num_blocks = 256;
9111		break;
9112	}
9113	case READ_10:
9114	case WRITE_10: {
9115		struct scsi_rw_10 *cdb;
9116
9117		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9118		if (cdb->byte2 & SRW10_FUA)
9119			flags |= CTL_LLF_FUA;
9120		if (cdb->byte2 & SRW10_DPO)
9121			flags |= CTL_LLF_DPO;
9122		lba = scsi_4btoul(cdb->addr);
9123		num_blocks = scsi_2btoul(cdb->length);
9124		break;
9125	}
9126	case WRITE_VERIFY_10: {
9127		struct scsi_write_verify_10 *cdb;
9128
9129		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9130		flags |= CTL_LLF_FUA;
9131		if (cdb->byte2 & SWV_DPO)
9132			flags |= CTL_LLF_DPO;
9133		lba = scsi_4btoul(cdb->addr);
9134		num_blocks = scsi_2btoul(cdb->length);
9135		break;
9136	}
9137	case READ_12:
9138	case WRITE_12: {
9139		struct scsi_rw_12 *cdb;
9140
9141		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9142		if (cdb->byte2 & SRW12_FUA)
9143			flags |= CTL_LLF_FUA;
9144		if (cdb->byte2 & SRW12_DPO)
9145			flags |= CTL_LLF_DPO;
9146		lba = scsi_4btoul(cdb->addr);
9147		num_blocks = scsi_4btoul(cdb->length);
9148		break;
9149	}
9150	case WRITE_VERIFY_12: {
9151		struct scsi_write_verify_12 *cdb;
9152
9153		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9154		flags |= CTL_LLF_FUA;
9155		if (cdb->byte2 & SWV_DPO)
9156			flags |= CTL_LLF_DPO;
9157		lba = scsi_4btoul(cdb->addr);
9158		num_blocks = scsi_4btoul(cdb->length);
9159		break;
9160	}
9161	case READ_16:
9162	case WRITE_16: {
9163		struct scsi_rw_16 *cdb;
9164
9165		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9166		if (cdb->byte2 & SRW12_FUA)
9167			flags |= CTL_LLF_FUA;
9168		if (cdb->byte2 & SRW12_DPO)
9169			flags |= CTL_LLF_DPO;
9170		lba = scsi_8btou64(cdb->addr);
9171		num_blocks = scsi_4btoul(cdb->length);
9172		break;
9173	}
9174	case WRITE_VERIFY_16: {
9175		struct scsi_write_verify_16 *cdb;
9176
9177		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9178		flags |= CTL_LLF_FUA;
9179		if (cdb->byte2 & SWV_DPO)
9180			flags |= CTL_LLF_DPO;
9181		lba = scsi_8btou64(cdb->addr);
9182		num_blocks = scsi_4btoul(cdb->length);
9183		break;
9184	}
9185	default:
9186		/*
9187		 * We got a command we don't support.  This shouldn't
9188		 * happen, commands should be filtered out above us.
9189		 */
9190		ctl_set_invalid_opcode(ctsio);
9191		ctl_done((union ctl_io *)ctsio);
9192
9193		return (CTL_RETVAL_COMPLETE);
9194		break; /* NOTREACHED */
9195	}
9196
9197	/*
9198	 * The first check is to make sure we're in bounds, the second
9199	 * check is to catch wrap-around problems.  If the lba + num blocks
9200	 * is less than the lba, then we've wrapped around and the block
9201	 * range is invalid anyway.
9202	 */
9203	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9204	 || ((lba + num_blocks) < lba)) {
9205		ctl_set_lba_out_of_range(ctsio);
9206		ctl_done((union ctl_io *)ctsio);
9207		return (CTL_RETVAL_COMPLETE);
9208	}
9209
9210	/*
9211	 * According to SBC-3, a transfer length of 0 is not an error.
9212	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9213	 * translates to 256 blocks for those commands.
9214	 */
9215	if (num_blocks == 0) {
9216		ctl_set_success(ctsio);
9217		ctl_done((union ctl_io *)ctsio);
9218		return (CTL_RETVAL_COMPLETE);
9219	}
9220
9221	/* Set FUA and/or DPO if caches are disabled. */
9222	if (isread) {
9223		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9224		    SCP_RCD) != 0)
9225			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9226	} else {
9227		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9228		    SCP_WCE) == 0)
9229			flags |= CTL_LLF_FUA;
9230	}
9231
9232	lbalen = (struct ctl_lba_len_flags *)
9233	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9234	lbalen->lba = lba;
9235	lbalen->len = num_blocks;
9236	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9237
9238	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9239	ctsio->kern_rel_offset = 0;
9240
9241	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9242
9243	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9244
9245	return (retval);
9246}
9247
9248static int
9249ctl_cnw_cont(union ctl_io *io)
9250{
9251	struct ctl_scsiio *ctsio;
9252	struct ctl_lun *lun;
9253	struct ctl_lba_len_flags *lbalen;
9254	int retval;
9255
9256	ctsio = &io->scsiio;
9257	ctsio->io_hdr.status = CTL_STATUS_NONE;
9258	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9259	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9260	lbalen = (struct ctl_lba_len_flags *)
9261	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9262	lbalen->flags &= ~CTL_LLF_COMPARE;
9263	lbalen->flags |= CTL_LLF_WRITE;
9264
9265	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9266	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9267	return (retval);
9268}
9269
9270int
9271ctl_cnw(struct ctl_scsiio *ctsio)
9272{
9273	struct ctl_lun *lun;
9274	struct ctl_lba_len_flags *lbalen;
9275	uint64_t lba;
9276	uint32_t num_blocks;
9277	int flags, retval;
9278
9279	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9280
9281	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9282
9283	flags = 0;
9284	retval = CTL_RETVAL_COMPLETE;
9285
9286	switch (ctsio->cdb[0]) {
9287	case COMPARE_AND_WRITE: {
9288		struct scsi_compare_and_write *cdb;
9289
9290		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9291		if (cdb->byte2 & SRW10_FUA)
9292			flags |= CTL_LLF_FUA;
9293		if (cdb->byte2 & SRW10_DPO)
9294			flags |= CTL_LLF_DPO;
9295		lba = scsi_8btou64(cdb->addr);
9296		num_blocks = cdb->length;
9297		break;
9298	}
9299	default:
9300		/*
9301		 * We got a command we don't support.  This shouldn't
9302		 * happen, commands should be filtered out above us.
9303		 */
9304		ctl_set_invalid_opcode(ctsio);
9305		ctl_done((union ctl_io *)ctsio);
9306
9307		return (CTL_RETVAL_COMPLETE);
9308		break; /* NOTREACHED */
9309	}
9310
9311	/*
9312	 * The first check is to make sure we're in bounds, the second
9313	 * check is to catch wrap-around problems.  If the lba + num blocks
9314	 * is less than the lba, then we've wrapped around and the block
9315	 * range is invalid anyway.
9316	 */
9317	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9318	 || ((lba + num_blocks) < lba)) {
9319		ctl_set_lba_out_of_range(ctsio);
9320		ctl_done((union ctl_io *)ctsio);
9321		return (CTL_RETVAL_COMPLETE);
9322	}
9323
9324	/*
9325	 * According to SBC-3, a transfer length of 0 is not an error.
9326	 */
9327	if (num_blocks == 0) {
9328		ctl_set_success(ctsio);
9329		ctl_done((union ctl_io *)ctsio);
9330		return (CTL_RETVAL_COMPLETE);
9331	}
9332
9333	/* Set FUA if write cache is disabled. */
9334	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9335	    SCP_WCE) == 0)
9336		flags |= CTL_LLF_FUA;
9337
9338	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9339	ctsio->kern_rel_offset = 0;
9340
9341	/*
9342	 * Set the IO_CONT flag, so that if this I/O gets passed to
9343	 * ctl_data_submit_done(), it'll get passed back to
9344	 * ctl_ctl_cnw_cont() for further processing.
9345	 */
9346	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9347	ctsio->io_cont = ctl_cnw_cont;
9348
9349	lbalen = (struct ctl_lba_len_flags *)
9350	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9351	lbalen->lba = lba;
9352	lbalen->len = num_blocks;
9353	lbalen->flags = CTL_LLF_COMPARE | flags;
9354
9355	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9356	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9357	return (retval);
9358}
9359
9360int
9361ctl_verify(struct ctl_scsiio *ctsio)
9362{
9363	struct ctl_lun *lun;
9364	struct ctl_lba_len_flags *lbalen;
9365	uint64_t lba;
9366	uint32_t num_blocks;
9367	int bytchk, flags;
9368	int retval;
9369
9370	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9371
9372	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9373
9374	bytchk = 0;
9375	flags = CTL_LLF_FUA;
9376	retval = CTL_RETVAL_COMPLETE;
9377
9378	switch (ctsio->cdb[0]) {
9379	case VERIFY_10: {
9380		struct scsi_verify_10 *cdb;
9381
9382		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9383		if (cdb->byte2 & SVFY_BYTCHK)
9384			bytchk = 1;
9385		if (cdb->byte2 & SVFY_DPO)
9386			flags |= CTL_LLF_DPO;
9387		lba = scsi_4btoul(cdb->addr);
9388		num_blocks = scsi_2btoul(cdb->length);
9389		break;
9390	}
9391	case VERIFY_12: {
9392		struct scsi_verify_12 *cdb;
9393
9394		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9395		if (cdb->byte2 & SVFY_BYTCHK)
9396			bytchk = 1;
9397		if (cdb->byte2 & SVFY_DPO)
9398			flags |= CTL_LLF_DPO;
9399		lba = scsi_4btoul(cdb->addr);
9400		num_blocks = scsi_4btoul(cdb->length);
9401		break;
9402	}
9403	case VERIFY_16: {
9404		struct scsi_rw_16 *cdb;
9405
9406		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9407		if (cdb->byte2 & SVFY_BYTCHK)
9408			bytchk = 1;
9409		if (cdb->byte2 & SVFY_DPO)
9410			flags |= CTL_LLF_DPO;
9411		lba = scsi_8btou64(cdb->addr);
9412		num_blocks = scsi_4btoul(cdb->length);
9413		break;
9414	}
9415	default:
9416		/*
9417		 * We got a command we don't support.  This shouldn't
9418		 * happen, commands should be filtered out above us.
9419		 */
9420		ctl_set_invalid_opcode(ctsio);
9421		ctl_done((union ctl_io *)ctsio);
9422		return (CTL_RETVAL_COMPLETE);
9423	}
9424
9425	/*
9426	 * The first check is to make sure we're in bounds, the second
9427	 * check is to catch wrap-around problems.  If the lba + num blocks
9428	 * is less than the lba, then we've wrapped around and the block
9429	 * range is invalid anyway.
9430	 */
9431	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9432	 || ((lba + num_blocks) < lba)) {
9433		ctl_set_lba_out_of_range(ctsio);
9434		ctl_done((union ctl_io *)ctsio);
9435		return (CTL_RETVAL_COMPLETE);
9436	}
9437
9438	/*
9439	 * According to SBC-3, a transfer length of 0 is not an error.
9440	 */
9441	if (num_blocks == 0) {
9442		ctl_set_success(ctsio);
9443		ctl_done((union ctl_io *)ctsio);
9444		return (CTL_RETVAL_COMPLETE);
9445	}
9446
9447	lbalen = (struct ctl_lba_len_flags *)
9448	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9449	lbalen->lba = lba;
9450	lbalen->len = num_blocks;
9451	if (bytchk) {
9452		lbalen->flags = CTL_LLF_COMPARE | flags;
9453		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9454	} else {
9455		lbalen->flags = CTL_LLF_VERIFY | flags;
9456		ctsio->kern_total_len = 0;
9457	}
9458	ctsio->kern_rel_offset = 0;
9459
9460	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9461	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9462	return (retval);
9463}
9464
9465int
9466ctl_report_luns(struct ctl_scsiio *ctsio)
9467{
9468	struct scsi_report_luns *cdb;
9469	struct scsi_report_luns_data *lun_data;
9470	struct ctl_lun *lun, *request_lun;
9471	int num_luns, retval;
9472	uint32_t alloc_len, lun_datalen;
9473	int num_filled, well_known;
9474	uint32_t initidx, targ_lun_id, lun_id;
9475
9476	retval = CTL_RETVAL_COMPLETE;
9477	well_known = 0;
9478
9479	cdb = (struct scsi_report_luns *)ctsio->cdb;
9480
9481	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9482
9483	mtx_lock(&control_softc->ctl_lock);
9484	num_luns = control_softc->num_luns;
9485	mtx_unlock(&control_softc->ctl_lock);
9486
9487	switch (cdb->select_report) {
9488	case RPL_REPORT_DEFAULT:
9489	case RPL_REPORT_ALL:
9490		break;
9491	case RPL_REPORT_WELLKNOWN:
9492		well_known = 1;
9493		num_luns = 0;
9494		break;
9495	default:
9496		ctl_set_invalid_field(ctsio,
9497				      /*sks_valid*/ 1,
9498				      /*command*/ 1,
9499				      /*field*/ 2,
9500				      /*bit_valid*/ 0,
9501				      /*bit*/ 0);
9502		ctl_done((union ctl_io *)ctsio);
9503		return (retval);
9504		break; /* NOTREACHED */
9505	}
9506
9507	alloc_len = scsi_4btoul(cdb->length);
9508	/*
9509	 * The initiator has to allocate at least 16 bytes for this request,
9510	 * so he can at least get the header and the first LUN.  Otherwise
9511	 * we reject the request (per SPC-3 rev 14, section 6.21).
9512	 */
9513	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9514	    sizeof(struct scsi_report_luns_lundata))) {
9515		ctl_set_invalid_field(ctsio,
9516				      /*sks_valid*/ 1,
9517				      /*command*/ 1,
9518				      /*field*/ 6,
9519				      /*bit_valid*/ 0,
9520				      /*bit*/ 0);
9521		ctl_done((union ctl_io *)ctsio);
9522		return (retval);
9523	}
9524
9525	request_lun = (struct ctl_lun *)
9526		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9527
9528	lun_datalen = sizeof(*lun_data) +
9529		(num_luns * sizeof(struct scsi_report_luns_lundata));
9530
9531	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9532	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9533	ctsio->kern_sg_entries = 0;
9534
9535	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9536
9537	mtx_lock(&control_softc->ctl_lock);
9538	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9539		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9540		if (lun_id >= CTL_MAX_LUNS)
9541			continue;
9542		lun = control_softc->ctl_luns[lun_id];
9543		if (lun == NULL)
9544			continue;
9545
9546		if (targ_lun_id <= 0xff) {
9547			/*
9548			 * Peripheral addressing method, bus number 0.
9549			 */
9550			lun_data->luns[num_filled].lundata[0] =
9551				RPL_LUNDATA_ATYP_PERIPH;
9552			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9553			num_filled++;
9554		} else if (targ_lun_id <= 0x3fff) {
9555			/*
9556			 * Flat addressing method.
9557			 */
9558			lun_data->luns[num_filled].lundata[0] =
9559				RPL_LUNDATA_ATYP_FLAT |
9560				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9561#ifdef OLDCTLHEADERS
9562				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9563				(targ_lun_id & SRLD_BUS_LUN_MASK);
9564#endif
9565			lun_data->luns[num_filled].lundata[1] =
9566#ifdef OLDCTLHEADERS
9567				targ_lun_id >> SRLD_BUS_LUN_BITS;
9568#endif
9569				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9570			num_filled++;
9571		} else {
9572			printf("ctl_report_luns: bogus LUN number %jd, "
9573			       "skipping\n", (intmax_t)targ_lun_id);
9574		}
9575		/*
9576		 * According to SPC-3, rev 14 section 6.21:
9577		 *
9578		 * "The execution of a REPORT LUNS command to any valid and
9579		 * installed logical unit shall clear the REPORTED LUNS DATA
9580		 * HAS CHANGED unit attention condition for all logical
9581		 * units of that target with respect to the requesting
9582		 * initiator. A valid and installed logical unit is one
9583		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9584		 * INQUIRY data (see 6.4.2)."
9585		 *
9586		 * If request_lun is NULL, the LUN this report luns command
9587		 * was issued to is either disabled or doesn't exist. In that
9588		 * case, we shouldn't clear any pending lun change unit
9589		 * attention.
9590		 */
9591		if (request_lun != NULL) {
9592			mtx_lock(&lun->lun_lock);
9593			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9594			mtx_unlock(&lun->lun_lock);
9595		}
9596	}
9597	mtx_unlock(&control_softc->ctl_lock);
9598
9599	/*
9600	 * It's quite possible that we've returned fewer LUNs than we allocated
9601	 * space for.  Trim it.
9602	 */
9603	lun_datalen = sizeof(*lun_data) +
9604		(num_filled * sizeof(struct scsi_report_luns_lundata));
9605
9606	if (lun_datalen < alloc_len) {
9607		ctsio->residual = alloc_len - lun_datalen;
9608		ctsio->kern_data_len = lun_datalen;
9609		ctsio->kern_total_len = lun_datalen;
9610	} else {
9611		ctsio->residual = 0;
9612		ctsio->kern_data_len = alloc_len;
9613		ctsio->kern_total_len = alloc_len;
9614	}
9615	ctsio->kern_data_resid = 0;
9616	ctsio->kern_rel_offset = 0;
9617	ctsio->kern_sg_entries = 0;
9618
9619	/*
9620	 * We set this to the actual data length, regardless of how much
9621	 * space we actually have to return results.  If the user looks at
9622	 * this value, he'll know whether or not he allocated enough space
9623	 * and reissue the command if necessary.  We don't support well
9624	 * known logical units, so if the user asks for that, return none.
9625	 */
9626	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9627
9628	/*
9629	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9630	 * this request.
9631	 */
9632	ctsio->scsi_status = SCSI_STATUS_OK;
9633
9634	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9635	ctsio->be_move_done = ctl_config_move_done;
9636	ctl_datamove((union ctl_io *)ctsio);
9637
9638	return (retval);
9639}
9640
9641int
9642ctl_request_sense(struct ctl_scsiio *ctsio)
9643{
9644	struct scsi_request_sense *cdb;
9645	struct scsi_sense_data *sense_ptr;
9646	struct ctl_lun *lun;
9647	uint32_t initidx;
9648	int have_error;
9649	scsi_sense_data_type sense_format;
9650
9651	cdb = (struct scsi_request_sense *)ctsio->cdb;
9652
9653	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9654
9655	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9656
9657	/*
9658	 * Determine which sense format the user wants.
9659	 */
9660	if (cdb->byte2 & SRS_DESC)
9661		sense_format = SSD_TYPE_DESC;
9662	else
9663		sense_format = SSD_TYPE_FIXED;
9664
9665	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9666	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9667	ctsio->kern_sg_entries = 0;
9668
9669	/*
9670	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9671	 * larger than the largest allowed value for the length field in the
9672	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9673	 */
9674	ctsio->residual = 0;
9675	ctsio->kern_data_len = cdb->length;
9676	ctsio->kern_total_len = cdb->length;
9677
9678	ctsio->kern_data_resid = 0;
9679	ctsio->kern_rel_offset = 0;
9680	ctsio->kern_sg_entries = 0;
9681
9682	/*
9683	 * If we don't have a LUN, we don't have any pending sense.
9684	 */
9685	if (lun == NULL)
9686		goto no_sense;
9687
9688	have_error = 0;
9689	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9690	/*
9691	 * Check for pending sense, and then for pending unit attentions.
9692	 * Pending sense gets returned first, then pending unit attentions.
9693	 */
9694	mtx_lock(&lun->lun_lock);
9695#ifdef CTL_WITH_CA
9696	if (ctl_is_set(lun->have_ca, initidx)) {
9697		scsi_sense_data_type stored_format;
9698
9699		/*
9700		 * Check to see which sense format was used for the stored
9701		 * sense data.
9702		 */
9703		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9704
9705		/*
9706		 * If the user requested a different sense format than the
9707		 * one we stored, then we need to convert it to the other
9708		 * format.  If we're going from descriptor to fixed format
9709		 * sense data, we may lose things in translation, depending
9710		 * on what options were used.
9711		 *
9712		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9713		 * for some reason we'll just copy it out as-is.
9714		 */
9715		if ((stored_format == SSD_TYPE_FIXED)
9716		 && (sense_format == SSD_TYPE_DESC))
9717			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9718			    &lun->pending_sense[initidx],
9719			    (struct scsi_sense_data_desc *)sense_ptr);
9720		else if ((stored_format == SSD_TYPE_DESC)
9721		      && (sense_format == SSD_TYPE_FIXED))
9722			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9723			    &lun->pending_sense[initidx],
9724			    (struct scsi_sense_data_fixed *)sense_ptr);
9725		else
9726			memcpy(sense_ptr, &lun->pending_sense[initidx],
9727			       ctl_min(sizeof(*sense_ptr),
9728			       sizeof(lun->pending_sense[initidx])));
9729
9730		ctl_clear_mask(lun->have_ca, initidx);
9731		have_error = 1;
9732	} else
9733#endif
9734	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9735		ctl_ua_type ua_type;
9736
9737		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9738				       sense_ptr, sense_format);
9739		if (ua_type != CTL_UA_NONE)
9740			have_error = 1;
9741	}
9742	mtx_unlock(&lun->lun_lock);
9743
9744	/*
9745	 * We already have a pending error, return it.
9746	 */
9747	if (have_error != 0) {
9748		/*
9749		 * We report the SCSI status as OK, since the status of the
9750		 * request sense command itself is OK.
9751		 */
9752		ctsio->scsi_status = SCSI_STATUS_OK;
9753
9754		/*
9755		 * We report 0 for the sense length, because we aren't doing
9756		 * autosense in this case.  We're reporting sense as
9757		 * parameter data.
9758		 */
9759		ctsio->sense_len = 0;
9760		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9761		ctsio->be_move_done = ctl_config_move_done;
9762		ctl_datamove((union ctl_io *)ctsio);
9763
9764		return (CTL_RETVAL_COMPLETE);
9765	}
9766
9767no_sense:
9768
9769	/*
9770	 * No sense information to report, so we report that everything is
9771	 * okay.
9772	 */
9773	ctl_set_sense_data(sense_ptr,
9774			   lun,
9775			   sense_format,
9776			   /*current_error*/ 1,
9777			   /*sense_key*/ SSD_KEY_NO_SENSE,
9778			   /*asc*/ 0x00,
9779			   /*ascq*/ 0x00,
9780			   SSD_ELEM_NONE);
9781
9782	ctsio->scsi_status = SCSI_STATUS_OK;
9783
9784	/*
9785	 * We report 0 for the sense length, because we aren't doing
9786	 * autosense in this case.  We're reporting sense as parameter data.
9787	 */
9788	ctsio->sense_len = 0;
9789	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9790	ctsio->be_move_done = ctl_config_move_done;
9791	ctl_datamove((union ctl_io *)ctsio);
9792
9793	return (CTL_RETVAL_COMPLETE);
9794}
9795
9796int
9797ctl_tur(struct ctl_scsiio *ctsio)
9798{
9799	struct ctl_lun *lun;
9800
9801	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9802
9803	CTL_DEBUG_PRINT(("ctl_tur\n"));
9804
9805	if (lun == NULL)
9806		return (EINVAL);
9807
9808	ctsio->scsi_status = SCSI_STATUS_OK;
9809	ctsio->io_hdr.status = CTL_SUCCESS;
9810
9811	ctl_done((union ctl_io *)ctsio);
9812
9813	return (CTL_RETVAL_COMPLETE);
9814}
9815
9816#ifdef notyet
9817static int
9818ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9819{
9820
9821}
9822#endif
9823
9824static int
9825ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9826{
9827	struct scsi_vpd_supported_pages *pages;
9828	int sup_page_size;
9829	struct ctl_lun *lun;
9830
9831	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9832
9833	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9834	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9835	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9836	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9837	ctsio->kern_sg_entries = 0;
9838
9839	if (sup_page_size < alloc_len) {
9840		ctsio->residual = alloc_len - sup_page_size;
9841		ctsio->kern_data_len = sup_page_size;
9842		ctsio->kern_total_len = sup_page_size;
9843	} else {
9844		ctsio->residual = 0;
9845		ctsio->kern_data_len = alloc_len;
9846		ctsio->kern_total_len = alloc_len;
9847	}
9848	ctsio->kern_data_resid = 0;
9849	ctsio->kern_rel_offset = 0;
9850	ctsio->kern_sg_entries = 0;
9851
9852	/*
9853	 * The control device is always connected.  The disk device, on the
9854	 * other hand, may not be online all the time.  Need to change this
9855	 * to figure out whether the disk device is actually online or not.
9856	 */
9857	if (lun != NULL)
9858		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9859				lun->be_lun->lun_type;
9860	else
9861		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9862
9863	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9864	/* Supported VPD pages */
9865	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9866	/* Serial Number */
9867	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9868	/* Device Identification */
9869	pages->page_list[2] = SVPD_DEVICE_ID;
9870	/* Extended INQUIRY Data */
9871	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9872	/* Mode Page Policy */
9873	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9874	/* SCSI Ports */
9875	pages->page_list[5] = SVPD_SCSI_PORTS;
9876	/* Third-party Copy */
9877	pages->page_list[6] = SVPD_SCSI_TPC;
9878	/* Block limits */
9879	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9880	/* Block Device Characteristics */
9881	pages->page_list[8] = SVPD_BDC;
9882	/* Logical Block Provisioning */
9883	pages->page_list[9] = SVPD_LBP;
9884
9885	ctsio->scsi_status = SCSI_STATUS_OK;
9886
9887	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9888	ctsio->be_move_done = ctl_config_move_done;
9889	ctl_datamove((union ctl_io *)ctsio);
9890
9891	return (CTL_RETVAL_COMPLETE);
9892}
9893
9894static int
9895ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9896{
9897	struct scsi_vpd_unit_serial_number *sn_ptr;
9898	struct ctl_lun *lun;
9899
9900	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9901
9902	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9903	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9904	ctsio->kern_sg_entries = 0;
9905
9906	if (sizeof(*sn_ptr) < alloc_len) {
9907		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9908		ctsio->kern_data_len = sizeof(*sn_ptr);
9909		ctsio->kern_total_len = sizeof(*sn_ptr);
9910	} else {
9911		ctsio->residual = 0;
9912		ctsio->kern_data_len = alloc_len;
9913		ctsio->kern_total_len = alloc_len;
9914	}
9915	ctsio->kern_data_resid = 0;
9916	ctsio->kern_rel_offset = 0;
9917	ctsio->kern_sg_entries = 0;
9918
9919	/*
9920	 * The control device is always connected.  The disk device, on the
9921	 * other hand, may not be online all the time.  Need to change this
9922	 * to figure out whether the disk device is actually online or not.
9923	 */
9924	if (lun != NULL)
9925		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9926				  lun->be_lun->lun_type;
9927	else
9928		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9929
9930	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9931	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9932	/*
9933	 * If we don't have a LUN, we just leave the serial number as
9934	 * all spaces.
9935	 */
9936	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9937	if (lun != NULL) {
9938		strncpy((char *)sn_ptr->serial_num,
9939			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9940	}
9941	ctsio->scsi_status = SCSI_STATUS_OK;
9942
9943	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9944	ctsio->be_move_done = ctl_config_move_done;
9945	ctl_datamove((union ctl_io *)ctsio);
9946
9947	return (CTL_RETVAL_COMPLETE);
9948}
9949
9950
9951static int
9952ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9953{
9954	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9955	struct ctl_lun *lun;
9956	int data_len;
9957
9958	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9959
9960	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9961	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9962
9963	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9964	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9965	ctsio->kern_sg_entries = 0;
9966
9967	if (data_len < alloc_len) {
9968		ctsio->residual = alloc_len - data_len;
9969		ctsio->kern_data_len = data_len;
9970		ctsio->kern_total_len = data_len;
9971	} else {
9972		ctsio->residual = 0;
9973		ctsio->kern_data_len = alloc_len;
9974		ctsio->kern_total_len = alloc_len;
9975	}
9976	ctsio->kern_data_resid = 0;
9977	ctsio->kern_rel_offset = 0;
9978	ctsio->kern_sg_entries = 0;
9979
9980	/*
9981	 * The control device is always connected.  The disk device, on the
9982	 * other hand, may not be online all the time.
9983	 */
9984	if (lun != NULL)
9985		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9986				     lun->be_lun->lun_type;
9987	else
9988		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9989	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9990	eid_ptr->page_length = data_len - 4;
9991	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9992	eid_ptr->flags3 = SVPD_EID_V_SUP;
9993
9994	ctsio->scsi_status = SCSI_STATUS_OK;
9995	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9996	ctsio->be_move_done = ctl_config_move_done;
9997	ctl_datamove((union ctl_io *)ctsio);
9998
9999	return (CTL_RETVAL_COMPLETE);
10000}
10001
10002static int
10003ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10004{
10005	struct scsi_vpd_mode_page_policy *mpp_ptr;
10006	struct ctl_lun *lun;
10007	int data_len;
10008
10009	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10010
10011	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10012	    sizeof(struct scsi_vpd_mode_page_policy_descr);
10013
10014	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10015	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10016	ctsio->kern_sg_entries = 0;
10017
10018	if (data_len < alloc_len) {
10019		ctsio->residual = alloc_len - data_len;
10020		ctsio->kern_data_len = data_len;
10021		ctsio->kern_total_len = data_len;
10022	} else {
10023		ctsio->residual = 0;
10024		ctsio->kern_data_len = alloc_len;
10025		ctsio->kern_total_len = alloc_len;
10026	}
10027	ctsio->kern_data_resid = 0;
10028	ctsio->kern_rel_offset = 0;
10029	ctsio->kern_sg_entries = 0;
10030
10031	/*
10032	 * The control device is always connected.  The disk device, on the
10033	 * other hand, may not be online all the time.
10034	 */
10035	if (lun != NULL)
10036		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10037				     lun->be_lun->lun_type;
10038	else
10039		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10040	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10041	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10042	mpp_ptr->descr[0].page_code = 0x3f;
10043	mpp_ptr->descr[0].subpage_code = 0xff;
10044	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10045
10046	ctsio->scsi_status = SCSI_STATUS_OK;
10047	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10048	ctsio->be_move_done = ctl_config_move_done;
10049	ctl_datamove((union ctl_io *)ctsio);
10050
10051	return (CTL_RETVAL_COMPLETE);
10052}
10053
10054static int
10055ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10056{
10057	struct scsi_vpd_device_id *devid_ptr;
10058	struct scsi_vpd_id_descriptor *desc;
10059	struct ctl_softc *ctl_softc;
10060	struct ctl_lun *lun;
10061	struct ctl_port *port;
10062	int data_len;
10063	uint8_t proto;
10064
10065	ctl_softc = control_softc;
10066
10067	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10068	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10069
10070	data_len = sizeof(struct scsi_vpd_device_id) +
10071	    sizeof(struct scsi_vpd_id_descriptor) +
10072		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10073	    sizeof(struct scsi_vpd_id_descriptor) +
10074		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10075	if (lun && lun->lun_devid)
10076		data_len += lun->lun_devid->len;
10077	if (port->port_devid)
10078		data_len += port->port_devid->len;
10079	if (port->target_devid)
10080		data_len += port->target_devid->len;
10081
10082	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10083	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10084	ctsio->kern_sg_entries = 0;
10085
10086	if (data_len < alloc_len) {
10087		ctsio->residual = alloc_len - data_len;
10088		ctsio->kern_data_len = data_len;
10089		ctsio->kern_total_len = data_len;
10090	} else {
10091		ctsio->residual = 0;
10092		ctsio->kern_data_len = alloc_len;
10093		ctsio->kern_total_len = alloc_len;
10094	}
10095	ctsio->kern_data_resid = 0;
10096	ctsio->kern_rel_offset = 0;
10097	ctsio->kern_sg_entries = 0;
10098
10099	/*
10100	 * The control device is always connected.  The disk device, on the
10101	 * other hand, may not be online all the time.
10102	 */
10103	if (lun != NULL)
10104		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10105				     lun->be_lun->lun_type;
10106	else
10107		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10108	devid_ptr->page_code = SVPD_DEVICE_ID;
10109	scsi_ulto2b(data_len - 4, devid_ptr->length);
10110
10111	if (port->port_type == CTL_PORT_FC)
10112		proto = SCSI_PROTO_FC << 4;
10113	else if (port->port_type == CTL_PORT_ISCSI)
10114		proto = SCSI_PROTO_ISCSI << 4;
10115	else
10116		proto = SCSI_PROTO_SPI << 4;
10117	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10118
10119	/*
10120	 * We're using a LUN association here.  i.e., this device ID is a
10121	 * per-LUN identifier.
10122	 */
10123	if (lun && lun->lun_devid) {
10124		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10125		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10126		    lun->lun_devid->len);
10127	}
10128
10129	/*
10130	 * This is for the WWPN which is a port association.
10131	 */
10132	if (port->port_devid) {
10133		memcpy(desc, port->port_devid->data, port->port_devid->len);
10134		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10135		    port->port_devid->len);
10136	}
10137
10138	/*
10139	 * This is for the Relative Target Port(type 4h) identifier
10140	 */
10141	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10142	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10143	    SVPD_ID_TYPE_RELTARG;
10144	desc->length = 4;
10145	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10146	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10147	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10148
10149	/*
10150	 * This is for the Target Port Group(type 5h) identifier
10151	 */
10152	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10153	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10154	    SVPD_ID_TYPE_TPORTGRP;
10155	desc->length = 4;
10156	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10157	    &desc->identifier[2]);
10158	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10159	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10160
10161	/*
10162	 * This is for the Target identifier
10163	 */
10164	if (port->target_devid) {
10165		memcpy(desc, port->target_devid->data, port->target_devid->len);
10166	}
10167
10168	ctsio->scsi_status = SCSI_STATUS_OK;
10169	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10170	ctsio->be_move_done = ctl_config_move_done;
10171	ctl_datamove((union ctl_io *)ctsio);
10172
10173	return (CTL_RETVAL_COMPLETE);
10174}
10175
10176static int
10177ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10178{
10179	struct ctl_softc *softc = control_softc;
10180	struct scsi_vpd_scsi_ports *sp;
10181	struct scsi_vpd_port_designation *pd;
10182	struct scsi_vpd_port_designation_cont *pdc;
10183	struct ctl_lun *lun;
10184	struct ctl_port *port;
10185	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10186	int num_target_port_groups, single;
10187
10188	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10189
10190	single = ctl_is_single;
10191	if (single)
10192		num_target_port_groups = 1;
10193	else
10194		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10195	num_target_ports = 0;
10196	iid_len = 0;
10197	id_len = 0;
10198	mtx_lock(&softc->ctl_lock);
10199	STAILQ_FOREACH(port, &softc->port_list, links) {
10200		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10201			continue;
10202		if (lun != NULL &&
10203		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10204		    CTL_MAX_LUNS)
10205			continue;
10206		num_target_ports++;
10207		if (port->init_devid)
10208			iid_len += port->init_devid->len;
10209		if (port->port_devid)
10210			id_len += port->port_devid->len;
10211	}
10212	mtx_unlock(&softc->ctl_lock);
10213
10214	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10215	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10216	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10217	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10218	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10219	ctsio->kern_sg_entries = 0;
10220
10221	if (data_len < alloc_len) {
10222		ctsio->residual = alloc_len - data_len;
10223		ctsio->kern_data_len = data_len;
10224		ctsio->kern_total_len = data_len;
10225	} else {
10226		ctsio->residual = 0;
10227		ctsio->kern_data_len = alloc_len;
10228		ctsio->kern_total_len = alloc_len;
10229	}
10230	ctsio->kern_data_resid = 0;
10231	ctsio->kern_rel_offset = 0;
10232	ctsio->kern_sg_entries = 0;
10233
10234	/*
10235	 * The control device is always connected.  The disk device, on the
10236	 * other hand, may not be online all the time.  Need to change this
10237	 * to figure out whether the disk device is actually online or not.
10238	 */
10239	if (lun != NULL)
10240		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10241				  lun->be_lun->lun_type;
10242	else
10243		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10244
10245	sp->page_code = SVPD_SCSI_PORTS;
10246	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10247	    sp->page_length);
10248	pd = &sp->design[0];
10249
10250	mtx_lock(&softc->ctl_lock);
10251	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10252		pg = 0;
10253	else
10254		pg = 1;
10255	for (g = 0; g < num_target_port_groups; g++) {
10256		STAILQ_FOREACH(port, &softc->port_list, links) {
10257			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10258				continue;
10259			if (lun != NULL &&
10260			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10261			    CTL_MAX_LUNS)
10262				continue;
10263			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10264			scsi_ulto2b(p, pd->relative_port_id);
10265			if (port->init_devid && g == pg) {
10266				iid_len = port->init_devid->len;
10267				memcpy(pd->initiator_transportid,
10268				    port->init_devid->data, port->init_devid->len);
10269			} else
10270				iid_len = 0;
10271			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10272			pdc = (struct scsi_vpd_port_designation_cont *)
10273			    (&pd->initiator_transportid[iid_len]);
10274			if (port->port_devid && g == pg) {
10275				id_len = port->port_devid->len;
10276				memcpy(pdc->target_port_descriptors,
10277				    port->port_devid->data, port->port_devid->len);
10278			} else
10279				id_len = 0;
10280			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10281			pd = (struct scsi_vpd_port_designation *)
10282			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10283		}
10284	}
10285	mtx_unlock(&softc->ctl_lock);
10286
10287	ctsio->scsi_status = SCSI_STATUS_OK;
10288	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10289	ctsio->be_move_done = ctl_config_move_done;
10290	ctl_datamove((union ctl_io *)ctsio);
10291
10292	return (CTL_RETVAL_COMPLETE);
10293}
10294
10295static int
10296ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10297{
10298	struct scsi_vpd_block_limits *bl_ptr;
10299	struct ctl_lun *lun;
10300	int bs;
10301
10302	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10303
10304	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10305	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10306	ctsio->kern_sg_entries = 0;
10307
10308	if (sizeof(*bl_ptr) < alloc_len) {
10309		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10310		ctsio->kern_data_len = sizeof(*bl_ptr);
10311		ctsio->kern_total_len = sizeof(*bl_ptr);
10312	} else {
10313		ctsio->residual = 0;
10314		ctsio->kern_data_len = alloc_len;
10315		ctsio->kern_total_len = alloc_len;
10316	}
10317	ctsio->kern_data_resid = 0;
10318	ctsio->kern_rel_offset = 0;
10319	ctsio->kern_sg_entries = 0;
10320
10321	/*
10322	 * The control device is always connected.  The disk device, on the
10323	 * other hand, may not be online all the time.  Need to change this
10324	 * to figure out whether the disk device is actually online or not.
10325	 */
10326	if (lun != NULL)
10327		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10328				  lun->be_lun->lun_type;
10329	else
10330		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10331
10332	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10333	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10334	bl_ptr->max_cmp_write_len = 0xff;
10335	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10336	if (lun != NULL) {
10337		bs = lun->be_lun->blocksize;
10338		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10339		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10340			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10341			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10342			if (lun->be_lun->pblockexp != 0) {
10343				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10344				    bl_ptr->opt_unmap_grain);
10345				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10346				    bl_ptr->unmap_grain_align);
10347			}
10348		}
10349	}
10350	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10351
10352	ctsio->scsi_status = SCSI_STATUS_OK;
10353	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10354	ctsio->be_move_done = ctl_config_move_done;
10355	ctl_datamove((union ctl_io *)ctsio);
10356
10357	return (CTL_RETVAL_COMPLETE);
10358}
10359
10360static int
10361ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10362{
10363	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10364	struct ctl_lun *lun;
10365
10366	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10367
10368	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10369	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10370	ctsio->kern_sg_entries = 0;
10371
10372	if (sizeof(*bdc_ptr) < alloc_len) {
10373		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10374		ctsio->kern_data_len = sizeof(*bdc_ptr);
10375		ctsio->kern_total_len = sizeof(*bdc_ptr);
10376	} else {
10377		ctsio->residual = 0;
10378		ctsio->kern_data_len = alloc_len;
10379		ctsio->kern_total_len = alloc_len;
10380	}
10381	ctsio->kern_data_resid = 0;
10382	ctsio->kern_rel_offset = 0;
10383	ctsio->kern_sg_entries = 0;
10384
10385	/*
10386	 * The control device is always connected.  The disk device, on the
10387	 * other hand, may not be online all the time.  Need to change this
10388	 * to figure out whether the disk device is actually online or not.
10389	 */
10390	if (lun != NULL)
10391		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10392				  lun->be_lun->lun_type;
10393	else
10394		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10395	bdc_ptr->page_code = SVPD_BDC;
10396	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10397	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10398	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10399
10400	ctsio->scsi_status = SCSI_STATUS_OK;
10401	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10402	ctsio->be_move_done = ctl_config_move_done;
10403	ctl_datamove((union ctl_io *)ctsio);
10404
10405	return (CTL_RETVAL_COMPLETE);
10406}
10407
10408static int
10409ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10410{
10411	struct scsi_vpd_logical_block_prov *lbp_ptr;
10412	struct ctl_lun *lun;
10413
10414	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10415
10416	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10417	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10418	ctsio->kern_sg_entries = 0;
10419
10420	if (sizeof(*lbp_ptr) < alloc_len) {
10421		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10422		ctsio->kern_data_len = sizeof(*lbp_ptr);
10423		ctsio->kern_total_len = sizeof(*lbp_ptr);
10424	} else {
10425		ctsio->residual = 0;
10426		ctsio->kern_data_len = alloc_len;
10427		ctsio->kern_total_len = alloc_len;
10428	}
10429	ctsio->kern_data_resid = 0;
10430	ctsio->kern_rel_offset = 0;
10431	ctsio->kern_sg_entries = 0;
10432
10433	/*
10434	 * The control device is always connected.  The disk device, on the
10435	 * other hand, may not be online all the time.  Need to change this
10436	 * to figure out whether the disk device is actually online or not.
10437	 */
10438	if (lun != NULL)
10439		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10440				  lun->be_lun->lun_type;
10441	else
10442		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10443
10444	lbp_ptr->page_code = SVPD_LBP;
10445	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10446	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10447		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10448		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10449		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10450	}
10451
10452	ctsio->scsi_status = SCSI_STATUS_OK;
10453	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10454	ctsio->be_move_done = ctl_config_move_done;
10455	ctl_datamove((union ctl_io *)ctsio);
10456
10457	return (CTL_RETVAL_COMPLETE);
10458}
10459
10460static int
10461ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10462{
10463	struct scsi_inquiry *cdb;
10464	struct ctl_lun *lun;
10465	int alloc_len, retval;
10466
10467	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10468	cdb = (struct scsi_inquiry *)ctsio->cdb;
10469
10470	retval = CTL_RETVAL_COMPLETE;
10471
10472	alloc_len = scsi_2btoul(cdb->length);
10473
10474	switch (cdb->page_code) {
10475	case SVPD_SUPPORTED_PAGES:
10476		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10477		break;
10478	case SVPD_UNIT_SERIAL_NUMBER:
10479		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10480		break;
10481	case SVPD_DEVICE_ID:
10482		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10483		break;
10484	case SVPD_EXTENDED_INQUIRY_DATA:
10485		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10486		break;
10487	case SVPD_MODE_PAGE_POLICY:
10488		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10489		break;
10490	case SVPD_SCSI_PORTS:
10491		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10492		break;
10493	case SVPD_SCSI_TPC:
10494		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10495		break;
10496	case SVPD_BLOCK_LIMITS:
10497		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10498		break;
10499	case SVPD_BDC:
10500		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10501		break;
10502	case SVPD_LBP:
10503		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10504		break;
10505	default:
10506		ctl_set_invalid_field(ctsio,
10507				      /*sks_valid*/ 1,
10508				      /*command*/ 1,
10509				      /*field*/ 2,
10510				      /*bit_valid*/ 0,
10511				      /*bit*/ 0);
10512		ctl_done((union ctl_io *)ctsio);
10513		retval = CTL_RETVAL_COMPLETE;
10514		break;
10515	}
10516
10517	return (retval);
10518}
10519
10520static int
10521ctl_inquiry_std(struct ctl_scsiio *ctsio)
10522{
10523	struct scsi_inquiry_data *inq_ptr;
10524	struct scsi_inquiry *cdb;
10525	struct ctl_softc *ctl_softc;
10526	struct ctl_lun *lun;
10527	char *val;
10528	uint32_t alloc_len;
10529	ctl_port_type port_type;
10530
10531	ctl_softc = control_softc;
10532
10533	/*
10534	 * Figure out whether we're talking to a Fibre Channel port or not.
10535	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10536	 * SCSI front ends.
10537	 */
10538	port_type = ctl_softc->ctl_ports[
10539	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10540	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10541		port_type = CTL_PORT_SCSI;
10542
10543	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10544	cdb = (struct scsi_inquiry *)ctsio->cdb;
10545	alloc_len = scsi_2btoul(cdb->length);
10546
10547	/*
10548	 * We malloc the full inquiry data size here and fill it
10549	 * in.  If the user only asks for less, we'll give him
10550	 * that much.
10551	 */
10552	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10553	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10554	ctsio->kern_sg_entries = 0;
10555	ctsio->kern_data_resid = 0;
10556	ctsio->kern_rel_offset = 0;
10557
10558	if (sizeof(*inq_ptr) < alloc_len) {
10559		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10560		ctsio->kern_data_len = sizeof(*inq_ptr);
10561		ctsio->kern_total_len = sizeof(*inq_ptr);
10562	} else {
10563		ctsio->residual = 0;
10564		ctsio->kern_data_len = alloc_len;
10565		ctsio->kern_total_len = alloc_len;
10566	}
10567
10568	/*
10569	 * If we have a LUN configured, report it as connected.  Otherwise,
10570	 * report that it is offline or no device is supported, depending
10571	 * on the value of inquiry_pq_no_lun.
10572	 *
10573	 * According to the spec (SPC-4 r34), the peripheral qualifier
10574	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10575	 *
10576	 * "A peripheral device having the specified peripheral device type
10577	 * is not connected to this logical unit. However, the device
10578	 * server is capable of supporting the specified peripheral device
10579	 * type on this logical unit."
10580	 *
10581	 * According to the same spec, the peripheral qualifier
10582	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10583	 *
10584	 * "The device server is not capable of supporting a peripheral
10585	 * device on this logical unit. For this peripheral qualifier the
10586	 * peripheral device type shall be set to 1Fh. All other peripheral
10587	 * device type values are reserved for this peripheral qualifier."
10588	 *
10589	 * Given the text, it would seem that we probably want to report that
10590	 * the LUN is offline here.  There is no LUN connected, but we can
10591	 * support a LUN at the given LUN number.
10592	 *
10593	 * In the real world, though, it sounds like things are a little
10594	 * different:
10595	 *
10596	 * - Linux, when presented with a LUN with the offline peripheral
10597	 *   qualifier, will create an sg driver instance for it.  So when
10598	 *   you attach it to CTL, you wind up with a ton of sg driver
10599	 *   instances.  (One for every LUN that Linux bothered to probe.)
10600	 *   Linux does this despite the fact that it issues a REPORT LUNs
10601	 *   to LUN 0 to get the inventory of supported LUNs.
10602	 *
10603	 * - There is other anecdotal evidence (from Emulex folks) about
10604	 *   arrays that use the offline peripheral qualifier for LUNs that
10605	 *   are on the "passive" path in an active/passive array.
10606	 *
10607	 * So the solution is provide a hopefully reasonable default
10608	 * (return bad/no LUN) and allow the user to change the behavior
10609	 * with a tunable/sysctl variable.
10610	 */
10611	if (lun != NULL)
10612		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10613				  lun->be_lun->lun_type;
10614	else if (ctl_softc->inquiry_pq_no_lun == 0)
10615		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10616	else
10617		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10618
10619	/* RMB in byte 2 is 0 */
10620	inq_ptr->version = SCSI_REV_SPC4;
10621
10622	/*
10623	 * According to SAM-3, even if a device only supports a single
10624	 * level of LUN addressing, it should still set the HISUP bit:
10625	 *
10626	 * 4.9.1 Logical unit numbers overview
10627	 *
10628	 * All logical unit number formats described in this standard are
10629	 * hierarchical in structure even when only a single level in that
10630	 * hierarchy is used. The HISUP bit shall be set to one in the
10631	 * standard INQUIRY data (see SPC-2) when any logical unit number
10632	 * format described in this standard is used.  Non-hierarchical
10633	 * formats are outside the scope of this standard.
10634	 *
10635	 * Therefore we set the HiSup bit here.
10636	 *
10637	 * The reponse format is 2, per SPC-3.
10638	 */
10639	inq_ptr->response_format = SID_HiSup | 2;
10640
10641	inq_ptr->additional_length =
10642	    offsetof(struct scsi_inquiry_data, vendor_specific1) -
10643	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10644	CTL_DEBUG_PRINT(("additional_length = %d\n",
10645			 inq_ptr->additional_length));
10646
10647	inq_ptr->spc3_flags = SPC3_SID_3PC;
10648	if (!ctl_is_single)
10649		inq_ptr->spc3_flags |= SPC3_SID_TPGS_IMPLICIT;
10650	/* 16 bit addressing */
10651	if (port_type == CTL_PORT_SCSI)
10652		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10653	/* XXX set the SID_MultiP bit here if we're actually going to
10654	   respond on multiple ports */
10655	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10656
10657	/* 16 bit data bus, synchronous transfers */
10658	if (port_type == CTL_PORT_SCSI)
10659		inq_ptr->flags = SID_WBus16 | SID_Sync;
10660	/*
10661	 * XXX KDM do we want to support tagged queueing on the control
10662	 * device at all?
10663	 */
10664	if ((lun == NULL)
10665	 || (lun->be_lun->lun_type != T_PROCESSOR))
10666		inq_ptr->flags |= SID_CmdQue;
10667	/*
10668	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10669	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10670	 * name and 4 bytes for the revision.
10671	 */
10672	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10673	    "vendor")) == NULL) {
10674		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10675	} else {
10676		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10677		strncpy(inq_ptr->vendor, val,
10678		    min(sizeof(inq_ptr->vendor), strlen(val)));
10679	}
10680	if (lun == NULL) {
10681		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10682		    sizeof(inq_ptr->product));
10683	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10684		switch (lun->be_lun->lun_type) {
10685		case T_DIRECT:
10686			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10687			    sizeof(inq_ptr->product));
10688			break;
10689		case T_PROCESSOR:
10690			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10691			    sizeof(inq_ptr->product));
10692			break;
10693		default:
10694			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10695			    sizeof(inq_ptr->product));
10696			break;
10697		}
10698	} else {
10699		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10700		strncpy(inq_ptr->product, val,
10701		    min(sizeof(inq_ptr->product), strlen(val)));
10702	}
10703
10704	/*
10705	 * XXX make this a macro somewhere so it automatically gets
10706	 * incremented when we make changes.
10707	 */
10708	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10709	    "revision")) == NULL) {
10710		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10711	} else {
10712		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10713		strncpy(inq_ptr->revision, val,
10714		    min(sizeof(inq_ptr->revision), strlen(val)));
10715	}
10716
10717	/*
10718	 * For parallel SCSI, we support double transition and single
10719	 * transition clocking.  We also support QAS (Quick Arbitration
10720	 * and Selection) and Information Unit transfers on both the
10721	 * control and array devices.
10722	 */
10723	if (port_type == CTL_PORT_SCSI)
10724		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10725				    SID_SPI_IUS;
10726
10727	/* SAM-5 (no version claimed) */
10728	scsi_ulto2b(0x00A0, inq_ptr->version1);
10729	/* SPC-4 (no version claimed) */
10730	scsi_ulto2b(0x0460, inq_ptr->version2);
10731	if (port_type == CTL_PORT_FC) {
10732		/* FCP-2 ANSI INCITS.350:2003 */
10733		scsi_ulto2b(0x0917, inq_ptr->version3);
10734	} else if (port_type == CTL_PORT_SCSI) {
10735		/* SPI-4 ANSI INCITS.362:200x */
10736		scsi_ulto2b(0x0B56, inq_ptr->version3);
10737	} else if (port_type == CTL_PORT_ISCSI) {
10738		/* iSCSI (no version claimed) */
10739		scsi_ulto2b(0x0960, inq_ptr->version3);
10740	} else if (port_type == CTL_PORT_SAS) {
10741		/* SAS (no version claimed) */
10742		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10743	}
10744
10745	if (lun == NULL) {
10746		/* SBC-3 (no version claimed) */
10747		scsi_ulto2b(0x04C0, inq_ptr->version4);
10748	} else {
10749		switch (lun->be_lun->lun_type) {
10750		case T_DIRECT:
10751			/* SBC-3 (no version claimed) */
10752			scsi_ulto2b(0x04C0, inq_ptr->version4);
10753			break;
10754		case T_PROCESSOR:
10755		default:
10756			break;
10757		}
10758	}
10759
10760	ctsio->scsi_status = SCSI_STATUS_OK;
10761	if (ctsio->kern_data_len > 0) {
10762		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10763		ctsio->be_move_done = ctl_config_move_done;
10764		ctl_datamove((union ctl_io *)ctsio);
10765	} else {
10766		ctsio->io_hdr.status = CTL_SUCCESS;
10767		ctl_done((union ctl_io *)ctsio);
10768	}
10769
10770	return (CTL_RETVAL_COMPLETE);
10771}
10772
10773int
10774ctl_inquiry(struct ctl_scsiio *ctsio)
10775{
10776	struct scsi_inquiry *cdb;
10777	int retval;
10778
10779	cdb = (struct scsi_inquiry *)ctsio->cdb;
10780
10781	retval = 0;
10782
10783	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10784
10785	/*
10786	 * Right now, we don't support the CmdDt inquiry information.
10787	 * This would be nice to support in the future.  When we do
10788	 * support it, we should change this test so that it checks to make
10789	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10790	 */
10791#ifdef notyet
10792	if (((cdb->byte2 & SI_EVPD)
10793	 && (cdb->byte2 & SI_CMDDT)))
10794#endif
10795	if (cdb->byte2 & SI_CMDDT) {
10796		/*
10797		 * Point to the SI_CMDDT bit.  We might change this
10798		 * when we support SI_CMDDT, but since both bits would be
10799		 * "wrong", this should probably just stay as-is then.
10800		 */
10801		ctl_set_invalid_field(ctsio,
10802				      /*sks_valid*/ 1,
10803				      /*command*/ 1,
10804				      /*field*/ 1,
10805				      /*bit_valid*/ 1,
10806				      /*bit*/ 1);
10807		ctl_done((union ctl_io *)ctsio);
10808		return (CTL_RETVAL_COMPLETE);
10809	}
10810	if (cdb->byte2 & SI_EVPD)
10811		retval = ctl_inquiry_evpd(ctsio);
10812#ifdef notyet
10813	else if (cdb->byte2 & SI_CMDDT)
10814		retval = ctl_inquiry_cmddt(ctsio);
10815#endif
10816	else
10817		retval = ctl_inquiry_std(ctsio);
10818
10819	return (retval);
10820}
10821
10822/*
10823 * For known CDB types, parse the LBA and length.
10824 */
10825static int
10826ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10827{
10828	if (io->io_hdr.io_type != CTL_IO_SCSI)
10829		return (1);
10830
10831	switch (io->scsiio.cdb[0]) {
10832	case COMPARE_AND_WRITE: {
10833		struct scsi_compare_and_write *cdb;
10834
10835		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10836
10837		*lba = scsi_8btou64(cdb->addr);
10838		*len = cdb->length;
10839		break;
10840	}
10841	case READ_6:
10842	case WRITE_6: {
10843		struct scsi_rw_6 *cdb;
10844
10845		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10846
10847		*lba = scsi_3btoul(cdb->addr);
10848		/* only 5 bits are valid in the most significant address byte */
10849		*lba &= 0x1fffff;
10850		*len = cdb->length;
10851		break;
10852	}
10853	case READ_10:
10854	case WRITE_10: {
10855		struct scsi_rw_10 *cdb;
10856
10857		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10858
10859		*lba = scsi_4btoul(cdb->addr);
10860		*len = scsi_2btoul(cdb->length);
10861		break;
10862	}
10863	case WRITE_VERIFY_10: {
10864		struct scsi_write_verify_10 *cdb;
10865
10866		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10867
10868		*lba = scsi_4btoul(cdb->addr);
10869		*len = scsi_2btoul(cdb->length);
10870		break;
10871	}
10872	case READ_12:
10873	case WRITE_12: {
10874		struct scsi_rw_12 *cdb;
10875
10876		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10877
10878		*lba = scsi_4btoul(cdb->addr);
10879		*len = scsi_4btoul(cdb->length);
10880		break;
10881	}
10882	case WRITE_VERIFY_12: {
10883		struct scsi_write_verify_12 *cdb;
10884
10885		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10886
10887		*lba = scsi_4btoul(cdb->addr);
10888		*len = scsi_4btoul(cdb->length);
10889		break;
10890	}
10891	case READ_16:
10892	case WRITE_16: {
10893		struct scsi_rw_16 *cdb;
10894
10895		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10896
10897		*lba = scsi_8btou64(cdb->addr);
10898		*len = scsi_4btoul(cdb->length);
10899		break;
10900	}
10901	case WRITE_VERIFY_16: {
10902		struct scsi_write_verify_16 *cdb;
10903
10904		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10905
10906
10907		*lba = scsi_8btou64(cdb->addr);
10908		*len = scsi_4btoul(cdb->length);
10909		break;
10910	}
10911	case WRITE_SAME_10: {
10912		struct scsi_write_same_10 *cdb;
10913
10914		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10915
10916		*lba = scsi_4btoul(cdb->addr);
10917		*len = scsi_2btoul(cdb->length);
10918		break;
10919	}
10920	case WRITE_SAME_16: {
10921		struct scsi_write_same_16 *cdb;
10922
10923		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10924
10925		*lba = scsi_8btou64(cdb->addr);
10926		*len = scsi_4btoul(cdb->length);
10927		break;
10928	}
10929	case VERIFY_10: {
10930		struct scsi_verify_10 *cdb;
10931
10932		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10933
10934		*lba = scsi_4btoul(cdb->addr);
10935		*len = scsi_2btoul(cdb->length);
10936		break;
10937	}
10938	case VERIFY_12: {
10939		struct scsi_verify_12 *cdb;
10940
10941		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10942
10943		*lba = scsi_4btoul(cdb->addr);
10944		*len = scsi_4btoul(cdb->length);
10945		break;
10946	}
10947	case VERIFY_16: {
10948		struct scsi_verify_16 *cdb;
10949
10950		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10951
10952		*lba = scsi_8btou64(cdb->addr);
10953		*len = scsi_4btoul(cdb->length);
10954		break;
10955	}
10956	case UNMAP: {
10957		*lba = 0;
10958		*len = UINT64_MAX;
10959		break;
10960	}
10961	default:
10962		return (1);
10963		break; /* NOTREACHED */
10964	}
10965
10966	return (0);
10967}
10968
10969static ctl_action
10970ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10971{
10972	uint64_t endlba1, endlba2;
10973
10974	endlba1 = lba1 + len1 - 1;
10975	endlba2 = lba2 + len2 - 1;
10976
10977	if ((endlba1 < lba2)
10978	 || (endlba2 < lba1))
10979		return (CTL_ACTION_PASS);
10980	else
10981		return (CTL_ACTION_BLOCK);
10982}
10983
10984static int
10985ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10986{
10987	struct ctl_ptr_len_flags *ptrlen;
10988	struct scsi_unmap_desc *buf, *end, *range;
10989	uint64_t lba;
10990	uint32_t len;
10991
10992	/* If not UNMAP -- go other way. */
10993	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10994	    io->scsiio.cdb[0] != UNMAP)
10995		return (CTL_ACTION_ERROR);
10996
10997	/* If UNMAP without data -- block and wait for data. */
10998	ptrlen = (struct ctl_ptr_len_flags *)
10999	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
11000	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
11001	    ptrlen->ptr == NULL)
11002		return (CTL_ACTION_BLOCK);
11003
11004	/* UNMAP with data -- check for collision. */
11005	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11006	end = buf + ptrlen->len / sizeof(*buf);
11007	for (range = buf; range < end; range++) {
11008		lba = scsi_8btou64(range->lba);
11009		len = scsi_4btoul(range->length);
11010		if ((lba < lba2 + len2) && (lba + len > lba2))
11011			return (CTL_ACTION_BLOCK);
11012	}
11013	return (CTL_ACTION_PASS);
11014}
11015
11016static ctl_action
11017ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
11018{
11019	uint64_t lba1, lba2;
11020	uint64_t len1, len2;
11021	int retval;
11022
11023	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11024		return (CTL_ACTION_ERROR);
11025
11026	retval = ctl_extent_check_unmap(io2, lba1, len1);
11027	if (retval != CTL_ACTION_ERROR)
11028		return (retval);
11029
11030	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11031		return (CTL_ACTION_ERROR);
11032
11033	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
11034}
11035
11036static ctl_action
11037ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
11038{
11039	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11040	ctl_serialize_action *serialize_row;
11041
11042	/*
11043	 * The initiator attempted multiple untagged commands at the same
11044	 * time.  Can't do that.
11045	 */
11046	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11047	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11048	 && ((pending_io->io_hdr.nexus.targ_port ==
11049	      ooa_io->io_hdr.nexus.targ_port)
11050	  && (pending_io->io_hdr.nexus.initid.id ==
11051	      ooa_io->io_hdr.nexus.initid.id))
11052	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11053		return (CTL_ACTION_OVERLAP);
11054
11055	/*
11056	 * The initiator attempted to send multiple tagged commands with
11057	 * the same ID.  (It's fine if different initiators have the same
11058	 * tag ID.)
11059	 *
11060	 * Even if all of those conditions are true, we don't kill the I/O
11061	 * if the command ahead of us has been aborted.  We won't end up
11062	 * sending it to the FETD, and it's perfectly legal to resend a
11063	 * command with the same tag number as long as the previous
11064	 * instance of this tag number has been aborted somehow.
11065	 */
11066	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11067	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11068	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11069	 && ((pending_io->io_hdr.nexus.targ_port ==
11070	      ooa_io->io_hdr.nexus.targ_port)
11071	  && (pending_io->io_hdr.nexus.initid.id ==
11072	      ooa_io->io_hdr.nexus.initid.id))
11073	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11074		return (CTL_ACTION_OVERLAP_TAG);
11075
11076	/*
11077	 * If we get a head of queue tag, SAM-3 says that we should
11078	 * immediately execute it.
11079	 *
11080	 * What happens if this command would normally block for some other
11081	 * reason?  e.g. a request sense with a head of queue tag
11082	 * immediately after a write.  Normally that would block, but this
11083	 * will result in its getting executed immediately...
11084	 *
11085	 * We currently return "pass" instead of "skip", so we'll end up
11086	 * going through the rest of the queue to check for overlapped tags.
11087	 *
11088	 * XXX KDM check for other types of blockage first??
11089	 */
11090	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11091		return (CTL_ACTION_PASS);
11092
11093	/*
11094	 * Ordered tags have to block until all items ahead of them
11095	 * have completed.  If we get called with an ordered tag, we always
11096	 * block, if something else is ahead of us in the queue.
11097	 */
11098	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11099		return (CTL_ACTION_BLOCK);
11100
11101	/*
11102	 * Simple tags get blocked until all head of queue and ordered tags
11103	 * ahead of them have completed.  I'm lumping untagged commands in
11104	 * with simple tags here.  XXX KDM is that the right thing to do?
11105	 */
11106	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11107	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11108	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11109	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11110		return (CTL_ACTION_BLOCK);
11111
11112	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
11113	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
11114
11115	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11116
11117	switch (serialize_row[pending_entry->seridx]) {
11118	case CTL_SER_BLOCK:
11119		return (CTL_ACTION_BLOCK);
11120		break; /* NOTREACHED */
11121	case CTL_SER_EXTENT:
11122		return (ctl_extent_check(pending_io, ooa_io));
11123		break; /* NOTREACHED */
11124	case CTL_SER_PASS:
11125		return (CTL_ACTION_PASS);
11126		break; /* NOTREACHED */
11127	case CTL_SER_SKIP:
11128		return (CTL_ACTION_SKIP);
11129		break;
11130	default:
11131		panic("invalid serialization value %d",
11132		      serialize_row[pending_entry->seridx]);
11133		break; /* NOTREACHED */
11134	}
11135
11136	return (CTL_ACTION_ERROR);
11137}
11138
11139/*
11140 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11141 * Assumptions:
11142 * - pending_io is generally either incoming, or on the blocked queue
11143 * - starting I/O is the I/O we want to start the check with.
11144 */
11145static ctl_action
11146ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11147	      union ctl_io *starting_io)
11148{
11149	union ctl_io *ooa_io;
11150	ctl_action action;
11151
11152	mtx_assert(&lun->lun_lock, MA_OWNED);
11153
11154	/*
11155	 * Run back along the OOA queue, starting with the current
11156	 * blocked I/O and going through every I/O before it on the
11157	 * queue.  If starting_io is NULL, we'll just end up returning
11158	 * CTL_ACTION_PASS.
11159	 */
11160	for (ooa_io = starting_io; ooa_io != NULL;
11161	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11162	     ooa_links)){
11163
11164		/*
11165		 * This routine just checks to see whether
11166		 * cur_blocked is blocked by ooa_io, which is ahead
11167		 * of it in the queue.  It doesn't queue/dequeue
11168		 * cur_blocked.
11169		 */
11170		action = ctl_check_for_blockage(pending_io, ooa_io);
11171		switch (action) {
11172		case CTL_ACTION_BLOCK:
11173		case CTL_ACTION_OVERLAP:
11174		case CTL_ACTION_OVERLAP_TAG:
11175		case CTL_ACTION_SKIP:
11176		case CTL_ACTION_ERROR:
11177			return (action);
11178			break; /* NOTREACHED */
11179		case CTL_ACTION_PASS:
11180			break;
11181		default:
11182			panic("invalid action %d", action);
11183			break;  /* NOTREACHED */
11184		}
11185	}
11186
11187	return (CTL_ACTION_PASS);
11188}
11189
11190/*
11191 * Assumptions:
11192 * - An I/O has just completed, and has been removed from the per-LUN OOA
11193 *   queue, so some items on the blocked queue may now be unblocked.
11194 */
11195static int
11196ctl_check_blocked(struct ctl_lun *lun)
11197{
11198	union ctl_io *cur_blocked, *next_blocked;
11199
11200	mtx_assert(&lun->lun_lock, MA_OWNED);
11201
11202	/*
11203	 * Run forward from the head of the blocked queue, checking each
11204	 * entry against the I/Os prior to it on the OOA queue to see if
11205	 * there is still any blockage.
11206	 *
11207	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11208	 * with our removing a variable on it while it is traversing the
11209	 * list.
11210	 */
11211	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11212	     cur_blocked != NULL; cur_blocked = next_blocked) {
11213		union ctl_io *prev_ooa;
11214		ctl_action action;
11215
11216		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11217							  blocked_links);
11218
11219		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11220						      ctl_ooaq, ooa_links);
11221
11222		/*
11223		 * If cur_blocked happens to be the first item in the OOA
11224		 * queue now, prev_ooa will be NULL, and the action
11225		 * returned will just be CTL_ACTION_PASS.
11226		 */
11227		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11228
11229		switch (action) {
11230		case CTL_ACTION_BLOCK:
11231			/* Nothing to do here, still blocked */
11232			break;
11233		case CTL_ACTION_OVERLAP:
11234		case CTL_ACTION_OVERLAP_TAG:
11235			/*
11236			 * This shouldn't happen!  In theory we've already
11237			 * checked this command for overlap...
11238			 */
11239			break;
11240		case CTL_ACTION_PASS:
11241		case CTL_ACTION_SKIP: {
11242			struct ctl_softc *softc;
11243			const struct ctl_cmd_entry *entry;
11244			uint32_t initidx;
11245			int isc_retval;
11246
11247			/*
11248			 * The skip case shouldn't happen, this transaction
11249			 * should have never made it onto the blocked queue.
11250			 */
11251			/*
11252			 * This I/O is no longer blocked, we can remove it
11253			 * from the blocked queue.  Since this is a TAILQ
11254			 * (doubly linked list), we can do O(1) removals
11255			 * from any place on the list.
11256			 */
11257			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11258				     blocked_links);
11259			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11260
11261			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11262				/*
11263				 * Need to send IO back to original side to
11264				 * run
11265				 */
11266				union ctl_ha_msg msg_info;
11267
11268				msg_info.hdr.original_sc =
11269					cur_blocked->io_hdr.original_sc;
11270				msg_info.hdr.serializing_sc = cur_blocked;
11271				msg_info.hdr.msg_type = CTL_MSG_R2R;
11272				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11273				     &msg_info, sizeof(msg_info), 0)) >
11274				     CTL_HA_STATUS_SUCCESS) {
11275					printf("CTL:Check Blocked error from "
11276					       "ctl_ha_msg_send %d\n",
11277					       isc_retval);
11278				}
11279				break;
11280			}
11281			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
11282			softc = control_softc;
11283
11284			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11285
11286			/*
11287			 * Check this I/O for LUN state changes that may
11288			 * have happened while this command was blocked.
11289			 * The LUN state may have been changed by a command
11290			 * ahead of us in the queue, so we need to re-check
11291			 * for any states that can be caused by SCSI
11292			 * commands.
11293			 */
11294			if (ctl_scsiio_lun_check(softc, lun, entry,
11295						 &cur_blocked->scsiio) == 0) {
11296				cur_blocked->io_hdr.flags |=
11297				                      CTL_FLAG_IS_WAS_ON_RTR;
11298				ctl_enqueue_rtr(cur_blocked);
11299			} else
11300				ctl_done(cur_blocked);
11301			break;
11302		}
11303		default:
11304			/*
11305			 * This probably shouldn't happen -- we shouldn't
11306			 * get CTL_ACTION_ERROR, or anything else.
11307			 */
11308			break;
11309		}
11310	}
11311
11312	return (CTL_RETVAL_COMPLETE);
11313}
11314
11315/*
11316 * This routine (with one exception) checks LUN flags that can be set by
11317 * commands ahead of us in the OOA queue.  These flags have to be checked
11318 * when a command initially comes in, and when we pull a command off the
11319 * blocked queue and are preparing to execute it.  The reason we have to
11320 * check these flags for commands on the blocked queue is that the LUN
11321 * state may have been changed by a command ahead of us while we're on the
11322 * blocked queue.
11323 *
11324 * Ordering is somewhat important with these checks, so please pay
11325 * careful attention to the placement of any new checks.
11326 */
11327static int
11328ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11329    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11330{
11331	int retval;
11332
11333	retval = 0;
11334
11335	mtx_assert(&lun->lun_lock, MA_OWNED);
11336
11337	/*
11338	 * If this shelf is a secondary shelf controller, we have to reject
11339	 * any media access commands.
11340	 */
11341#if 0
11342	/* No longer needed for HA */
11343	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11344	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11345		ctl_set_lun_standby(ctsio);
11346		retval = 1;
11347		goto bailout;
11348	}
11349#endif
11350
11351	/*
11352	 * Check for a reservation conflict.  If this command isn't allowed
11353	 * even on reserved LUNs, and if this initiator isn't the one who
11354	 * reserved us, reject the command with a reservation conflict.
11355	 */
11356	if ((lun->flags & CTL_LUN_RESERVED)
11357	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11358		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11359		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11360		 || (ctsio->io_hdr.nexus.targ_target.id !=
11361		     lun->rsv_nexus.targ_target.id)) {
11362			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11363			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11364			retval = 1;
11365			goto bailout;
11366		}
11367	}
11368
11369	if ( (lun->flags & CTL_LUN_PR_RESERVED)
11370	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11371		uint32_t residx;
11372
11373		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11374		/*
11375		 * if we aren't registered or it's a res holder type
11376		 * reservation and this isn't the res holder then set a
11377		 * conflict.
11378		 * NOTE: Commands which might be allowed on write exclusive
11379		 * type reservations are checked in the particular command
11380		 * for a conflict. Read and SSU are the only ones.
11381		 */
11382		if (!lun->per_res[residx].registered
11383		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11384			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11385			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11386			retval = 1;
11387			goto bailout;
11388		}
11389
11390	}
11391
11392	if ((lun->flags & CTL_LUN_OFFLINE)
11393	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11394		ctl_set_lun_not_ready(ctsio);
11395		retval = 1;
11396		goto bailout;
11397	}
11398
11399	/*
11400	 * If the LUN is stopped, see if this particular command is allowed
11401	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11402	 */
11403	if ((lun->flags & CTL_LUN_STOPPED)
11404	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11405		/* "Logical unit not ready, initializing cmd. required" */
11406		ctl_set_lun_stopped(ctsio);
11407		retval = 1;
11408		goto bailout;
11409	}
11410
11411	if ((lun->flags & CTL_LUN_INOPERABLE)
11412	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11413		/* "Medium format corrupted" */
11414		ctl_set_medium_format_corrupted(ctsio);
11415		retval = 1;
11416		goto bailout;
11417	}
11418
11419bailout:
11420	return (retval);
11421
11422}
11423
11424static void
11425ctl_failover_io(union ctl_io *io, int have_lock)
11426{
11427	ctl_set_busy(&io->scsiio);
11428	ctl_done(io);
11429}
11430
11431static void
11432ctl_failover(void)
11433{
11434	struct ctl_lun *lun;
11435	struct ctl_softc *ctl_softc;
11436	union ctl_io *next_io, *pending_io;
11437	union ctl_io *io;
11438	int lun_idx;
11439	int i;
11440
11441	ctl_softc = control_softc;
11442
11443	mtx_lock(&ctl_softc->ctl_lock);
11444	/*
11445	 * Remove any cmds from the other SC from the rtr queue.  These
11446	 * will obviously only be for LUNs for which we're the primary.
11447	 * We can't send status or get/send data for these commands.
11448	 * Since they haven't been executed yet, we can just remove them.
11449	 * We'll either abort them or delete them below, depending on
11450	 * which HA mode we're in.
11451	 */
11452#ifdef notyet
11453	mtx_lock(&ctl_softc->queue_lock);
11454	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11455	     io != NULL; io = next_io) {
11456		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11457		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11458			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11459				      ctl_io_hdr, links);
11460	}
11461	mtx_unlock(&ctl_softc->queue_lock);
11462#endif
11463
11464	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11465		lun = ctl_softc->ctl_luns[lun_idx];
11466		if (lun==NULL)
11467			continue;
11468
11469		/*
11470		 * Processor LUNs are primary on both sides.
11471		 * XXX will this always be true?
11472		 */
11473		if (lun->be_lun->lun_type == T_PROCESSOR)
11474			continue;
11475
11476		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11477		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11478			printf("FAILOVER: primary lun %d\n", lun_idx);
11479		        /*
11480			 * Remove all commands from the other SC. First from the
11481			 * blocked queue then from the ooa queue. Once we have
11482			 * removed them. Call ctl_check_blocked to see if there
11483			 * is anything that can run.
11484			 */
11485			for (io = (union ctl_io *)TAILQ_FIRST(
11486			     &lun->blocked_queue); io != NULL; io = next_io) {
11487
11488		        	next_io = (union ctl_io *)TAILQ_NEXT(
11489				    &io->io_hdr, blocked_links);
11490
11491				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11492					TAILQ_REMOVE(&lun->blocked_queue,
11493						     &io->io_hdr,blocked_links);
11494					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11495					TAILQ_REMOVE(&lun->ooa_queue,
11496						     &io->io_hdr, ooa_links);
11497
11498					ctl_free_io(io);
11499				}
11500			}
11501
11502			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11503	     		     io != NULL; io = next_io) {
11504
11505		        	next_io = (union ctl_io *)TAILQ_NEXT(
11506				    &io->io_hdr, ooa_links);
11507
11508				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11509
11510					TAILQ_REMOVE(&lun->ooa_queue,
11511						&io->io_hdr,
11512					     	ooa_links);
11513
11514					ctl_free_io(io);
11515				}
11516			}
11517			ctl_check_blocked(lun);
11518		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11519			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11520
11521			printf("FAILOVER: primary lun %d\n", lun_idx);
11522			/*
11523			 * Abort all commands from the other SC.  We can't
11524			 * send status back for them now.  These should get
11525			 * cleaned up when they are completed or come out
11526			 * for a datamove operation.
11527			 */
11528			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11529	     		     io != NULL; io = next_io) {
11530		        	next_io = (union ctl_io *)TAILQ_NEXT(
11531					&io->io_hdr, ooa_links);
11532
11533				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11534					io->io_hdr.flags |= CTL_FLAG_ABORT;
11535			}
11536		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11537			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11538
11539			printf("FAILOVER: secondary lun %d\n", lun_idx);
11540
11541			lun->flags |= CTL_LUN_PRIMARY_SC;
11542
11543			/*
11544			 * We send all I/O that was sent to this controller
11545			 * and redirected to the other side back with
11546			 * busy status, and have the initiator retry it.
11547			 * Figuring out how much data has been transferred,
11548			 * etc. and picking up where we left off would be
11549			 * very tricky.
11550			 *
11551			 * XXX KDM need to remove I/O from the blocked
11552			 * queue as well!
11553			 */
11554			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11555			     &lun->ooa_queue); pending_io != NULL;
11556			     pending_io = next_io) {
11557
11558				next_io =  (union ctl_io *)TAILQ_NEXT(
11559					&pending_io->io_hdr, ooa_links);
11560
11561				pending_io->io_hdr.flags &=
11562					~CTL_FLAG_SENT_2OTHER_SC;
11563
11564				if (pending_io->io_hdr.flags &
11565				    CTL_FLAG_IO_ACTIVE) {
11566					pending_io->io_hdr.flags |=
11567						CTL_FLAG_FAILOVER;
11568				} else {
11569					ctl_set_busy(&pending_io->scsiio);
11570					ctl_done(pending_io);
11571				}
11572			}
11573
11574			/*
11575			 * Build Unit Attention
11576			 */
11577			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11578				lun->pending_ua[i] |=
11579				                     CTL_UA_ASYM_ACC_CHANGE;
11580			}
11581		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11582			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11583			printf("FAILOVER: secondary lun %d\n", lun_idx);
11584			/*
11585			 * if the first io on the OOA is not on the RtR queue
11586			 * add it.
11587			 */
11588			lun->flags |= CTL_LUN_PRIMARY_SC;
11589
11590			pending_io = (union ctl_io *)TAILQ_FIRST(
11591			    &lun->ooa_queue);
11592			if (pending_io==NULL) {
11593				printf("Nothing on OOA queue\n");
11594				continue;
11595			}
11596
11597			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11598			if ((pending_io->io_hdr.flags &
11599			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11600				pending_io->io_hdr.flags |=
11601				    CTL_FLAG_IS_WAS_ON_RTR;
11602				ctl_enqueue_rtr(pending_io);
11603			}
11604#if 0
11605			else
11606			{
11607				printf("Tag 0x%04x is running\n",
11608				      pending_io->scsiio.tag_num);
11609			}
11610#endif
11611
11612			next_io = (union ctl_io *)TAILQ_NEXT(
11613			    &pending_io->io_hdr, ooa_links);
11614			for (pending_io=next_io; pending_io != NULL;
11615			     pending_io = next_io) {
11616				pending_io->io_hdr.flags &=
11617				    ~CTL_FLAG_SENT_2OTHER_SC;
11618				next_io = (union ctl_io *)TAILQ_NEXT(
11619					&pending_io->io_hdr, ooa_links);
11620				if (pending_io->io_hdr.flags &
11621				    CTL_FLAG_IS_WAS_ON_RTR) {
11622#if 0
11623				        printf("Tag 0x%04x is running\n",
11624				      		pending_io->scsiio.tag_num);
11625#endif
11626					continue;
11627				}
11628
11629				switch (ctl_check_ooa(lun, pending_io,
11630			            (union ctl_io *)TAILQ_PREV(
11631				    &pending_io->io_hdr, ctl_ooaq,
11632				    ooa_links))) {
11633
11634				case CTL_ACTION_BLOCK:
11635					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11636							  &pending_io->io_hdr,
11637							  blocked_links);
11638					pending_io->io_hdr.flags |=
11639					    CTL_FLAG_BLOCKED;
11640					break;
11641				case CTL_ACTION_PASS:
11642				case CTL_ACTION_SKIP:
11643					pending_io->io_hdr.flags |=
11644					    CTL_FLAG_IS_WAS_ON_RTR;
11645					ctl_enqueue_rtr(pending_io);
11646					break;
11647				case CTL_ACTION_OVERLAP:
11648					ctl_set_overlapped_cmd(
11649					    (struct ctl_scsiio *)pending_io);
11650					ctl_done(pending_io);
11651					break;
11652				case CTL_ACTION_OVERLAP_TAG:
11653					ctl_set_overlapped_tag(
11654					    (struct ctl_scsiio *)pending_io,
11655					    pending_io->scsiio.tag_num & 0xff);
11656					ctl_done(pending_io);
11657					break;
11658				case CTL_ACTION_ERROR:
11659				default:
11660					ctl_set_internal_failure(
11661						(struct ctl_scsiio *)pending_io,
11662						0,  // sks_valid
11663						0); //retry count
11664					ctl_done(pending_io);
11665					break;
11666				}
11667			}
11668
11669			/*
11670			 * Build Unit Attention
11671			 */
11672			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11673				lun->pending_ua[i] |=
11674				                     CTL_UA_ASYM_ACC_CHANGE;
11675			}
11676		} else {
11677			panic("Unhandled HA mode failover, LUN flags = %#x, "
11678			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11679		}
11680	}
11681	ctl_pause_rtr = 0;
11682	mtx_unlock(&ctl_softc->ctl_lock);
11683}
11684
11685static int
11686ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11687{
11688	struct ctl_lun *lun;
11689	const struct ctl_cmd_entry *entry;
11690	uint32_t initidx, targ_lun;
11691	int retval;
11692
11693	retval = 0;
11694
11695	lun = NULL;
11696
11697	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11698	if ((targ_lun < CTL_MAX_LUNS)
11699	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11700		lun = ctl_softc->ctl_luns[targ_lun];
11701		/*
11702		 * If the LUN is invalid, pretend that it doesn't exist.
11703		 * It will go away as soon as all pending I/O has been
11704		 * completed.
11705		 */
11706		if (lun->flags & CTL_LUN_DISABLED) {
11707			lun = NULL;
11708		} else {
11709			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11710			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11711				lun->be_lun;
11712			if (lun->be_lun->lun_type == T_PROCESSOR) {
11713				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11714			}
11715
11716			/*
11717			 * Every I/O goes into the OOA queue for a
11718			 * particular LUN, and stays there until completion.
11719			 */
11720			mtx_lock(&lun->lun_lock);
11721			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11722			    ooa_links);
11723		}
11724	} else {
11725		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11726		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11727	}
11728
11729	/* Get command entry and return error if it is unsuppotyed. */
11730	entry = ctl_validate_command(ctsio);
11731	if (entry == NULL) {
11732		if (lun)
11733			mtx_unlock(&lun->lun_lock);
11734		return (retval);
11735	}
11736
11737	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11738	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11739
11740	/*
11741	 * Check to see whether we can send this command to LUNs that don't
11742	 * exist.  This should pretty much only be the case for inquiry
11743	 * and request sense.  Further checks, below, really require having
11744	 * a LUN, so we can't really check the command anymore.  Just put
11745	 * it on the rtr queue.
11746	 */
11747	if (lun == NULL) {
11748		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11749			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11750			ctl_enqueue_rtr((union ctl_io *)ctsio);
11751			return (retval);
11752		}
11753
11754		ctl_set_unsupported_lun(ctsio);
11755		ctl_done((union ctl_io *)ctsio);
11756		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11757		return (retval);
11758	} else {
11759		/*
11760		 * Make sure we support this particular command on this LUN.
11761		 * e.g., we don't support writes to the control LUN.
11762		 */
11763		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11764			mtx_unlock(&lun->lun_lock);
11765			ctl_set_invalid_opcode(ctsio);
11766			ctl_done((union ctl_io *)ctsio);
11767			return (retval);
11768		}
11769	}
11770
11771	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11772
11773#ifdef CTL_WITH_CA
11774	/*
11775	 * If we've got a request sense, it'll clear the contingent
11776	 * allegiance condition.  Otherwise, if we have a CA condition for
11777	 * this initiator, clear it, because it sent down a command other
11778	 * than request sense.
11779	 */
11780	if ((ctsio->cdb[0] != REQUEST_SENSE)
11781	 && (ctl_is_set(lun->have_ca, initidx)))
11782		ctl_clear_mask(lun->have_ca, initidx);
11783#endif
11784
11785	/*
11786	 * If the command has this flag set, it handles its own unit
11787	 * attention reporting, we shouldn't do anything.  Otherwise we
11788	 * check for any pending unit attentions, and send them back to the
11789	 * initiator.  We only do this when a command initially comes in,
11790	 * not when we pull it off the blocked queue.
11791	 *
11792	 * According to SAM-3, section 5.3.2, the order that things get
11793	 * presented back to the host is basically unit attentions caused
11794	 * by some sort of reset event, busy status, reservation conflicts
11795	 * or task set full, and finally any other status.
11796	 *
11797	 * One issue here is that some of the unit attentions we report
11798	 * don't fall into the "reset" category (e.g. "reported luns data
11799	 * has changed").  So reporting it here, before the reservation
11800	 * check, may be technically wrong.  I guess the only thing to do
11801	 * would be to check for and report the reset events here, and then
11802	 * check for the other unit attention types after we check for a
11803	 * reservation conflict.
11804	 *
11805	 * XXX KDM need to fix this
11806	 */
11807	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11808		ctl_ua_type ua_type;
11809
11810		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11811			scsi_sense_data_type sense_format;
11812
11813			if (lun != NULL)
11814				sense_format = (lun->flags &
11815				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11816				    SSD_TYPE_FIXED;
11817			else
11818				sense_format = SSD_TYPE_FIXED;
11819
11820			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11821			    &ctsio->sense_data, sense_format);
11822			if (ua_type != CTL_UA_NONE) {
11823				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11824				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11825						       CTL_AUTOSENSE;
11826				ctsio->sense_len = SSD_FULL_SIZE;
11827				mtx_unlock(&lun->lun_lock);
11828				ctl_done((union ctl_io *)ctsio);
11829				return (retval);
11830			}
11831		}
11832	}
11833
11834
11835	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11836		mtx_unlock(&lun->lun_lock);
11837		ctl_done((union ctl_io *)ctsio);
11838		return (retval);
11839	}
11840
11841	/*
11842	 * XXX CHD this is where we want to send IO to other side if
11843	 * this LUN is secondary on this SC. We will need to make a copy
11844	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11845	 * the copy we send as FROM_OTHER.
11846	 * We also need to stuff the address of the original IO so we can
11847	 * find it easily. Something similar will need be done on the other
11848	 * side so when we are done we can find the copy.
11849	 */
11850	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11851		union ctl_ha_msg msg_info;
11852		int isc_retval;
11853
11854		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11855
11856		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11857		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11858#if 0
11859		printf("1. ctsio %p\n", ctsio);
11860#endif
11861		msg_info.hdr.serializing_sc = NULL;
11862		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11863		msg_info.scsi.tag_num = ctsio->tag_num;
11864		msg_info.scsi.tag_type = ctsio->tag_type;
11865		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11866
11867		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11868
11869		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11870		    (void *)&msg_info, sizeof(msg_info), 0)) >
11871		    CTL_HA_STATUS_SUCCESS) {
11872			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11873			       isc_retval);
11874			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11875		} else {
11876#if 0
11877			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11878#endif
11879		}
11880
11881		/*
11882		 * XXX KDM this I/O is off the incoming queue, but hasn't
11883		 * been inserted on any other queue.  We may need to come
11884		 * up with a holding queue while we wait for serialization
11885		 * so that we have an idea of what we're waiting for from
11886		 * the other side.
11887		 */
11888		mtx_unlock(&lun->lun_lock);
11889		return (retval);
11890	}
11891
11892	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11893			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11894			      ctl_ooaq, ooa_links))) {
11895	case CTL_ACTION_BLOCK:
11896		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11897		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11898				  blocked_links);
11899		mtx_unlock(&lun->lun_lock);
11900		return (retval);
11901	case CTL_ACTION_PASS:
11902	case CTL_ACTION_SKIP:
11903		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11904		mtx_unlock(&lun->lun_lock);
11905		ctl_enqueue_rtr((union ctl_io *)ctsio);
11906		break;
11907	case CTL_ACTION_OVERLAP:
11908		mtx_unlock(&lun->lun_lock);
11909		ctl_set_overlapped_cmd(ctsio);
11910		ctl_done((union ctl_io *)ctsio);
11911		break;
11912	case CTL_ACTION_OVERLAP_TAG:
11913		mtx_unlock(&lun->lun_lock);
11914		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11915		ctl_done((union ctl_io *)ctsio);
11916		break;
11917	case CTL_ACTION_ERROR:
11918	default:
11919		mtx_unlock(&lun->lun_lock);
11920		ctl_set_internal_failure(ctsio,
11921					 /*sks_valid*/ 0,
11922					 /*retry_count*/ 0);
11923		ctl_done((union ctl_io *)ctsio);
11924		break;
11925	}
11926	return (retval);
11927}
11928
11929const struct ctl_cmd_entry *
11930ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11931{
11932	const struct ctl_cmd_entry *entry;
11933	int service_action;
11934
11935	entry = &ctl_cmd_table[ctsio->cdb[0]];
11936	if (entry->flags & CTL_CMD_FLAG_SA5) {
11937		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11938		entry = &((const struct ctl_cmd_entry *)
11939		    entry->execute)[service_action];
11940	}
11941	return (entry);
11942}
11943
11944const struct ctl_cmd_entry *
11945ctl_validate_command(struct ctl_scsiio *ctsio)
11946{
11947	const struct ctl_cmd_entry *entry;
11948	int i;
11949	uint8_t diff;
11950
11951	entry = ctl_get_cmd_entry(ctsio);
11952	if (entry->execute == NULL) {
11953		ctl_set_invalid_opcode(ctsio);
11954		ctl_done((union ctl_io *)ctsio);
11955		return (NULL);
11956	}
11957	KASSERT(entry->length > 0,
11958	    ("Not defined length for command 0x%02x/0x%02x",
11959	     ctsio->cdb[0], ctsio->cdb[1]));
11960	for (i = 1; i < entry->length; i++) {
11961		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11962		if (diff == 0)
11963			continue;
11964		ctl_set_invalid_field(ctsio,
11965				      /*sks_valid*/ 1,
11966				      /*command*/ 1,
11967				      /*field*/ i,
11968				      /*bit_valid*/ 1,
11969				      /*bit*/ fls(diff) - 1);
11970		ctl_done((union ctl_io *)ctsio);
11971		return (NULL);
11972	}
11973	return (entry);
11974}
11975
11976static int
11977ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11978{
11979
11980	switch (lun_type) {
11981	case T_PROCESSOR:
11982		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11983		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11984			return (0);
11985		break;
11986	case T_DIRECT:
11987		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11988		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11989			return (0);
11990		break;
11991	default:
11992		return (0);
11993	}
11994	return (1);
11995}
11996
11997static int
11998ctl_scsiio(struct ctl_scsiio *ctsio)
11999{
12000	int retval;
12001	const struct ctl_cmd_entry *entry;
12002
12003	retval = CTL_RETVAL_COMPLETE;
12004
12005	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12006
12007	entry = ctl_get_cmd_entry(ctsio);
12008
12009	/*
12010	 * If this I/O has been aborted, just send it straight to
12011	 * ctl_done() without executing it.
12012	 */
12013	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12014		ctl_done((union ctl_io *)ctsio);
12015		goto bailout;
12016	}
12017
12018	/*
12019	 * All the checks should have been handled by ctl_scsiio_precheck().
12020	 * We should be clear now to just execute the I/O.
12021	 */
12022	retval = entry->execute(ctsio);
12023
12024bailout:
12025	return (retval);
12026}
12027
12028/*
12029 * Since we only implement one target right now, a bus reset simply resets
12030 * our single target.
12031 */
12032static int
12033ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12034{
12035	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12036}
12037
12038static int
12039ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12040		 ctl_ua_type ua_type)
12041{
12042	struct ctl_lun *lun;
12043	int retval;
12044
12045	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12046		union ctl_ha_msg msg_info;
12047
12048		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12049		msg_info.hdr.nexus = io->io_hdr.nexus;
12050		if (ua_type==CTL_UA_TARG_RESET)
12051			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12052		else
12053			msg_info.task.task_action = CTL_TASK_BUS_RESET;
12054		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12055		msg_info.hdr.original_sc = NULL;
12056		msg_info.hdr.serializing_sc = NULL;
12057		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12058		    (void *)&msg_info, sizeof(msg_info), 0)) {
12059		}
12060	}
12061	retval = 0;
12062
12063	mtx_lock(&ctl_softc->ctl_lock);
12064	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12065		retval += ctl_lun_reset(lun, io, ua_type);
12066	mtx_unlock(&ctl_softc->ctl_lock);
12067
12068	return (retval);
12069}
12070
12071/*
12072 * The LUN should always be set.  The I/O is optional, and is used to
12073 * distinguish between I/Os sent by this initiator, and by other
12074 * initiators.  We set unit attention for initiators other than this one.
12075 * SAM-3 is vague on this point.  It does say that a unit attention should
12076 * be established for other initiators when a LUN is reset (see section
12077 * 5.7.3), but it doesn't specifically say that the unit attention should
12078 * be established for this particular initiator when a LUN is reset.  Here
12079 * is the relevant text, from SAM-3 rev 8:
12080 *
12081 * 5.7.2 When a SCSI initiator port aborts its own tasks
12082 *
12083 * When a SCSI initiator port causes its own task(s) to be aborted, no
12084 * notification that the task(s) have been aborted shall be returned to
12085 * the SCSI initiator port other than the completion response for the
12086 * command or task management function action that caused the task(s) to
12087 * be aborted and notification(s) associated with related effects of the
12088 * action (e.g., a reset unit attention condition).
12089 *
12090 * XXX KDM for now, we're setting unit attention for all initiators.
12091 */
12092static int
12093ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12094{
12095	union ctl_io *xio;
12096#if 0
12097	uint32_t initindex;
12098#endif
12099	int i;
12100
12101	mtx_lock(&lun->lun_lock);
12102	/*
12103	 * Run through the OOA queue and abort each I/O.
12104	 */
12105#if 0
12106	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12107#endif
12108	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12109	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12110		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12111	}
12112
12113	/*
12114	 * This version sets unit attention for every
12115	 */
12116#if 0
12117	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12118	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12119		if (initindex == i)
12120			continue;
12121		lun->pending_ua[i] |= ua_type;
12122	}
12123#endif
12124
12125	/*
12126	 * A reset (any kind, really) clears reservations established with
12127	 * RESERVE/RELEASE.  It does not clear reservations established
12128	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12129	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12130	 * reservations made with the RESERVE/RELEASE commands, because
12131	 * those commands are obsolete in SPC-3.
12132	 */
12133	lun->flags &= ~CTL_LUN_RESERVED;
12134
12135	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12136#ifdef CTL_WITH_CA
12137		ctl_clear_mask(lun->have_ca, i);
12138#endif
12139		lun->pending_ua[i] |= ua_type;
12140	}
12141	mtx_unlock(&lun->lun_lock);
12142
12143	return (0);
12144}
12145
12146static void
12147ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12148    int other_sc)
12149{
12150	union ctl_io *xio;
12151
12152	mtx_assert(&lun->lun_lock, MA_OWNED);
12153
12154	/*
12155	 * Run through the OOA queue and attempt to find the given I/O.
12156	 * The target port, initiator ID, tag type and tag number have to
12157	 * match the values that we got from the initiator.  If we have an
12158	 * untagged command to abort, simply abort the first untagged command
12159	 * we come to.  We only allow one untagged command at a time of course.
12160	 */
12161	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12162	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12163
12164		if ((targ_port == UINT32_MAX ||
12165		     targ_port == xio->io_hdr.nexus.targ_port) &&
12166		    (init_id == UINT32_MAX ||
12167		     init_id == xio->io_hdr.nexus.initid.id)) {
12168			if (targ_port != xio->io_hdr.nexus.targ_port ||
12169			    init_id != xio->io_hdr.nexus.initid.id)
12170				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12171			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12172			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12173				union ctl_ha_msg msg_info;
12174
12175				msg_info.hdr.nexus = xio->io_hdr.nexus;
12176				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12177				msg_info.task.tag_num = xio->scsiio.tag_num;
12178				msg_info.task.tag_type = xio->scsiio.tag_type;
12179				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12180				msg_info.hdr.original_sc = NULL;
12181				msg_info.hdr.serializing_sc = NULL;
12182				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12183				    (void *)&msg_info, sizeof(msg_info), 0);
12184			}
12185		}
12186	}
12187}
12188
12189static int
12190ctl_abort_task_set(union ctl_io *io)
12191{
12192	struct ctl_softc *softc = control_softc;
12193	struct ctl_lun *lun;
12194	uint32_t targ_lun;
12195
12196	/*
12197	 * Look up the LUN.
12198	 */
12199	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12200	mtx_lock(&softc->ctl_lock);
12201	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12202		lun = softc->ctl_luns[targ_lun];
12203	else {
12204		mtx_unlock(&softc->ctl_lock);
12205		return (1);
12206	}
12207
12208	mtx_lock(&lun->lun_lock);
12209	mtx_unlock(&softc->ctl_lock);
12210	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12211		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12212		    io->io_hdr.nexus.initid.id,
12213		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12214	} else { /* CTL_TASK_CLEAR_TASK_SET */
12215		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12216		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12217	}
12218	mtx_unlock(&lun->lun_lock);
12219	return (0);
12220}
12221
12222static int
12223ctl_i_t_nexus_reset(union ctl_io *io)
12224{
12225	struct ctl_softc *softc = control_softc;
12226	struct ctl_lun *lun;
12227	uint32_t initindex;
12228
12229	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12230	mtx_lock(&softc->ctl_lock);
12231	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12232		mtx_lock(&lun->lun_lock);
12233		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12234		    io->io_hdr.nexus.initid.id,
12235		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12236#ifdef CTL_WITH_CA
12237		ctl_clear_mask(lun->have_ca, initindex);
12238#endif
12239		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12240		mtx_unlock(&lun->lun_lock);
12241	}
12242	mtx_unlock(&softc->ctl_lock);
12243	return (0);
12244}
12245
12246static int
12247ctl_abort_task(union ctl_io *io)
12248{
12249	union ctl_io *xio;
12250	struct ctl_lun *lun;
12251	struct ctl_softc *ctl_softc;
12252#if 0
12253	struct sbuf sb;
12254	char printbuf[128];
12255#endif
12256	int found;
12257	uint32_t targ_lun;
12258
12259	ctl_softc = control_softc;
12260	found = 0;
12261
12262	/*
12263	 * Look up the LUN.
12264	 */
12265	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12266	mtx_lock(&ctl_softc->ctl_lock);
12267	if ((targ_lun < CTL_MAX_LUNS)
12268	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12269		lun = ctl_softc->ctl_luns[targ_lun];
12270	else {
12271		mtx_unlock(&ctl_softc->ctl_lock);
12272		return (1);
12273	}
12274
12275#if 0
12276	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12277	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12278#endif
12279
12280	mtx_lock(&lun->lun_lock);
12281	mtx_unlock(&ctl_softc->ctl_lock);
12282	/*
12283	 * Run through the OOA queue and attempt to find the given I/O.
12284	 * The target port, initiator ID, tag type and tag number have to
12285	 * match the values that we got from the initiator.  If we have an
12286	 * untagged command to abort, simply abort the first untagged command
12287	 * we come to.  We only allow one untagged command at a time of course.
12288	 */
12289#if 0
12290	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12291#endif
12292	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12293	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12294#if 0
12295		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12296
12297		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12298			    lun->lun, xio->scsiio.tag_num,
12299			    xio->scsiio.tag_type,
12300			    (xio->io_hdr.blocked_links.tqe_prev
12301			    == NULL) ? "" : " BLOCKED",
12302			    (xio->io_hdr.flags &
12303			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12304			    (xio->io_hdr.flags &
12305			    CTL_FLAG_ABORT) ? " ABORT" : "",
12306			    (xio->io_hdr.flags &
12307			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12308		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12309		sbuf_finish(&sb);
12310		printf("%s\n", sbuf_data(&sb));
12311#endif
12312
12313		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12314		 && (xio->io_hdr.nexus.initid.id ==
12315		     io->io_hdr.nexus.initid.id)) {
12316			/*
12317			 * If the abort says that the task is untagged, the
12318			 * task in the queue must be untagged.  Otherwise,
12319			 * we just check to see whether the tag numbers
12320			 * match.  This is because the QLogic firmware
12321			 * doesn't pass back the tag type in an abort
12322			 * request.
12323			 */
12324#if 0
12325			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12326			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12327			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12328#endif
12329			/*
12330			 * XXX KDM we've got problems with FC, because it
12331			 * doesn't send down a tag type with aborts.  So we
12332			 * can only really go by the tag number...
12333			 * This may cause problems with parallel SCSI.
12334			 * Need to figure that out!!
12335			 */
12336			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12337				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12338				found = 1;
12339				if ((io->io_hdr.flags &
12340				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12341				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12342					union ctl_ha_msg msg_info;
12343
12344					io->io_hdr.flags |=
12345					                CTL_FLAG_SENT_2OTHER_SC;
12346					msg_info.hdr.nexus = io->io_hdr.nexus;
12347					msg_info.task.task_action =
12348						CTL_TASK_ABORT_TASK;
12349					msg_info.task.tag_num =
12350						io->taskio.tag_num;
12351					msg_info.task.tag_type =
12352						io->taskio.tag_type;
12353					msg_info.hdr.msg_type =
12354						CTL_MSG_MANAGE_TASKS;
12355					msg_info.hdr.original_sc = NULL;
12356					msg_info.hdr.serializing_sc = NULL;
12357#if 0
12358					printf("Sent Abort to other side\n");
12359#endif
12360					if (CTL_HA_STATUS_SUCCESS !=
12361					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12362		    				(void *)&msg_info,
12363						sizeof(msg_info), 0)) {
12364					}
12365				}
12366#if 0
12367				printf("ctl_abort_task: found I/O to abort\n");
12368#endif
12369				break;
12370			}
12371		}
12372	}
12373	mtx_unlock(&lun->lun_lock);
12374
12375	if (found == 0) {
12376		/*
12377		 * This isn't really an error.  It's entirely possible for
12378		 * the abort and command completion to cross on the wire.
12379		 * This is more of an informative/diagnostic error.
12380		 */
12381#if 0
12382		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12383		       "%d:%d:%d:%d tag %d type %d\n",
12384		       io->io_hdr.nexus.initid.id,
12385		       io->io_hdr.nexus.targ_port,
12386		       io->io_hdr.nexus.targ_target.id,
12387		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12388		       io->taskio.tag_type);
12389#endif
12390	}
12391	return (0);
12392}
12393
12394static void
12395ctl_run_task(union ctl_io *io)
12396{
12397	struct ctl_softc *ctl_softc = control_softc;
12398	int retval = 1;
12399	const char *task_desc;
12400
12401	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12402
12403	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12404	    ("ctl_run_task: Unextected io_type %d\n",
12405	     io->io_hdr.io_type));
12406
12407	task_desc = ctl_scsi_task_string(&io->taskio);
12408	if (task_desc != NULL) {
12409#ifdef NEEDTOPORT
12410		csevent_log(CSC_CTL | CSC_SHELF_SW |
12411			    CTL_TASK_REPORT,
12412			    csevent_LogType_Trace,
12413			    csevent_Severity_Information,
12414			    csevent_AlertLevel_Green,
12415			    csevent_FRU_Firmware,
12416			    csevent_FRU_Unknown,
12417			    "CTL: received task: %s",task_desc);
12418#endif
12419	} else {
12420#ifdef NEEDTOPORT
12421		csevent_log(CSC_CTL | CSC_SHELF_SW |
12422			    CTL_TASK_REPORT,
12423			    csevent_LogType_Trace,
12424			    csevent_Severity_Information,
12425			    csevent_AlertLevel_Green,
12426			    csevent_FRU_Firmware,
12427			    csevent_FRU_Unknown,
12428			    "CTL: received unknown task "
12429			    "type: %d (%#x)",
12430			    io->taskio.task_action,
12431			    io->taskio.task_action);
12432#endif
12433	}
12434	switch (io->taskio.task_action) {
12435	case CTL_TASK_ABORT_TASK:
12436		retval = ctl_abort_task(io);
12437		break;
12438	case CTL_TASK_ABORT_TASK_SET:
12439	case CTL_TASK_CLEAR_TASK_SET:
12440		retval = ctl_abort_task_set(io);
12441		break;
12442	case CTL_TASK_CLEAR_ACA:
12443		break;
12444	case CTL_TASK_I_T_NEXUS_RESET:
12445		retval = ctl_i_t_nexus_reset(io);
12446		break;
12447	case CTL_TASK_LUN_RESET: {
12448		struct ctl_lun *lun;
12449		uint32_t targ_lun;
12450
12451		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12452		mtx_lock(&ctl_softc->ctl_lock);
12453		if ((targ_lun < CTL_MAX_LUNS)
12454		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12455			lun = ctl_softc->ctl_luns[targ_lun];
12456		else {
12457			mtx_unlock(&ctl_softc->ctl_lock);
12458			retval = 1;
12459			break;
12460		}
12461
12462		if (!(io->io_hdr.flags &
12463		    CTL_FLAG_FROM_OTHER_SC)) {
12464			union ctl_ha_msg msg_info;
12465
12466			io->io_hdr.flags |=
12467				CTL_FLAG_SENT_2OTHER_SC;
12468			msg_info.hdr.msg_type =
12469				CTL_MSG_MANAGE_TASKS;
12470			msg_info.hdr.nexus = io->io_hdr.nexus;
12471			msg_info.task.task_action =
12472				CTL_TASK_LUN_RESET;
12473			msg_info.hdr.original_sc = NULL;
12474			msg_info.hdr.serializing_sc = NULL;
12475			if (CTL_HA_STATUS_SUCCESS !=
12476			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12477			    (void *)&msg_info,
12478			    sizeof(msg_info), 0)) {
12479			}
12480		}
12481
12482		retval = ctl_lun_reset(lun, io,
12483				       CTL_UA_LUN_RESET);
12484		mtx_unlock(&ctl_softc->ctl_lock);
12485		break;
12486	}
12487	case CTL_TASK_TARGET_RESET:
12488		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12489		break;
12490	case CTL_TASK_BUS_RESET:
12491		retval = ctl_bus_reset(ctl_softc, io);
12492		break;
12493	case CTL_TASK_PORT_LOGIN:
12494		break;
12495	case CTL_TASK_PORT_LOGOUT:
12496		break;
12497	default:
12498		printf("ctl_run_task: got unknown task management event %d\n",
12499		       io->taskio.task_action);
12500		break;
12501	}
12502	if (retval == 0)
12503		io->io_hdr.status = CTL_SUCCESS;
12504	else
12505		io->io_hdr.status = CTL_ERROR;
12506	ctl_done(io);
12507}
12508
12509/*
12510 * For HA operation.  Handle commands that come in from the other
12511 * controller.
12512 */
12513static void
12514ctl_handle_isc(union ctl_io *io)
12515{
12516	int free_io;
12517	struct ctl_lun *lun;
12518	struct ctl_softc *ctl_softc;
12519	uint32_t targ_lun;
12520
12521	ctl_softc = control_softc;
12522
12523	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12524	lun = ctl_softc->ctl_luns[targ_lun];
12525
12526	switch (io->io_hdr.msg_type) {
12527	case CTL_MSG_SERIALIZE:
12528		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12529		break;
12530	case CTL_MSG_R2R: {
12531		const struct ctl_cmd_entry *entry;
12532
12533		/*
12534		 * This is only used in SER_ONLY mode.
12535		 */
12536		free_io = 0;
12537		entry = ctl_get_cmd_entry(&io->scsiio);
12538		mtx_lock(&lun->lun_lock);
12539		if (ctl_scsiio_lun_check(ctl_softc, lun,
12540		    entry, (struct ctl_scsiio *)io) != 0) {
12541			mtx_unlock(&lun->lun_lock);
12542			ctl_done(io);
12543			break;
12544		}
12545		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12546		mtx_unlock(&lun->lun_lock);
12547		ctl_enqueue_rtr(io);
12548		break;
12549	}
12550	case CTL_MSG_FINISH_IO:
12551		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12552			free_io = 0;
12553			ctl_done(io);
12554		} else {
12555			free_io = 1;
12556			mtx_lock(&lun->lun_lock);
12557			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12558				     ooa_links);
12559			ctl_check_blocked(lun);
12560			mtx_unlock(&lun->lun_lock);
12561		}
12562		break;
12563	case CTL_MSG_PERS_ACTION:
12564		ctl_hndl_per_res_out_on_other_sc(
12565			(union ctl_ha_msg *)&io->presio.pr_msg);
12566		free_io = 1;
12567		break;
12568	case CTL_MSG_BAD_JUJU:
12569		free_io = 0;
12570		ctl_done(io);
12571		break;
12572	case CTL_MSG_DATAMOVE:
12573		/* Only used in XFER mode */
12574		free_io = 0;
12575		ctl_datamove_remote(io);
12576		break;
12577	case CTL_MSG_DATAMOVE_DONE:
12578		/* Only used in XFER mode */
12579		free_io = 0;
12580		io->scsiio.be_move_done(io);
12581		break;
12582	default:
12583		free_io = 1;
12584		printf("%s: Invalid message type %d\n",
12585		       __func__, io->io_hdr.msg_type);
12586		break;
12587	}
12588	if (free_io)
12589		ctl_free_io(io);
12590
12591}
12592
12593
12594/*
12595 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12596 * there is no match.
12597 */
12598static ctl_lun_error_pattern
12599ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12600{
12601	const struct ctl_cmd_entry *entry;
12602	ctl_lun_error_pattern filtered_pattern, pattern;
12603
12604	pattern = desc->error_pattern;
12605
12606	/*
12607	 * XXX KDM we need more data passed into this function to match a
12608	 * custom pattern, and we actually need to implement custom pattern
12609	 * matching.
12610	 */
12611	if (pattern & CTL_LUN_PAT_CMD)
12612		return (CTL_LUN_PAT_CMD);
12613
12614	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12615		return (CTL_LUN_PAT_ANY);
12616
12617	entry = ctl_get_cmd_entry(ctsio);
12618
12619	filtered_pattern = entry->pattern & pattern;
12620
12621	/*
12622	 * If the user requested specific flags in the pattern (e.g.
12623	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12624	 * flags.
12625	 *
12626	 * If the user did not specify any flags, it doesn't matter whether
12627	 * or not the command supports the flags.
12628	 */
12629	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12630	     (pattern & ~CTL_LUN_PAT_MASK))
12631		return (CTL_LUN_PAT_NONE);
12632
12633	/*
12634	 * If the user asked for a range check, see if the requested LBA
12635	 * range overlaps with this command's LBA range.
12636	 */
12637	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12638		uint64_t lba1;
12639		uint64_t len1;
12640		ctl_action action;
12641		int retval;
12642
12643		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12644		if (retval != 0)
12645			return (CTL_LUN_PAT_NONE);
12646
12647		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12648					      desc->lba_range.len);
12649		/*
12650		 * A "pass" means that the LBA ranges don't overlap, so
12651		 * this doesn't match the user's range criteria.
12652		 */
12653		if (action == CTL_ACTION_PASS)
12654			return (CTL_LUN_PAT_NONE);
12655	}
12656
12657	return (filtered_pattern);
12658}
12659
12660static void
12661ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12662{
12663	struct ctl_error_desc *desc, *desc2;
12664
12665	mtx_assert(&lun->lun_lock, MA_OWNED);
12666
12667	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12668		ctl_lun_error_pattern pattern;
12669		/*
12670		 * Check to see whether this particular command matches
12671		 * the pattern in the descriptor.
12672		 */
12673		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12674		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12675			continue;
12676
12677		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12678		case CTL_LUN_INJ_ABORTED:
12679			ctl_set_aborted(&io->scsiio);
12680			break;
12681		case CTL_LUN_INJ_MEDIUM_ERR:
12682			ctl_set_medium_error(&io->scsiio);
12683			break;
12684		case CTL_LUN_INJ_UA:
12685			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12686			 * OCCURRED */
12687			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12688			break;
12689		case CTL_LUN_INJ_CUSTOM:
12690			/*
12691			 * We're assuming the user knows what he is doing.
12692			 * Just copy the sense information without doing
12693			 * checks.
12694			 */
12695			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12696			      ctl_min(sizeof(desc->custom_sense),
12697				      sizeof(io->scsiio.sense_data)));
12698			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12699			io->scsiio.sense_len = SSD_FULL_SIZE;
12700			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12701			break;
12702		case CTL_LUN_INJ_NONE:
12703		default:
12704			/*
12705			 * If this is an error injection type we don't know
12706			 * about, clear the continuous flag (if it is set)
12707			 * so it will get deleted below.
12708			 */
12709			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12710			break;
12711		}
12712		/*
12713		 * By default, each error injection action is a one-shot
12714		 */
12715		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12716			continue;
12717
12718		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12719
12720		free(desc, M_CTL);
12721	}
12722}
12723
12724#ifdef CTL_IO_DELAY
12725static void
12726ctl_datamove_timer_wakeup(void *arg)
12727{
12728	union ctl_io *io;
12729
12730	io = (union ctl_io *)arg;
12731
12732	ctl_datamove(io);
12733}
12734#endif /* CTL_IO_DELAY */
12735
12736void
12737ctl_datamove(union ctl_io *io)
12738{
12739	void (*fe_datamove)(union ctl_io *io);
12740
12741	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12742
12743	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12744
12745#ifdef CTL_TIME_IO
12746	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12747		char str[256];
12748		char path_str[64];
12749		struct sbuf sb;
12750
12751		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12752		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12753
12754		sbuf_cat(&sb, path_str);
12755		switch (io->io_hdr.io_type) {
12756		case CTL_IO_SCSI:
12757			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12758			sbuf_printf(&sb, "\n");
12759			sbuf_cat(&sb, path_str);
12760			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12761				    io->scsiio.tag_num, io->scsiio.tag_type);
12762			break;
12763		case CTL_IO_TASK:
12764			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12765				    "Tag Type: %d\n", io->taskio.task_action,
12766				    io->taskio.tag_num, io->taskio.tag_type);
12767			break;
12768		default:
12769			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12770			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12771			break;
12772		}
12773		sbuf_cat(&sb, path_str);
12774		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12775			    (intmax_t)time_uptime - io->io_hdr.start_time);
12776		sbuf_finish(&sb);
12777		printf("%s", sbuf_data(&sb));
12778	}
12779#endif /* CTL_TIME_IO */
12780
12781#ifdef CTL_IO_DELAY
12782	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12783		struct ctl_lun *lun;
12784
12785		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12786
12787		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12788	} else {
12789		struct ctl_lun *lun;
12790
12791		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12792		if ((lun != NULL)
12793		 && (lun->delay_info.datamove_delay > 0)) {
12794			struct callout *callout;
12795
12796			callout = (struct callout *)&io->io_hdr.timer_bytes;
12797			callout_init(callout, /*mpsafe*/ 1);
12798			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12799			callout_reset(callout,
12800				      lun->delay_info.datamove_delay * hz,
12801				      ctl_datamove_timer_wakeup, io);
12802			if (lun->delay_info.datamove_type ==
12803			    CTL_DELAY_TYPE_ONESHOT)
12804				lun->delay_info.datamove_delay = 0;
12805			return;
12806		}
12807	}
12808#endif
12809
12810	/*
12811	 * This command has been aborted.  Set the port status, so we fail
12812	 * the data move.
12813	 */
12814	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12815		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12816		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12817		       io->io_hdr.nexus.targ_port,
12818		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12819		       io->io_hdr.nexus.targ_lun);
12820		io->io_hdr.port_status = 31337;
12821		/*
12822		 * Note that the backend, in this case, will get the
12823		 * callback in its context.  In other cases it may get
12824		 * called in the frontend's interrupt thread context.
12825		 */
12826		io->scsiio.be_move_done(io);
12827		return;
12828	}
12829
12830	/*
12831	 * If we're in XFER mode and this I/O is from the other shelf
12832	 * controller, we need to send the DMA to the other side to
12833	 * actually transfer the data to/from the host.  In serialize only
12834	 * mode the transfer happens below CTL and ctl_datamove() is only
12835	 * called on the machine that originally received the I/O.
12836	 */
12837	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12838	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12839		union ctl_ha_msg msg;
12840		uint32_t sg_entries_sent;
12841		int do_sg_copy;
12842		int i;
12843
12844		memset(&msg, 0, sizeof(msg));
12845		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12846		msg.hdr.original_sc = io->io_hdr.original_sc;
12847		msg.hdr.serializing_sc = io;
12848		msg.hdr.nexus = io->io_hdr.nexus;
12849		msg.dt.flags = io->io_hdr.flags;
12850		/*
12851		 * We convert everything into a S/G list here.  We can't
12852		 * pass by reference, only by value between controllers.
12853		 * So we can't pass a pointer to the S/G list, only as many
12854		 * S/G entries as we can fit in here.  If it's possible for
12855		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12856		 * then we need to break this up into multiple transfers.
12857		 */
12858		if (io->scsiio.kern_sg_entries == 0) {
12859			msg.dt.kern_sg_entries = 1;
12860			/*
12861			 * If this is in cached memory, flush the cache
12862			 * before we send the DMA request to the other
12863			 * controller.  We want to do this in either the
12864			 * read or the write case.  The read case is
12865			 * straightforward.  In the write case, we want to
12866			 * make sure nothing is in the local cache that
12867			 * could overwrite the DMAed data.
12868			 */
12869			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12870				/*
12871				 * XXX KDM use bus_dmamap_sync() here.
12872				 */
12873			}
12874
12875			/*
12876			 * Convert to a physical address if this is a
12877			 * virtual address.
12878			 */
12879			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12880				msg.dt.sg_list[0].addr =
12881					io->scsiio.kern_data_ptr;
12882			} else {
12883				/*
12884				 * XXX KDM use busdma here!
12885				 */
12886#if 0
12887				msg.dt.sg_list[0].addr = (void *)
12888					vtophys(io->scsiio.kern_data_ptr);
12889#endif
12890			}
12891
12892			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12893			do_sg_copy = 0;
12894		} else {
12895			struct ctl_sg_entry *sgl;
12896
12897			do_sg_copy = 1;
12898			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12899			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12900			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12901				/*
12902				 * XXX KDM use bus_dmamap_sync() here.
12903				 */
12904			}
12905		}
12906
12907		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12908		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12909		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12910		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12911		msg.dt.sg_sequence = 0;
12912
12913		/*
12914		 * Loop until we've sent all of the S/G entries.  On the
12915		 * other end, we'll recompose these S/G entries into one
12916		 * contiguous list before passing it to the
12917		 */
12918		for (sg_entries_sent = 0; sg_entries_sent <
12919		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12920			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12921				sizeof(msg.dt.sg_list[0])),
12922				msg.dt.kern_sg_entries - sg_entries_sent);
12923
12924			if (do_sg_copy != 0) {
12925				struct ctl_sg_entry *sgl;
12926				int j;
12927
12928				sgl = (struct ctl_sg_entry *)
12929					io->scsiio.kern_data_ptr;
12930				/*
12931				 * If this is in cached memory, flush the cache
12932				 * before we send the DMA request to the other
12933				 * controller.  We want to do this in either
12934				 * the * read or the write case.  The read
12935				 * case is straightforward.  In the write
12936				 * case, we want to make sure nothing is
12937				 * in the local cache that could overwrite
12938				 * the DMAed data.
12939				 */
12940
12941				for (i = sg_entries_sent, j = 0;
12942				     i < msg.dt.cur_sg_entries; i++, j++) {
12943					if ((io->io_hdr.flags &
12944					     CTL_FLAG_NO_DATASYNC) == 0) {
12945						/*
12946						 * XXX KDM use bus_dmamap_sync()
12947						 */
12948					}
12949					if ((io->io_hdr.flags &
12950					     CTL_FLAG_BUS_ADDR) == 0) {
12951						/*
12952						 * XXX KDM use busdma.
12953						 */
12954#if 0
12955						msg.dt.sg_list[j].addr =(void *)
12956						       vtophys(sgl[i].addr);
12957#endif
12958					} else {
12959						msg.dt.sg_list[j].addr =
12960							sgl[i].addr;
12961					}
12962					msg.dt.sg_list[j].len = sgl[i].len;
12963				}
12964			}
12965
12966			sg_entries_sent += msg.dt.cur_sg_entries;
12967			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12968				msg.dt.sg_last = 1;
12969			else
12970				msg.dt.sg_last = 0;
12971
12972			/*
12973			 * XXX KDM drop and reacquire the lock here?
12974			 */
12975			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12976			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12977				/*
12978				 * XXX do something here.
12979				 */
12980			}
12981
12982			msg.dt.sent_sg_entries = sg_entries_sent;
12983		}
12984		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12985		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12986			ctl_failover_io(io, /*have_lock*/ 0);
12987
12988	} else {
12989
12990		/*
12991		 * Lookup the fe_datamove() function for this particular
12992		 * front end.
12993		 */
12994		fe_datamove =
12995		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12996
12997		fe_datamove(io);
12998	}
12999}
13000
13001static void
13002ctl_send_datamove_done(union ctl_io *io, int have_lock)
13003{
13004	union ctl_ha_msg msg;
13005	int isc_status;
13006
13007	memset(&msg, 0, sizeof(msg));
13008
13009	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13010	msg.hdr.original_sc = io;
13011	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13012	msg.hdr.nexus = io->io_hdr.nexus;
13013	msg.hdr.status = io->io_hdr.status;
13014	msg.scsi.tag_num = io->scsiio.tag_num;
13015	msg.scsi.tag_type = io->scsiio.tag_type;
13016	msg.scsi.scsi_status = io->scsiio.scsi_status;
13017	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13018	       sizeof(io->scsiio.sense_data));
13019	msg.scsi.sense_len = io->scsiio.sense_len;
13020	msg.scsi.sense_residual = io->scsiio.sense_residual;
13021	msg.scsi.fetd_status = io->io_hdr.port_status;
13022	msg.scsi.residual = io->scsiio.residual;
13023	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13024
13025	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13026		ctl_failover_io(io, /*have_lock*/ have_lock);
13027		return;
13028	}
13029
13030	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13031	if (isc_status > CTL_HA_STATUS_SUCCESS) {
13032		/* XXX do something if this fails */
13033	}
13034
13035}
13036
13037/*
13038 * The DMA to the remote side is done, now we need to tell the other side
13039 * we're done so it can continue with its data movement.
13040 */
13041static void
13042ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13043{
13044	union ctl_io *io;
13045
13046	io = rq->context;
13047
13048	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13049		printf("%s: ISC DMA write failed with error %d", __func__,
13050		       rq->ret);
13051		ctl_set_internal_failure(&io->scsiio,
13052					 /*sks_valid*/ 1,
13053					 /*retry_count*/ rq->ret);
13054	}
13055
13056	ctl_dt_req_free(rq);
13057
13058	/*
13059	 * In this case, we had to malloc the memory locally.  Free it.
13060	 */
13061	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13062		int i;
13063		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13064			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13065	}
13066	/*
13067	 * The data is in local and remote memory, so now we need to send
13068	 * status (good or back) back to the other side.
13069	 */
13070	ctl_send_datamove_done(io, /*have_lock*/ 0);
13071}
13072
13073/*
13074 * We've moved the data from the host/controller into local memory.  Now we
13075 * need to push it over to the remote controller's memory.
13076 */
13077static int
13078ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13079{
13080	int retval;
13081
13082	retval = 0;
13083
13084	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13085					  ctl_datamove_remote_write_cb);
13086
13087	return (retval);
13088}
13089
13090static void
13091ctl_datamove_remote_write(union ctl_io *io)
13092{
13093	int retval;
13094	void (*fe_datamove)(union ctl_io *io);
13095
13096	/*
13097	 * - Get the data from the host/HBA into local memory.
13098	 * - DMA memory from the local controller to the remote controller.
13099	 * - Send status back to the remote controller.
13100	 */
13101
13102	retval = ctl_datamove_remote_sgl_setup(io);
13103	if (retval != 0)
13104		return;
13105
13106	/* Switch the pointer over so the FETD knows what to do */
13107	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13108
13109	/*
13110	 * Use a custom move done callback, since we need to send completion
13111	 * back to the other controller, not to the backend on this side.
13112	 */
13113	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13114
13115	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13116
13117	fe_datamove(io);
13118
13119	return;
13120
13121}
13122
13123static int
13124ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13125{
13126#if 0
13127	char str[256];
13128	char path_str[64];
13129	struct sbuf sb;
13130#endif
13131
13132	/*
13133	 * In this case, we had to malloc the memory locally.  Free it.
13134	 */
13135	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13136		int i;
13137		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13138			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13139	}
13140
13141#if 0
13142	scsi_path_string(io, path_str, sizeof(path_str));
13143	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13144	sbuf_cat(&sb, path_str);
13145	scsi_command_string(&io->scsiio, NULL, &sb);
13146	sbuf_printf(&sb, "\n");
13147	sbuf_cat(&sb, path_str);
13148	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13149		    io->scsiio.tag_num, io->scsiio.tag_type);
13150	sbuf_cat(&sb, path_str);
13151	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13152		    io->io_hdr.flags, io->io_hdr.status);
13153	sbuf_finish(&sb);
13154	printk("%s", sbuf_data(&sb));
13155#endif
13156
13157
13158	/*
13159	 * The read is done, now we need to send status (good or bad) back
13160	 * to the other side.
13161	 */
13162	ctl_send_datamove_done(io, /*have_lock*/ 0);
13163
13164	return (0);
13165}
13166
13167static void
13168ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13169{
13170	union ctl_io *io;
13171	void (*fe_datamove)(union ctl_io *io);
13172
13173	io = rq->context;
13174
13175	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13176		printf("%s: ISC DMA read failed with error %d", __func__,
13177		       rq->ret);
13178		ctl_set_internal_failure(&io->scsiio,
13179					 /*sks_valid*/ 1,
13180					 /*retry_count*/ rq->ret);
13181	}
13182
13183	ctl_dt_req_free(rq);
13184
13185	/* Switch the pointer over so the FETD knows what to do */
13186	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13187
13188	/*
13189	 * Use a custom move done callback, since we need to send completion
13190	 * back to the other controller, not to the backend on this side.
13191	 */
13192	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13193
13194	/* XXX KDM add checks like the ones in ctl_datamove? */
13195
13196	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13197
13198	fe_datamove(io);
13199}
13200
13201static int
13202ctl_datamove_remote_sgl_setup(union ctl_io *io)
13203{
13204	struct ctl_sg_entry *local_sglist, *remote_sglist;
13205	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13206	struct ctl_softc *softc;
13207	int retval;
13208	int i;
13209
13210	retval = 0;
13211	softc = control_softc;
13212
13213	local_sglist = io->io_hdr.local_sglist;
13214	local_dma_sglist = io->io_hdr.local_dma_sglist;
13215	remote_sglist = io->io_hdr.remote_sglist;
13216	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13217
13218	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13219		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13220			local_sglist[i].len = remote_sglist[i].len;
13221
13222			/*
13223			 * XXX Detect the situation where the RS-level I/O
13224			 * redirector on the other side has already read the
13225			 * data off of the AOR RS on this side, and
13226			 * transferred it to remote (mirror) memory on the
13227			 * other side.  Since we already have the data in
13228			 * memory here, we just need to use it.
13229			 *
13230			 * XXX KDM this can probably be removed once we
13231			 * get the cache device code in and take the
13232			 * current AOR implementation out.
13233			 */
13234#ifdef NEEDTOPORT
13235			if ((remote_sglist[i].addr >=
13236			     (void *)vtophys(softc->mirr->addr))
13237			 && (remote_sglist[i].addr <
13238			     ((void *)vtophys(softc->mirr->addr) +
13239			     CacheMirrorOffset))) {
13240				local_sglist[i].addr = remote_sglist[i].addr -
13241					CacheMirrorOffset;
13242				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13243				     CTL_FLAG_DATA_IN)
13244					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13245			} else {
13246				local_sglist[i].addr = remote_sglist[i].addr +
13247					CacheMirrorOffset;
13248			}
13249#endif
13250#if 0
13251			printf("%s: local %p, remote %p, len %d\n",
13252			       __func__, local_sglist[i].addr,
13253			       remote_sglist[i].addr, local_sglist[i].len);
13254#endif
13255		}
13256	} else {
13257		uint32_t len_to_go;
13258
13259		/*
13260		 * In this case, we don't have automatically allocated
13261		 * memory for this I/O on this controller.  This typically
13262		 * happens with internal CTL I/O -- e.g. inquiry, mode
13263		 * sense, etc.  Anything coming from RAIDCore will have
13264		 * a mirror area available.
13265		 */
13266		len_to_go = io->scsiio.kern_data_len;
13267
13268		/*
13269		 * Clear the no datasync flag, we have to use malloced
13270		 * buffers.
13271		 */
13272		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13273
13274		/*
13275		 * The difficult thing here is that the size of the various
13276		 * S/G segments may be different than the size from the
13277		 * remote controller.  That'll make it harder when DMAing
13278		 * the data back to the other side.
13279		 */
13280		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13281		     sizeof(io->io_hdr.remote_sglist[0])) &&
13282		     (len_to_go > 0); i++) {
13283			local_sglist[i].len = ctl_min(len_to_go, 131072);
13284			CTL_SIZE_8B(local_dma_sglist[i].len,
13285				    local_sglist[i].len);
13286			local_sglist[i].addr =
13287				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13288
13289			local_dma_sglist[i].addr = local_sglist[i].addr;
13290
13291			if (local_sglist[i].addr == NULL) {
13292				int j;
13293
13294				printf("malloc failed for %zd bytes!",
13295				       local_dma_sglist[i].len);
13296				for (j = 0; j < i; j++) {
13297					free(local_sglist[j].addr, M_CTL);
13298				}
13299				ctl_set_internal_failure(&io->scsiio,
13300							 /*sks_valid*/ 1,
13301							 /*retry_count*/ 4857);
13302				retval = 1;
13303				goto bailout_error;
13304
13305			}
13306			/* XXX KDM do we need a sync here? */
13307
13308			len_to_go -= local_sglist[i].len;
13309		}
13310		/*
13311		 * Reset the number of S/G entries accordingly.  The
13312		 * original number of S/G entries is available in
13313		 * rem_sg_entries.
13314		 */
13315		io->scsiio.kern_sg_entries = i;
13316
13317#if 0
13318		printf("%s: kern_sg_entries = %d\n", __func__,
13319		       io->scsiio.kern_sg_entries);
13320		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13321			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13322			       local_sglist[i].addr, local_sglist[i].len,
13323			       local_dma_sglist[i].len);
13324#endif
13325	}
13326
13327
13328	return (retval);
13329
13330bailout_error:
13331
13332	ctl_send_datamove_done(io, /*have_lock*/ 0);
13333
13334	return (retval);
13335}
13336
13337static int
13338ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13339			 ctl_ha_dt_cb callback)
13340{
13341	struct ctl_ha_dt_req *rq;
13342	struct ctl_sg_entry *remote_sglist, *local_sglist;
13343	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13344	uint32_t local_used, remote_used, total_used;
13345	int retval;
13346	int i, j;
13347
13348	retval = 0;
13349
13350	rq = ctl_dt_req_alloc();
13351
13352	/*
13353	 * If we failed to allocate the request, and if the DMA didn't fail
13354	 * anyway, set busy status.  This is just a resource allocation
13355	 * failure.
13356	 */
13357	if ((rq == NULL)
13358	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13359		ctl_set_busy(&io->scsiio);
13360
13361	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13362
13363		if (rq != NULL)
13364			ctl_dt_req_free(rq);
13365
13366		/*
13367		 * The data move failed.  We need to return status back
13368		 * to the other controller.  No point in trying to DMA
13369		 * data to the remote controller.
13370		 */
13371
13372		ctl_send_datamove_done(io, /*have_lock*/ 0);
13373
13374		retval = 1;
13375
13376		goto bailout;
13377	}
13378
13379	local_sglist = io->io_hdr.local_sglist;
13380	local_dma_sglist = io->io_hdr.local_dma_sglist;
13381	remote_sglist = io->io_hdr.remote_sglist;
13382	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13383	local_used = 0;
13384	remote_used = 0;
13385	total_used = 0;
13386
13387	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13388		rq->ret = CTL_HA_STATUS_SUCCESS;
13389		rq->context = io;
13390		callback(rq);
13391		goto bailout;
13392	}
13393
13394	/*
13395	 * Pull/push the data over the wire from/to the other controller.
13396	 * This takes into account the possibility that the local and
13397	 * remote sglists may not be identical in terms of the size of
13398	 * the elements and the number of elements.
13399	 *
13400	 * One fundamental assumption here is that the length allocated for
13401	 * both the local and remote sglists is identical.  Otherwise, we've
13402	 * essentially got a coding error of some sort.
13403	 */
13404	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13405		int isc_ret;
13406		uint32_t cur_len, dma_length;
13407		uint8_t *tmp_ptr;
13408
13409		rq->id = CTL_HA_DATA_CTL;
13410		rq->command = command;
13411		rq->context = io;
13412
13413		/*
13414		 * Both pointers should be aligned.  But it is possible
13415		 * that the allocation length is not.  They should both
13416		 * also have enough slack left over at the end, though,
13417		 * to round up to the next 8 byte boundary.
13418		 */
13419		cur_len = ctl_min(local_sglist[i].len - local_used,
13420				  remote_sglist[j].len - remote_used);
13421
13422		/*
13423		 * In this case, we have a size issue and need to decrease
13424		 * the size, except in the case where we actually have less
13425		 * than 8 bytes left.  In that case, we need to increase
13426		 * the DMA length to get the last bit.
13427		 */
13428		if ((cur_len & 0x7) != 0) {
13429			if (cur_len > 0x7) {
13430				cur_len = cur_len - (cur_len & 0x7);
13431				dma_length = cur_len;
13432			} else {
13433				CTL_SIZE_8B(dma_length, cur_len);
13434			}
13435
13436		} else
13437			dma_length = cur_len;
13438
13439		/*
13440		 * If we had to allocate memory for this I/O, instead of using
13441		 * the non-cached mirror memory, we'll need to flush the cache
13442		 * before trying to DMA to the other controller.
13443		 *
13444		 * We could end up doing this multiple times for the same
13445		 * segment if we have a larger local segment than remote
13446		 * segment.  That shouldn't be an issue.
13447		 */
13448		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13449			/*
13450			 * XXX KDM use bus_dmamap_sync() here.
13451			 */
13452		}
13453
13454		rq->size = dma_length;
13455
13456		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13457		tmp_ptr += local_used;
13458
13459		/* Use physical addresses when talking to ISC hardware */
13460		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13461			/* XXX KDM use busdma */
13462#if 0
13463			rq->local = vtophys(tmp_ptr);
13464#endif
13465		} else
13466			rq->local = tmp_ptr;
13467
13468		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13469		tmp_ptr += remote_used;
13470		rq->remote = tmp_ptr;
13471
13472		rq->callback = NULL;
13473
13474		local_used += cur_len;
13475		if (local_used >= local_sglist[i].len) {
13476			i++;
13477			local_used = 0;
13478		}
13479
13480		remote_used += cur_len;
13481		if (remote_used >= remote_sglist[j].len) {
13482			j++;
13483			remote_used = 0;
13484		}
13485		total_used += cur_len;
13486
13487		if (total_used >= io->scsiio.kern_data_len)
13488			rq->callback = callback;
13489
13490		if ((rq->size & 0x7) != 0) {
13491			printf("%s: warning: size %d is not on 8b boundary\n",
13492			       __func__, rq->size);
13493		}
13494		if (((uintptr_t)rq->local & 0x7) != 0) {
13495			printf("%s: warning: local %p not on 8b boundary\n",
13496			       __func__, rq->local);
13497		}
13498		if (((uintptr_t)rq->remote & 0x7) != 0) {
13499			printf("%s: warning: remote %p not on 8b boundary\n",
13500			       __func__, rq->local);
13501		}
13502#if 0
13503		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13504		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13505		       rq->local, rq->remote, rq->size);
13506#endif
13507
13508		isc_ret = ctl_dt_single(rq);
13509		if (isc_ret == CTL_HA_STATUS_WAIT)
13510			continue;
13511
13512		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13513			rq->ret = CTL_HA_STATUS_SUCCESS;
13514		} else {
13515			rq->ret = isc_ret;
13516		}
13517		callback(rq);
13518		goto bailout;
13519	}
13520
13521bailout:
13522	return (retval);
13523
13524}
13525
13526static void
13527ctl_datamove_remote_read(union ctl_io *io)
13528{
13529	int retval;
13530	int i;
13531
13532	/*
13533	 * This will send an error to the other controller in the case of a
13534	 * failure.
13535	 */
13536	retval = ctl_datamove_remote_sgl_setup(io);
13537	if (retval != 0)
13538		return;
13539
13540	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13541					  ctl_datamove_remote_read_cb);
13542	if ((retval != 0)
13543	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13544		/*
13545		 * Make sure we free memory if there was an error..  The
13546		 * ctl_datamove_remote_xfer() function will send the
13547		 * datamove done message, or call the callback with an
13548		 * error if there is a problem.
13549		 */
13550		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13551			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13552	}
13553
13554	return;
13555}
13556
13557/*
13558 * Process a datamove request from the other controller.  This is used for
13559 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13560 * first.  Once that is complete, the data gets DMAed into the remote
13561 * controller's memory.  For reads, we DMA from the remote controller's
13562 * memory into our memory first, and then move it out to the FETD.
13563 */
13564static void
13565ctl_datamove_remote(union ctl_io *io)
13566{
13567	struct ctl_softc *softc;
13568
13569	softc = control_softc;
13570
13571	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13572
13573	/*
13574	 * Note that we look for an aborted I/O here, but don't do some of
13575	 * the other checks that ctl_datamove() normally does.
13576	 * We don't need to run the datamove delay code, since that should
13577	 * have been done if need be on the other controller.
13578	 */
13579	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13580		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13581		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13582		       io->io_hdr.nexus.targ_port,
13583		       io->io_hdr.nexus.targ_target.id,
13584		       io->io_hdr.nexus.targ_lun);
13585		io->io_hdr.port_status = 31338;
13586		ctl_send_datamove_done(io, /*have_lock*/ 0);
13587		return;
13588	}
13589
13590	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13591		ctl_datamove_remote_write(io);
13592	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13593		ctl_datamove_remote_read(io);
13594	} else {
13595		union ctl_ha_msg msg;
13596		struct scsi_sense_data *sense;
13597		uint8_t sks[3];
13598		int retry_count;
13599
13600		memset(&msg, 0, sizeof(msg));
13601
13602		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13603		msg.hdr.status = CTL_SCSI_ERROR;
13604		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13605
13606		retry_count = 4243;
13607
13608		sense = &msg.scsi.sense_data;
13609		sks[0] = SSD_SCS_VALID;
13610		sks[1] = (retry_count >> 8) & 0xff;
13611		sks[2] = retry_count & 0xff;
13612
13613		/* "Internal target failure" */
13614		scsi_set_sense_data(sense,
13615				    /*sense_format*/ SSD_TYPE_NONE,
13616				    /*current_error*/ 1,
13617				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13618				    /*asc*/ 0x44,
13619				    /*ascq*/ 0x00,
13620				    /*type*/ SSD_ELEM_SKS,
13621				    /*size*/ sizeof(sks),
13622				    /*data*/ sks,
13623				    SSD_ELEM_NONE);
13624
13625		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13626		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13627			ctl_failover_io(io, /*have_lock*/ 1);
13628			return;
13629		}
13630
13631		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13632		    CTL_HA_STATUS_SUCCESS) {
13633			/* XXX KDM what to do if this fails? */
13634		}
13635		return;
13636	}
13637
13638}
13639
13640static int
13641ctl_process_done(union ctl_io *io)
13642{
13643	struct ctl_lun *lun;
13644	struct ctl_softc *ctl_softc;
13645	void (*fe_done)(union ctl_io *io);
13646	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13647
13648	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13649
13650	fe_done =
13651	    control_softc->ctl_ports[targ_port]->fe_done;
13652
13653#ifdef CTL_TIME_IO
13654	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13655		char str[256];
13656		char path_str[64];
13657		struct sbuf sb;
13658
13659		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13660		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13661
13662		sbuf_cat(&sb, path_str);
13663		switch (io->io_hdr.io_type) {
13664		case CTL_IO_SCSI:
13665			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13666			sbuf_printf(&sb, "\n");
13667			sbuf_cat(&sb, path_str);
13668			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13669				    io->scsiio.tag_num, io->scsiio.tag_type);
13670			break;
13671		case CTL_IO_TASK:
13672			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13673				    "Tag Type: %d\n", io->taskio.task_action,
13674				    io->taskio.tag_num, io->taskio.tag_type);
13675			break;
13676		default:
13677			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13678			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13679			break;
13680		}
13681		sbuf_cat(&sb, path_str);
13682		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13683			    (intmax_t)time_uptime - io->io_hdr.start_time);
13684		sbuf_finish(&sb);
13685		printf("%s", sbuf_data(&sb));
13686	}
13687#endif /* CTL_TIME_IO */
13688
13689	switch (io->io_hdr.io_type) {
13690	case CTL_IO_SCSI:
13691		break;
13692	case CTL_IO_TASK:
13693		if (bootverbose || verbose > 0)
13694			ctl_io_error_print(io, NULL);
13695		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13696			ctl_free_io(io);
13697		else
13698			fe_done(io);
13699		return (CTL_RETVAL_COMPLETE);
13700		break;
13701	default:
13702		printf("ctl_process_done: invalid io type %d\n",
13703		       io->io_hdr.io_type);
13704		panic("ctl_process_done: invalid io type %d\n",
13705		      io->io_hdr.io_type);
13706		break; /* NOTREACHED */
13707	}
13708
13709	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13710	if (lun == NULL) {
13711		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13712				 io->io_hdr.nexus.targ_mapped_lun));
13713		fe_done(io);
13714		goto bailout;
13715	}
13716	ctl_softc = lun->ctl_softc;
13717
13718	mtx_lock(&lun->lun_lock);
13719
13720	/*
13721	 * Check to see if we have any errors to inject here.  We only
13722	 * inject errors for commands that don't already have errors set.
13723	 */
13724	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13725	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13726		ctl_inject_error(lun, io);
13727
13728	/*
13729	 * XXX KDM how do we treat commands that aren't completed
13730	 * successfully?
13731	 *
13732	 * XXX KDM should we also track I/O latency?
13733	 */
13734	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13735	    io->io_hdr.io_type == CTL_IO_SCSI) {
13736#ifdef CTL_TIME_IO
13737		struct bintime cur_bt;
13738#endif
13739		int type;
13740
13741		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13742		    CTL_FLAG_DATA_IN)
13743			type = CTL_STATS_READ;
13744		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13745		    CTL_FLAG_DATA_OUT)
13746			type = CTL_STATS_WRITE;
13747		else
13748			type = CTL_STATS_NO_IO;
13749
13750		lun->stats.ports[targ_port].bytes[type] +=
13751		    io->scsiio.kern_total_len;
13752		lun->stats.ports[targ_port].operations[type]++;
13753#ifdef CTL_TIME_IO
13754		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13755		   &io->io_hdr.dma_bt);
13756		lun->stats.ports[targ_port].num_dmas[type] +=
13757		    io->io_hdr.num_dmas;
13758		getbintime(&cur_bt);
13759		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13760		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13761#endif
13762	}
13763
13764	/*
13765	 * Remove this from the OOA queue.
13766	 */
13767	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13768
13769	/*
13770	 * Run through the blocked queue on this LUN and see if anything
13771	 * has become unblocked, now that this transaction is done.
13772	 */
13773	ctl_check_blocked(lun);
13774
13775	/*
13776	 * If the LUN has been invalidated, free it if there is nothing
13777	 * left on its OOA queue.
13778	 */
13779	if ((lun->flags & CTL_LUN_INVALID)
13780	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13781		mtx_unlock(&lun->lun_lock);
13782		mtx_lock(&ctl_softc->ctl_lock);
13783		ctl_free_lun(lun);
13784		mtx_unlock(&ctl_softc->ctl_lock);
13785	} else
13786		mtx_unlock(&lun->lun_lock);
13787
13788	/*
13789	 * If this command has been aborted, make sure we set the status
13790	 * properly.  The FETD is responsible for freeing the I/O and doing
13791	 * whatever it needs to do to clean up its state.
13792	 */
13793	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13794		ctl_set_task_aborted(&io->scsiio);
13795
13796	/*
13797	 * We print out status for every task management command.  For SCSI
13798	 * commands, we filter out any unit attention errors; they happen
13799	 * on every boot, and would clutter up the log.  Note:  task
13800	 * management commands aren't printed here, they are printed above,
13801	 * since they should never even make it down here.
13802	 */
13803	switch (io->io_hdr.io_type) {
13804	case CTL_IO_SCSI: {
13805		int error_code, sense_key, asc, ascq;
13806
13807		sense_key = 0;
13808
13809		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13810		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13811			/*
13812			 * Since this is just for printing, no need to
13813			 * show errors here.
13814			 */
13815			scsi_extract_sense_len(&io->scsiio.sense_data,
13816					       io->scsiio.sense_len,
13817					       &error_code,
13818					       &sense_key,
13819					       &asc,
13820					       &ascq,
13821					       /*show_errors*/ 0);
13822		}
13823
13824		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13825		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13826		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13827		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13828
13829			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13830				ctl_softc->skipped_prints++;
13831			} else {
13832				uint32_t skipped_prints;
13833
13834				skipped_prints = ctl_softc->skipped_prints;
13835
13836				ctl_softc->skipped_prints = 0;
13837				ctl_softc->last_print_jiffies = time_uptime;
13838
13839				if (skipped_prints > 0) {
13840#ifdef NEEDTOPORT
13841					csevent_log(CSC_CTL | CSC_SHELF_SW |
13842					    CTL_ERROR_REPORT,
13843					    csevent_LogType_Trace,
13844					    csevent_Severity_Information,
13845					    csevent_AlertLevel_Green,
13846					    csevent_FRU_Firmware,
13847					    csevent_FRU_Unknown,
13848					    "High CTL error volume, %d prints "
13849					    "skipped", skipped_prints);
13850#endif
13851				}
13852				if (bootverbose || verbose > 0)
13853					ctl_io_error_print(io, NULL);
13854			}
13855		}
13856		break;
13857	}
13858	case CTL_IO_TASK:
13859		if (bootverbose || verbose > 0)
13860			ctl_io_error_print(io, NULL);
13861		break;
13862	default:
13863		break;
13864	}
13865
13866	/*
13867	 * Tell the FETD or the other shelf controller we're done with this
13868	 * command.  Note that only SCSI commands get to this point.  Task
13869	 * management commands are completed above.
13870	 *
13871	 * We only send status to the other controller if we're in XFER
13872	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13873	 * received the I/O (from CTL's perspective), and so the status is
13874	 * generated there.
13875	 *
13876	 * XXX KDM if we hold the lock here, we could cause a deadlock
13877	 * if the frontend comes back in in this context to queue
13878	 * something.
13879	 */
13880	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13881	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13882		union ctl_ha_msg msg;
13883
13884		memset(&msg, 0, sizeof(msg));
13885		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13886		msg.hdr.original_sc = io->io_hdr.original_sc;
13887		msg.hdr.nexus = io->io_hdr.nexus;
13888		msg.hdr.status = io->io_hdr.status;
13889		msg.scsi.scsi_status = io->scsiio.scsi_status;
13890		msg.scsi.tag_num = io->scsiio.tag_num;
13891		msg.scsi.tag_type = io->scsiio.tag_type;
13892		msg.scsi.sense_len = io->scsiio.sense_len;
13893		msg.scsi.sense_residual = io->scsiio.sense_residual;
13894		msg.scsi.residual = io->scsiio.residual;
13895		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13896		       sizeof(io->scsiio.sense_data));
13897		/*
13898		 * We copy this whether or not this is an I/O-related
13899		 * command.  Otherwise, we'd have to go and check to see
13900		 * whether it's a read/write command, and it really isn't
13901		 * worth it.
13902		 */
13903		memcpy(&msg.scsi.lbalen,
13904		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13905		       sizeof(msg.scsi.lbalen));
13906
13907		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13908				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13909			/* XXX do something here */
13910		}
13911
13912		ctl_free_io(io);
13913	} else
13914		fe_done(io);
13915
13916bailout:
13917
13918	return (CTL_RETVAL_COMPLETE);
13919}
13920
13921#ifdef CTL_WITH_CA
13922/*
13923 * Front end should call this if it doesn't do autosense.  When the request
13924 * sense comes back in from the initiator, we'll dequeue this and send it.
13925 */
13926int
13927ctl_queue_sense(union ctl_io *io)
13928{
13929	struct ctl_lun *lun;
13930	struct ctl_softc *ctl_softc;
13931	uint32_t initidx, targ_lun;
13932
13933	ctl_softc = control_softc;
13934
13935	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13936
13937	/*
13938	 * LUN lookup will likely move to the ctl_work_thread() once we
13939	 * have our new queueing infrastructure (that doesn't put things on
13940	 * a per-LUN queue initially).  That is so that we can handle
13941	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13942	 * can't deal with that right now.
13943	 */
13944	mtx_lock(&ctl_softc->ctl_lock);
13945
13946	/*
13947	 * If we don't have a LUN for this, just toss the sense
13948	 * information.
13949	 */
13950	targ_lun = io->io_hdr.nexus.targ_lun;
13951	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13952	if ((targ_lun < CTL_MAX_LUNS)
13953	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13954		lun = ctl_softc->ctl_luns[targ_lun];
13955	else
13956		goto bailout;
13957
13958	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13959
13960	mtx_lock(&lun->lun_lock);
13961	/*
13962	 * Already have CA set for this LUN...toss the sense information.
13963	 */
13964	if (ctl_is_set(lun->have_ca, initidx)) {
13965		mtx_unlock(&lun->lun_lock);
13966		goto bailout;
13967	}
13968
13969	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13970	       ctl_min(sizeof(lun->pending_sense[initidx]),
13971	       sizeof(io->scsiio.sense_data)));
13972	ctl_set_mask(lun->have_ca, initidx);
13973	mtx_unlock(&lun->lun_lock);
13974
13975bailout:
13976	mtx_unlock(&ctl_softc->ctl_lock);
13977
13978	ctl_free_io(io);
13979
13980	return (CTL_RETVAL_COMPLETE);
13981}
13982#endif
13983
13984/*
13985 * Primary command inlet from frontend ports.  All SCSI and task I/O
13986 * requests must go through this function.
13987 */
13988int
13989ctl_queue(union ctl_io *io)
13990{
13991	struct ctl_softc *ctl_softc;
13992
13993	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13994
13995	ctl_softc = control_softc;
13996
13997#ifdef CTL_TIME_IO
13998	io->io_hdr.start_time = time_uptime;
13999	getbintime(&io->io_hdr.start_bt);
14000#endif /* CTL_TIME_IO */
14001
14002	/* Map FE-specific LUN ID into global one. */
14003	io->io_hdr.nexus.targ_mapped_lun =
14004	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
14005
14006	switch (io->io_hdr.io_type) {
14007	case CTL_IO_SCSI:
14008	case CTL_IO_TASK:
14009		ctl_enqueue_incoming(io);
14010		break;
14011	default:
14012		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14013		return (EINVAL);
14014	}
14015
14016	return (CTL_RETVAL_COMPLETE);
14017}
14018
14019#ifdef CTL_IO_DELAY
14020static void
14021ctl_done_timer_wakeup(void *arg)
14022{
14023	union ctl_io *io;
14024
14025	io = (union ctl_io *)arg;
14026	ctl_done(io);
14027}
14028#endif /* CTL_IO_DELAY */
14029
14030void
14031ctl_done(union ctl_io *io)
14032{
14033	struct ctl_softc *ctl_softc;
14034
14035	ctl_softc = control_softc;
14036
14037	/*
14038	 * Enable this to catch duplicate completion issues.
14039	 */
14040#if 0
14041	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14042		printf("%s: type %d msg %d cdb %x iptl: "
14043		       "%d:%d:%d:%d tag 0x%04x "
14044		       "flag %#x status %x\n",
14045			__func__,
14046			io->io_hdr.io_type,
14047			io->io_hdr.msg_type,
14048			io->scsiio.cdb[0],
14049			io->io_hdr.nexus.initid.id,
14050			io->io_hdr.nexus.targ_port,
14051			io->io_hdr.nexus.targ_target.id,
14052			io->io_hdr.nexus.targ_lun,
14053			(io->io_hdr.io_type ==
14054			CTL_IO_TASK) ?
14055			io->taskio.tag_num :
14056			io->scsiio.tag_num,
14057		        io->io_hdr.flags,
14058			io->io_hdr.status);
14059	} else
14060		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14061#endif
14062
14063	/*
14064	 * This is an internal copy of an I/O, and should not go through
14065	 * the normal done processing logic.
14066	 */
14067	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14068		return;
14069
14070	/*
14071	 * We need to send a msg to the serializing shelf to finish the IO
14072	 * as well.  We don't send a finish message to the other shelf if
14073	 * this is a task management command.  Task management commands
14074	 * aren't serialized in the OOA queue, but rather just executed on
14075	 * both shelf controllers for commands that originated on that
14076	 * controller.
14077	 */
14078	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14079	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14080		union ctl_ha_msg msg_io;
14081
14082		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14083		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14084		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14085		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14086		}
14087		/* continue on to finish IO */
14088	}
14089#ifdef CTL_IO_DELAY
14090	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14091		struct ctl_lun *lun;
14092
14093		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14094
14095		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14096	} else {
14097		struct ctl_lun *lun;
14098
14099		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14100
14101		if ((lun != NULL)
14102		 && (lun->delay_info.done_delay > 0)) {
14103			struct callout *callout;
14104
14105			callout = (struct callout *)&io->io_hdr.timer_bytes;
14106			callout_init(callout, /*mpsafe*/ 1);
14107			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14108			callout_reset(callout,
14109				      lun->delay_info.done_delay * hz,
14110				      ctl_done_timer_wakeup, io);
14111			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14112				lun->delay_info.done_delay = 0;
14113			return;
14114		}
14115	}
14116#endif /* CTL_IO_DELAY */
14117
14118	ctl_enqueue_done(io);
14119}
14120
14121int
14122ctl_isc(struct ctl_scsiio *ctsio)
14123{
14124	struct ctl_lun *lun;
14125	int retval;
14126
14127	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14128
14129	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14130
14131	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14132
14133	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14134
14135	return (retval);
14136}
14137
14138
14139static void
14140ctl_work_thread(void *arg)
14141{
14142	struct ctl_thread *thr = (struct ctl_thread *)arg;
14143	struct ctl_softc *softc = thr->ctl_softc;
14144	union ctl_io *io;
14145	int retval;
14146
14147	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14148
14149	for (;;) {
14150		retval = 0;
14151
14152		/*
14153		 * We handle the queues in this order:
14154		 * - ISC
14155		 * - done queue (to free up resources, unblock other commands)
14156		 * - RtR queue
14157		 * - incoming queue
14158		 *
14159		 * If those queues are empty, we break out of the loop and
14160		 * go to sleep.
14161		 */
14162		mtx_lock(&thr->queue_lock);
14163		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14164		if (io != NULL) {
14165			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14166			mtx_unlock(&thr->queue_lock);
14167			ctl_handle_isc(io);
14168			continue;
14169		}
14170		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14171		if (io != NULL) {
14172			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14173			/* clear any blocked commands, call fe_done */
14174			mtx_unlock(&thr->queue_lock);
14175			retval = ctl_process_done(io);
14176			continue;
14177		}
14178		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14179		if (io != NULL) {
14180			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14181			mtx_unlock(&thr->queue_lock);
14182			if (io->io_hdr.io_type == CTL_IO_TASK)
14183				ctl_run_task(io);
14184			else
14185				ctl_scsiio_precheck(softc, &io->scsiio);
14186			continue;
14187		}
14188		if (!ctl_pause_rtr) {
14189			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14190			if (io != NULL) {
14191				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14192				mtx_unlock(&thr->queue_lock);
14193				retval = ctl_scsiio(&io->scsiio);
14194				if (retval != CTL_RETVAL_COMPLETE)
14195					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14196				continue;
14197			}
14198		}
14199
14200		/* Sleep until we have something to do. */
14201		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14202	}
14203}
14204
14205static void
14206ctl_lun_thread(void *arg)
14207{
14208	struct ctl_softc *softc = (struct ctl_softc *)arg;
14209	struct ctl_be_lun *be_lun;
14210	int retval;
14211
14212	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14213
14214	for (;;) {
14215		retval = 0;
14216		mtx_lock(&softc->ctl_lock);
14217		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14218		if (be_lun != NULL) {
14219			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14220			mtx_unlock(&softc->ctl_lock);
14221			ctl_create_lun(be_lun);
14222			continue;
14223		}
14224
14225		/* Sleep until we have something to do. */
14226		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14227		    PDROP | PRIBIO, "-", 0);
14228	}
14229}
14230
14231static void
14232ctl_enqueue_incoming(union ctl_io *io)
14233{
14234	struct ctl_softc *softc = control_softc;
14235	struct ctl_thread *thr;
14236	u_int idx;
14237
14238	idx = (io->io_hdr.nexus.targ_port * 127 +
14239	       io->io_hdr.nexus.initid.id) % worker_threads;
14240	thr = &softc->threads[idx];
14241	mtx_lock(&thr->queue_lock);
14242	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14243	mtx_unlock(&thr->queue_lock);
14244	wakeup(thr);
14245}
14246
14247static void
14248ctl_enqueue_rtr(union ctl_io *io)
14249{
14250	struct ctl_softc *softc = control_softc;
14251	struct ctl_thread *thr;
14252
14253	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14254	mtx_lock(&thr->queue_lock);
14255	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14256	mtx_unlock(&thr->queue_lock);
14257	wakeup(thr);
14258}
14259
14260static void
14261ctl_enqueue_done(union ctl_io *io)
14262{
14263	struct ctl_softc *softc = control_softc;
14264	struct ctl_thread *thr;
14265
14266	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14267	mtx_lock(&thr->queue_lock);
14268	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14269	mtx_unlock(&thr->queue_lock);
14270	wakeup(thr);
14271}
14272
14273static void
14274ctl_enqueue_isc(union ctl_io *io)
14275{
14276	struct ctl_softc *softc = control_softc;
14277	struct ctl_thread *thr;
14278
14279	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14280	mtx_lock(&thr->queue_lock);
14281	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14282	mtx_unlock(&thr->queue_lock);
14283	wakeup(thr);
14284}
14285
14286/* Initialization and failover */
14287
14288void
14289ctl_init_isc_msg(void)
14290{
14291	printf("CTL: Still calling this thing\n");
14292}
14293
14294/*
14295 * Init component
14296 * 	Initializes component into configuration defined by bootMode
14297 *	(see hasc-sv.c)
14298 *  	returns hasc_Status:
14299 * 		OK
14300 *		ERROR - fatal error
14301 */
14302static ctl_ha_comp_status
14303ctl_isc_init(struct ctl_ha_component *c)
14304{
14305	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14306
14307	c->status = ret;
14308	return ret;
14309}
14310
14311/* Start component
14312 * 	Starts component in state requested. If component starts successfully,
14313 *	it must set its own state to the requestrd state
14314 *	When requested state is HASC_STATE_HA, the component may refine it
14315 * 	by adding _SLAVE or _MASTER flags.
14316 *	Currently allowed state transitions are:
14317 *	UNKNOWN->HA		- initial startup
14318 *	UNKNOWN->SINGLE - initial startup when no parter detected
14319 *	HA->SINGLE		- failover
14320 * returns ctl_ha_comp_status:
14321 * 		OK	- component successfully started in requested state
14322 *		FAILED  - could not start the requested state, failover may
14323 * 			  be possible
14324 *		ERROR	- fatal error detected, no future startup possible
14325 */
14326static ctl_ha_comp_status
14327ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14328{
14329	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14330
14331	printf("%s: go\n", __func__);
14332
14333	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14334	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14335		ctl_is_single = 0;
14336		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14337		    != CTL_HA_STATUS_SUCCESS) {
14338			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14339			ret = CTL_HA_COMP_STATUS_ERROR;
14340		}
14341	} else if (CTL_HA_STATE_IS_HA(c->state)
14342		&& CTL_HA_STATE_IS_SINGLE(state)){
14343		// HA->SINGLE transition
14344	        ctl_failover();
14345		ctl_is_single = 1;
14346	} else {
14347		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14348		       c->state, state);
14349		ret = CTL_HA_COMP_STATUS_ERROR;
14350	}
14351	if (CTL_HA_STATE_IS_SINGLE(state))
14352		ctl_is_single = 1;
14353
14354	c->state = state;
14355	c->status = ret;
14356	return ret;
14357}
14358
14359/*
14360 * Quiesce component
14361 * The component must clear any error conditions (set status to OK) and
14362 * prepare itself to another Start call
14363 * returns ctl_ha_comp_status:
14364 * 	OK
14365 *	ERROR
14366 */
14367static ctl_ha_comp_status
14368ctl_isc_quiesce(struct ctl_ha_component *c)
14369{
14370	int ret = CTL_HA_COMP_STATUS_OK;
14371
14372	ctl_pause_rtr = 1;
14373	c->status = ret;
14374	return ret;
14375}
14376
14377struct ctl_ha_component ctl_ha_component_ctlisc =
14378{
14379	.name = "CTL ISC",
14380	.state = CTL_HA_STATE_UNKNOWN,
14381	.init = ctl_isc_init,
14382	.start = ctl_isc_start,
14383	.quiesce = ctl_isc_quiesce
14384};
14385
14386/*
14387 *  vim: ts=8
14388 */
14389