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