ctl.c revision 268293
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 268293 2014-07-05 19:30:20Z 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*/ 0,
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	/*reserved*/0,
286	/*aen_holdoff_period*/{0, 0}
287};
288
289static struct scsi_control_page control_page_changeable = {
290	/*page_code*/SMS_CONTROL_MODE_PAGE,
291	/*page_length*/sizeof(struct scsi_control_page) - 2,
292	/*rlec*/SCP_DSENSE,
293	/*queue_flags*/0,
294	/*eca_and_aen*/0,
295	/*reserved*/0,
296	/*aen_holdoff_period*/{0, 0}
297};
298
299
300/*
301 * XXX KDM move these into the softc.
302 */
303static int rcv_sync_msg;
304static int persis_offset;
305static uint8_t ctl_pause_rtr;
306static int     ctl_is_single = 1;
307static int     index_to_aps_page;
308
309SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
310static int worker_threads = -1;
311SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
312    &worker_threads, 1, "Number of worker threads");
313static int verbose = 0;
314SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
315    &verbose, 0, "Show SCSI errors returned to initiator");
316
317/*
318 * Serial number (0x80), device id (0x83), supported pages (0x00),
319 * Block limits (0xB0) and Logical Block Provisioning (0xB2)
320 */
321#define SCSI_EVPD_NUM_SUPPORTED_PAGES	5
322
323static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
324				  int param);
325static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
326static int ctl_init(void);
327void ctl_shutdown(void);
328static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
329static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
330static void ctl_ioctl_online(void *arg);
331static void ctl_ioctl_offline(void *arg);
332static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
333static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
334static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
335static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
336static int ctl_ioctl_submit_wait(union ctl_io *io);
337static void ctl_ioctl_datamove(union ctl_io *io);
338static void ctl_ioctl_done(union ctl_io *io);
339static void ctl_ioctl_hard_startstop_callback(void *arg,
340					      struct cfi_metatask *metatask);
341static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
342static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
343			      struct ctl_ooa *ooa_hdr,
344			      struct ctl_ooa_entry *kern_entries);
345static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
346		     struct thread *td);
347uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
348uint32_t ctl_port_idx(int port_num);
349#ifdef unused
350static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
351				   uint32_t targ_target, uint32_t targ_lun,
352				   int can_wait);
353static void ctl_kfree_io(union ctl_io *io);
354#endif /* unused */
355static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
356			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
357static int ctl_free_lun(struct ctl_lun *lun);
358static void ctl_create_lun(struct ctl_be_lun *be_lun);
359/**
360static void ctl_failover_change_pages(struct ctl_softc *softc,
361				      struct ctl_scsiio *ctsio, int master);
362**/
363
364static int ctl_do_mode_select(union ctl_io *io);
365static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
366			   uint64_t res_key, uint64_t sa_res_key,
367			   uint8_t type, uint32_t residx,
368			   struct ctl_scsiio *ctsio,
369			   struct scsi_per_res_out *cdb,
370			   struct scsi_per_res_out_parms* param);
371static void ctl_pro_preempt_other(struct ctl_lun *lun,
372				  union ctl_ha_msg *msg);
373static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
374static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
375static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
376static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
377static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
378					 int alloc_len);
379static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
380static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
381static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
382static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
383static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
384static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
385					 union ctl_io *ooa_io);
386static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
387				union ctl_io *starting_io);
388static int ctl_check_blocked(struct ctl_lun *lun);
389static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
390				struct ctl_lun *lun,
391				const struct ctl_cmd_entry *entry,
392				struct ctl_scsiio *ctsio);
393//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
394static void ctl_failover(void);
395static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
396			       struct ctl_scsiio *ctsio);
397static int ctl_scsiio(struct ctl_scsiio *ctsio);
398
399static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
400static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
401			    ctl_ua_type ua_type);
402static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
403			 ctl_ua_type ua_type);
404static int ctl_abort_task(union ctl_io *io);
405static void ctl_run_task(union ctl_io *io);
406#ifdef CTL_IO_DELAY
407static void ctl_datamove_timer_wakeup(void *arg);
408static void ctl_done_timer_wakeup(void *arg);
409#endif /* CTL_IO_DELAY */
410
411static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
412static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
413static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
414static void ctl_datamove_remote_write(union ctl_io *io);
415static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
416static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
417static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
418static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
419				    ctl_ha_dt_cb callback);
420static void ctl_datamove_remote_read(union ctl_io *io);
421static void ctl_datamove_remote(union ctl_io *io);
422static int ctl_process_done(union ctl_io *io);
423static void ctl_lun_thread(void *arg);
424static void ctl_work_thread(void *arg);
425static void ctl_enqueue_incoming(union ctl_io *io);
426static void ctl_enqueue_rtr(union ctl_io *io);
427static void ctl_enqueue_done(union ctl_io *io);
428static void ctl_enqueue_isc(union ctl_io *io);
429static const struct ctl_cmd_entry *
430    ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
431static const struct ctl_cmd_entry *
432    ctl_validate_command(struct ctl_scsiio *ctsio);
433static int ctl_cmd_applicable(uint8_t lun_type,
434    const struct ctl_cmd_entry *entry);
435
436/*
437 * Load the serialization table.  This isn't very pretty, but is probably
438 * the easiest way to do it.
439 */
440#include "ctl_ser_table.c"
441
442/*
443 * We only need to define open, close and ioctl routines for this driver.
444 */
445static struct cdevsw ctl_cdevsw = {
446	.d_version =	D_VERSION,
447	.d_flags =	0,
448	.d_open =	ctl_open,
449	.d_close =	ctl_close,
450	.d_ioctl =	ctl_ioctl,
451	.d_name =	"ctl",
452};
453
454
455MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
456MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
457
458static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
459
460static moduledata_t ctl_moduledata = {
461	"ctl",
462	ctl_module_event_handler,
463	NULL
464};
465
466DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
467MODULE_VERSION(ctl, 1);
468
469static struct ctl_frontend ioctl_frontend =
470{
471	.name = "ioctl",
472};
473
474static void
475ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
476			    union ctl_ha_msg *msg_info)
477{
478	struct ctl_scsiio *ctsio;
479
480	if (msg_info->hdr.original_sc == NULL) {
481		printf("%s: original_sc == NULL!\n", __func__);
482		/* XXX KDM now what? */
483		return;
484	}
485
486	ctsio = &msg_info->hdr.original_sc->scsiio;
487	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
488	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
489	ctsio->io_hdr.status = msg_info->hdr.status;
490	ctsio->scsi_status = msg_info->scsi.scsi_status;
491	ctsio->sense_len = msg_info->scsi.sense_len;
492	ctsio->sense_residual = msg_info->scsi.sense_residual;
493	ctsio->residual = msg_info->scsi.residual;
494	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
495	       sizeof(ctsio->sense_data));
496	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
497	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
498	ctl_enqueue_isc((union ctl_io *)ctsio);
499}
500
501static void
502ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
503				union ctl_ha_msg *msg_info)
504{
505	struct ctl_scsiio *ctsio;
506
507	if (msg_info->hdr.serializing_sc == NULL) {
508		printf("%s: serializing_sc == NULL!\n", __func__);
509		/* XXX KDM now what? */
510		return;
511	}
512
513	ctsio = &msg_info->hdr.serializing_sc->scsiio;
514#if 0
515	/*
516	 * Attempt to catch the situation where an I/O has
517	 * been freed, and we're using it again.
518	 */
519	if (ctsio->io_hdr.io_type == 0xff) {
520		union ctl_io *tmp_io;
521		tmp_io = (union ctl_io *)ctsio;
522		printf("%s: %p use after free!\n", __func__,
523		       ctsio);
524		printf("%s: type %d msg %d cdb %x iptl: "
525		       "%d:%d:%d:%d tag 0x%04x "
526		       "flag %#x status %x\n",
527			__func__,
528			tmp_io->io_hdr.io_type,
529			tmp_io->io_hdr.msg_type,
530			tmp_io->scsiio.cdb[0],
531			tmp_io->io_hdr.nexus.initid.id,
532			tmp_io->io_hdr.nexus.targ_port,
533			tmp_io->io_hdr.nexus.targ_target.id,
534			tmp_io->io_hdr.nexus.targ_lun,
535			(tmp_io->io_hdr.io_type ==
536			CTL_IO_TASK) ?
537			tmp_io->taskio.tag_num :
538			tmp_io->scsiio.tag_num,
539		        tmp_io->io_hdr.flags,
540			tmp_io->io_hdr.status);
541	}
542#endif
543	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
544	ctl_enqueue_isc((union ctl_io *)ctsio);
545}
546
547/*
548 * ISC (Inter Shelf Communication) event handler.  Events from the HA
549 * subsystem come in here.
550 */
551static void
552ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
553{
554	struct ctl_softc *ctl_softc;
555	union ctl_io *io;
556	struct ctl_prio *presio;
557	ctl_ha_status isc_status;
558
559	ctl_softc = control_softc;
560	io = NULL;
561
562
563#if 0
564	printf("CTL: Isc Msg event %d\n", event);
565#endif
566	if (event == CTL_HA_EVT_MSG_RECV) {
567		union ctl_ha_msg msg_info;
568
569		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
570					     sizeof(msg_info), /*wait*/ 0);
571#if 0
572		printf("CTL: msg_type %d\n", msg_info.msg_type);
573#endif
574		if (isc_status != 0) {
575			printf("Error receiving message, status = %d\n",
576			       isc_status);
577			return;
578		}
579
580		switch (msg_info.hdr.msg_type) {
581		case CTL_MSG_SERIALIZE:
582#if 0
583			printf("Serialize\n");
584#endif
585			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
586			if (io == NULL) {
587				printf("ctl_isc_event_handler: can't allocate "
588				       "ctl_io!\n");
589				/* Bad Juju */
590				/* Need to set busy and send msg back */
591				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
592				msg_info.hdr.status = CTL_SCSI_ERROR;
593				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
594				msg_info.scsi.sense_len = 0;
595			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
596				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
597				}
598				goto bailout;
599			}
600			ctl_zero_io(io);
601			// populate ctsio from msg_info
602			io->io_hdr.io_type = CTL_IO_SCSI;
603			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
604			io->io_hdr.original_sc = msg_info.hdr.original_sc;
605#if 0
606			printf("pOrig %x\n", (int)msg_info.original_sc);
607#endif
608			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
609					    CTL_FLAG_IO_ACTIVE;
610			/*
611			 * If we're in serialization-only mode, we don't
612			 * want to go through full done processing.  Thus
613			 * the COPY flag.
614			 *
615			 * XXX KDM add another flag that is more specific.
616			 */
617			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
618				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
619			io->io_hdr.nexus = msg_info.hdr.nexus;
620#if 0
621			printf("targ %d, port %d, iid %d, lun %d\n",
622			       io->io_hdr.nexus.targ_target.id,
623			       io->io_hdr.nexus.targ_port,
624			       io->io_hdr.nexus.initid.id,
625			       io->io_hdr.nexus.targ_lun);
626#endif
627			io->scsiio.tag_num = msg_info.scsi.tag_num;
628			io->scsiio.tag_type = msg_info.scsi.tag_type;
629			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
630			       CTL_MAX_CDBLEN);
631			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
632				const struct ctl_cmd_entry *entry;
633
634				entry = ctl_get_cmd_entry(&io->scsiio);
635				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
636				io->io_hdr.flags |=
637					entry->flags & CTL_FLAG_DATA_MASK;
638			}
639			ctl_enqueue_isc(io);
640			break;
641
642		/* Performed on the Originating SC, XFER mode only */
643		case CTL_MSG_DATAMOVE: {
644			struct ctl_sg_entry *sgl;
645			int i, j;
646
647			io = msg_info.hdr.original_sc;
648			if (io == NULL) {
649				printf("%s: original_sc == NULL!\n", __func__);
650				/* XXX KDM do something here */
651				break;
652			}
653			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
654			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
655			/*
656			 * Keep track of this, we need to send it back over
657			 * when the datamove is complete.
658			 */
659			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
660
661			if (msg_info.dt.sg_sequence == 0) {
662				/*
663				 * XXX KDM we use the preallocated S/G list
664				 * here, but we'll need to change this to
665				 * dynamic allocation if we need larger S/G
666				 * lists.
667				 */
668				if (msg_info.dt.kern_sg_entries >
669				    sizeof(io->io_hdr.remote_sglist) /
670				    sizeof(io->io_hdr.remote_sglist[0])) {
671					printf("%s: number of S/G entries "
672					    "needed %u > allocated num %zd\n",
673					    __func__,
674					    msg_info.dt.kern_sg_entries,
675					    sizeof(io->io_hdr.remote_sglist)/
676					    sizeof(io->io_hdr.remote_sglist[0]));
677
678					/*
679					 * XXX KDM send a message back to
680					 * the other side to shut down the
681					 * DMA.  The error will come back
682					 * through via the normal channel.
683					 */
684					break;
685				}
686				sgl = io->io_hdr.remote_sglist;
687				memset(sgl, 0,
688				       sizeof(io->io_hdr.remote_sglist));
689
690				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
691
692				io->scsiio.kern_sg_entries =
693					msg_info.dt.kern_sg_entries;
694				io->scsiio.rem_sg_entries =
695					msg_info.dt.kern_sg_entries;
696				io->scsiio.kern_data_len =
697					msg_info.dt.kern_data_len;
698				io->scsiio.kern_total_len =
699					msg_info.dt.kern_total_len;
700				io->scsiio.kern_data_resid =
701					msg_info.dt.kern_data_resid;
702				io->scsiio.kern_rel_offset =
703					msg_info.dt.kern_rel_offset;
704				/*
705				 * Clear out per-DMA flags.
706				 */
707				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
708				/*
709				 * Add per-DMA flags that are set for this
710				 * particular DMA request.
711				 */
712				io->io_hdr.flags |= msg_info.dt.flags &
713						    CTL_FLAG_RDMA_MASK;
714			} else
715				sgl = (struct ctl_sg_entry *)
716					io->scsiio.kern_data_ptr;
717
718			for (i = msg_info.dt.sent_sg_entries, j = 0;
719			     i < (msg_info.dt.sent_sg_entries +
720			     msg_info.dt.cur_sg_entries); i++, j++) {
721				sgl[i].addr = msg_info.dt.sg_list[j].addr;
722				sgl[i].len = msg_info.dt.sg_list[j].len;
723
724#if 0
725				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
726				       __func__,
727				       msg_info.dt.sg_list[j].addr,
728				       msg_info.dt.sg_list[j].len,
729				       sgl[i].addr, sgl[i].len, j, i);
730#endif
731			}
732#if 0
733			memcpy(&sgl[msg_info.dt.sent_sg_entries],
734			       msg_info.dt.sg_list,
735			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
736#endif
737
738			/*
739			 * If this is the last piece of the I/O, we've got
740			 * the full S/G list.  Queue processing in the thread.
741			 * Otherwise wait for the next piece.
742			 */
743			if (msg_info.dt.sg_last != 0)
744				ctl_enqueue_isc(io);
745			break;
746		}
747		/* Performed on the Serializing (primary) SC, XFER mode only */
748		case CTL_MSG_DATAMOVE_DONE: {
749			if (msg_info.hdr.serializing_sc == NULL) {
750				printf("%s: serializing_sc == NULL!\n",
751				       __func__);
752				/* XXX KDM now what? */
753				break;
754			}
755			/*
756			 * We grab the sense information here in case
757			 * there was a failure, so we can return status
758			 * back to the initiator.
759			 */
760			io = msg_info.hdr.serializing_sc;
761			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
762			io->io_hdr.status = msg_info.hdr.status;
763			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
764			io->scsiio.sense_len = msg_info.scsi.sense_len;
765			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
766			io->io_hdr.port_status = msg_info.scsi.fetd_status;
767			io->scsiio.residual = msg_info.scsi.residual;
768			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
769			       sizeof(io->scsiio.sense_data));
770			ctl_enqueue_isc(io);
771			break;
772		}
773
774		/* Preformed on Originating SC, SER_ONLY mode */
775		case CTL_MSG_R2R:
776			io = msg_info.hdr.original_sc;
777			if (io == NULL) {
778				printf("%s: Major Bummer\n", __func__);
779				return;
780			} else {
781#if 0
782				printf("pOrig %x\n",(int) ctsio);
783#endif
784			}
785			io->io_hdr.msg_type = CTL_MSG_R2R;
786			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
787			ctl_enqueue_isc(io);
788			break;
789
790		/*
791		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
792		 * mode.
793		 * Performed on the Originating (i.e. secondary) SC in XFER
794		 * mode
795		 */
796		case CTL_MSG_FINISH_IO:
797			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
798				ctl_isc_handler_finish_xfer(ctl_softc,
799							    &msg_info);
800			else
801				ctl_isc_handler_finish_ser_only(ctl_softc,
802								&msg_info);
803			break;
804
805		/* Preformed on Originating SC */
806		case CTL_MSG_BAD_JUJU:
807			io = msg_info.hdr.original_sc;
808			if (io == NULL) {
809				printf("%s: Bad JUJU!, original_sc is NULL!\n",
810				       __func__);
811				break;
812			}
813			ctl_copy_sense_data(&msg_info, io);
814			/*
815			 * IO should have already been cleaned up on other
816			 * SC so clear this flag so we won't send a message
817			 * back to finish the IO there.
818			 */
819			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
820			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
821
822			/* io = msg_info.hdr.serializing_sc; */
823			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
824			ctl_enqueue_isc(io);
825			break;
826
827		/* Handle resets sent from the other side */
828		case CTL_MSG_MANAGE_TASKS: {
829			struct ctl_taskio *taskio;
830			taskio = (struct ctl_taskio *)ctl_alloc_io(
831				(void *)ctl_softc->othersc_pool);
832			if (taskio == NULL) {
833				printf("ctl_isc_event_handler: can't allocate "
834				       "ctl_io!\n");
835				/* Bad Juju */
836				/* should I just call the proper reset func
837				   here??? */
838				goto bailout;
839			}
840			ctl_zero_io((union ctl_io *)taskio);
841			taskio->io_hdr.io_type = CTL_IO_TASK;
842			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
843			taskio->io_hdr.nexus = msg_info.hdr.nexus;
844			taskio->task_action = msg_info.task.task_action;
845			taskio->tag_num = msg_info.task.tag_num;
846			taskio->tag_type = msg_info.task.tag_type;
847#ifdef CTL_TIME_IO
848			taskio->io_hdr.start_time = time_uptime;
849			getbintime(&taskio->io_hdr.start_bt);
850#if 0
851			cs_prof_gettime(&taskio->io_hdr.start_ticks);
852#endif
853#endif /* CTL_TIME_IO */
854			ctl_run_task((union ctl_io *)taskio);
855			break;
856		}
857		/* Persistent Reserve action which needs attention */
858		case CTL_MSG_PERS_ACTION:
859			presio = (struct ctl_prio *)ctl_alloc_io(
860				(void *)ctl_softc->othersc_pool);
861			if (presio == NULL) {
862				printf("ctl_isc_event_handler: can't allocate "
863				       "ctl_io!\n");
864				/* Bad Juju */
865				/* Need to set busy and send msg back */
866				goto bailout;
867			}
868			ctl_zero_io((union ctl_io *)presio);
869			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
870			presio->pr_msg = msg_info.pr;
871			ctl_enqueue_isc((union ctl_io *)presio);
872			break;
873		case CTL_MSG_SYNC_FE:
874			rcv_sync_msg = 1;
875			break;
876		case CTL_MSG_APS_LOCK: {
877			// It's quicker to execute this then to
878			// queue it.
879			struct ctl_lun *lun;
880			struct ctl_page_index *page_index;
881			struct copan_aps_subpage *current_sp;
882			uint32_t targ_lun;
883
884			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
885			lun = ctl_softc->ctl_luns[targ_lun];
886			mtx_lock(&lun->lun_lock);
887			page_index = &lun->mode_pages.index[index_to_aps_page];
888			current_sp = (struct copan_aps_subpage *)
889				     (page_index->page_data +
890				     (page_index->page_len * CTL_PAGE_CURRENT));
891
892			current_sp->lock_active = msg_info.aps.lock_flag;
893			mtx_unlock(&lun->lun_lock);
894		        break;
895		}
896		default:
897		        printf("How did I get here?\n");
898		}
899	} else if (event == CTL_HA_EVT_MSG_SENT) {
900		if (param != CTL_HA_STATUS_SUCCESS) {
901			printf("Bad status from ctl_ha_msg_send status %d\n",
902			       param);
903		}
904		return;
905	} else if (event == CTL_HA_EVT_DISCONNECT) {
906		printf("CTL: Got a disconnect from Isc\n");
907		return;
908	} else {
909		printf("ctl_isc_event_handler: Unknown event %d\n", event);
910		return;
911	}
912
913bailout:
914	return;
915}
916
917static void
918ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
919{
920	struct scsi_sense_data *sense;
921
922	sense = &dest->scsiio.sense_data;
923	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
924	dest->scsiio.scsi_status = src->scsi.scsi_status;
925	dest->scsiio.sense_len = src->scsi.sense_len;
926	dest->io_hdr.status = src->hdr.status;
927}
928
929static int
930ctl_init(void)
931{
932	struct ctl_softc *softc;
933	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
934	struct ctl_port *port;
935        uint8_t sc_id =0;
936	int i, error, retval;
937	//int isc_retval;
938
939	retval = 0;
940	ctl_pause_rtr = 0;
941        rcv_sync_msg = 0;
942
943	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
944			       M_WAITOK | M_ZERO);
945	softc = control_softc;
946
947	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
948			      "cam/ctl");
949
950	softc->dev->si_drv1 = softc;
951
952	/*
953	 * By default, return a "bad LUN" peripheral qualifier for unknown
954	 * LUNs.  The user can override this default using the tunable or
955	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
956	 */
957	softc->inquiry_pq_no_lun = 1;
958	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
959			  &softc->inquiry_pq_no_lun);
960	sysctl_ctx_init(&softc->sysctl_ctx);
961	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
962		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
963		CTLFLAG_RD, 0, "CAM Target Layer");
964
965	if (softc->sysctl_tree == NULL) {
966		printf("%s: unable to allocate sysctl tree\n", __func__);
967		destroy_dev(softc->dev);
968		free(control_softc, M_DEVBUF);
969		control_softc = NULL;
970		return (ENOMEM);
971	}
972
973	SYSCTL_ADD_INT(&softc->sysctl_ctx,
974		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
975		       "inquiry_pq_no_lun", CTLFLAG_RW,
976		       &softc->inquiry_pq_no_lun, 0,
977		       "Report no lun possible for invalid LUNs");
978
979	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
980	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
981	softc->open_count = 0;
982
983	/*
984	 * Default to actually sending a SYNCHRONIZE CACHE command down to
985	 * the drive.
986	 */
987	softc->flags = CTL_FLAG_REAL_SYNC;
988
989	/*
990	 * In Copan's HA scheme, the "master" and "slave" roles are
991	 * figured out through the slot the controller is in.  Although it
992	 * is an active/active system, someone has to be in charge.
993 	 */
994#ifdef NEEDTOPORT
995        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
996#endif
997
998        if (sc_id == 0) {
999		softc->flags |= CTL_FLAG_MASTER_SHELF;
1000		persis_offset = 0;
1001	} else
1002		persis_offset = CTL_MAX_INITIATORS;
1003
1004	/*
1005	 * XXX KDM need to figure out where we want to get our target ID
1006	 * and WWID.  Is it different on each port?
1007	 */
1008	softc->target.id = 0;
1009	softc->target.wwid[0] = 0x12345678;
1010	softc->target.wwid[1] = 0x87654321;
1011	STAILQ_INIT(&softc->lun_list);
1012	STAILQ_INIT(&softc->pending_lun_queue);
1013	STAILQ_INIT(&softc->fe_list);
1014	STAILQ_INIT(&softc->port_list);
1015	STAILQ_INIT(&softc->be_list);
1016	STAILQ_INIT(&softc->io_pools);
1017
1018	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1019			    &internal_pool)!= 0){
1020		printf("ctl: can't allocate %d entry internal pool, "
1021		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1022		return (ENOMEM);
1023	}
1024
1025	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1026			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1027		printf("ctl: can't allocate %d entry emergency pool, "
1028		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1029		ctl_pool_free(internal_pool);
1030		return (ENOMEM);
1031	}
1032
1033	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1034	                    &other_pool) != 0)
1035	{
1036		printf("ctl: can't allocate %d entry other SC pool, "
1037		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1038		ctl_pool_free(internal_pool);
1039		ctl_pool_free(emergency_pool);
1040		return (ENOMEM);
1041	}
1042
1043	softc->internal_pool = internal_pool;
1044	softc->emergency_pool = emergency_pool;
1045	softc->othersc_pool = other_pool;
1046
1047	if (worker_threads <= 0)
1048		worker_threads = max(1, mp_ncpus / 4);
1049	if (worker_threads > CTL_MAX_THREADS)
1050		worker_threads = CTL_MAX_THREADS;
1051
1052	for (i = 0; i < worker_threads; i++) {
1053		struct ctl_thread *thr = &softc->threads[i];
1054
1055		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1056		thr->ctl_softc = softc;
1057		STAILQ_INIT(&thr->incoming_queue);
1058		STAILQ_INIT(&thr->rtr_queue);
1059		STAILQ_INIT(&thr->done_queue);
1060		STAILQ_INIT(&thr->isc_queue);
1061
1062		error = kproc_kthread_add(ctl_work_thread, thr,
1063		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1064		if (error != 0) {
1065			printf("error creating CTL work thread!\n");
1066			ctl_pool_free(internal_pool);
1067			ctl_pool_free(emergency_pool);
1068			ctl_pool_free(other_pool);
1069			return (error);
1070		}
1071	}
1072	error = kproc_kthread_add(ctl_lun_thread, softc,
1073	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1074	if (error != 0) {
1075		printf("error creating CTL lun thread!\n");
1076		ctl_pool_free(internal_pool);
1077		ctl_pool_free(emergency_pool);
1078		ctl_pool_free(other_pool);
1079		return (error);
1080	}
1081	if (bootverbose)
1082		printf("ctl: CAM Target Layer loaded\n");
1083
1084	/*
1085	 * Initialize the initiator and portname mappings
1086	 */
1087	memset(softc->wwpn_iid, 0, sizeof(softc->wwpn_iid));
1088
1089	/*
1090	 * Initialize the ioctl front end.
1091	 */
1092	ctl_frontend_register(&ioctl_frontend);
1093	port = &softc->ioctl_info.port;
1094	port->frontend = &ioctl_frontend;
1095	sprintf(softc->ioctl_info.port_name, "ioctl");
1096	port->port_type = CTL_PORT_IOCTL;
1097	port->num_requested_ctl_io = 100;
1098	port->port_name = softc->ioctl_info.port_name;
1099	port->port_online = ctl_ioctl_online;
1100	port->port_offline = ctl_ioctl_offline;
1101	port->onoff_arg = &softc->ioctl_info;
1102	port->lun_enable = ctl_ioctl_lun_enable;
1103	port->lun_disable = ctl_ioctl_lun_disable;
1104	port->targ_lun_arg = &softc->ioctl_info;
1105	port->fe_datamove = ctl_ioctl_datamove;
1106	port->fe_done = ctl_ioctl_done;
1107	port->max_targets = 15;
1108	port->max_target_id = 15;
1109
1110	if (ctl_port_register(&softc->ioctl_info.port,
1111	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1112		printf("ctl: ioctl front end registration failed, will "
1113		       "continue anyway\n");
1114	}
1115
1116#ifdef CTL_IO_DELAY
1117	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1118		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1119		       sizeof(struct callout), CTL_TIMER_BYTES);
1120		return (EINVAL);
1121	}
1122#endif /* CTL_IO_DELAY */
1123
1124	return (0);
1125}
1126
1127void
1128ctl_shutdown(void)
1129{
1130	struct ctl_softc *softc;
1131	struct ctl_lun *lun, *next_lun;
1132	struct ctl_io_pool *pool;
1133
1134	softc = (struct ctl_softc *)control_softc;
1135
1136	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1137		printf("ctl: ioctl front end deregistration failed\n");
1138
1139	mtx_lock(&softc->ctl_lock);
1140
1141	/*
1142	 * Free up each LUN.
1143	 */
1144	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1145		next_lun = STAILQ_NEXT(lun, links);
1146		ctl_free_lun(lun);
1147	}
1148
1149	mtx_unlock(&softc->ctl_lock);
1150
1151	ctl_frontend_deregister(&ioctl_frontend);
1152
1153	/*
1154	 * This will rip the rug out from under any FETDs or anyone else
1155	 * that has a pool allocated.  Since we increment our module
1156	 * refcount any time someone outside the main CTL module allocates
1157	 * a pool, we shouldn't have any problems here.  The user won't be
1158	 * able to unload the CTL module until client modules have
1159	 * successfully unloaded.
1160	 */
1161	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1162		ctl_pool_free(pool);
1163
1164#if 0
1165	ctl_shutdown_thread(softc->work_thread);
1166	mtx_destroy(&softc->queue_lock);
1167#endif
1168
1169	mtx_destroy(&softc->pool_lock);
1170	mtx_destroy(&softc->ctl_lock);
1171
1172	destroy_dev(softc->dev);
1173
1174	sysctl_ctx_free(&softc->sysctl_ctx);
1175
1176	free(control_softc, M_DEVBUF);
1177	control_softc = NULL;
1178
1179	if (bootverbose)
1180		printf("ctl: CAM Target Layer unloaded\n");
1181}
1182
1183static int
1184ctl_module_event_handler(module_t mod, int what, void *arg)
1185{
1186
1187	switch (what) {
1188	case MOD_LOAD:
1189		return (ctl_init());
1190	case MOD_UNLOAD:
1191		return (EBUSY);
1192	default:
1193		return (EOPNOTSUPP);
1194	}
1195}
1196
1197/*
1198 * XXX KDM should we do some access checks here?  Bump a reference count to
1199 * prevent a CTL module from being unloaded while someone has it open?
1200 */
1201static int
1202ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1203{
1204	return (0);
1205}
1206
1207static int
1208ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1209{
1210	return (0);
1211}
1212
1213int
1214ctl_port_enable(ctl_port_type port_type)
1215{
1216	struct ctl_softc *softc;
1217	struct ctl_port *port;
1218
1219	if (ctl_is_single == 0) {
1220		union ctl_ha_msg msg_info;
1221		int isc_retval;
1222
1223#if 0
1224		printf("%s: HA mode, synchronizing frontend enable\n",
1225		        __func__);
1226#endif
1227		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1228	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1229		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1230			printf("Sync msg send error retval %d\n", isc_retval);
1231		}
1232		if (!rcv_sync_msg) {
1233			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1234			        sizeof(msg_info), 1);
1235		}
1236#if 0
1237        	printf("CTL:Frontend Enable\n");
1238	} else {
1239		printf("%s: single mode, skipping frontend synchronization\n",
1240		        __func__);
1241#endif
1242	}
1243
1244	softc = control_softc;
1245
1246	STAILQ_FOREACH(port, &softc->port_list, links) {
1247		if (port_type & port->port_type)
1248		{
1249#if 0
1250			printf("port %d\n", port->targ_port);
1251#endif
1252			ctl_port_online(port);
1253		}
1254	}
1255
1256	return (0);
1257}
1258
1259int
1260ctl_port_disable(ctl_port_type port_type)
1261{
1262	struct ctl_softc *softc;
1263	struct ctl_port *port;
1264
1265	softc = control_softc;
1266
1267	STAILQ_FOREACH(port, &softc->port_list, links) {
1268		if (port_type & port->port_type)
1269			ctl_port_offline(port);
1270	}
1271
1272	return (0);
1273}
1274
1275/*
1276 * Returns 0 for success, 1 for failure.
1277 * Currently the only failure mode is if there aren't enough entries
1278 * allocated.  So, in case of a failure, look at num_entries_dropped,
1279 * reallocate and try again.
1280 */
1281int
1282ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1283	      int *num_entries_filled, int *num_entries_dropped,
1284	      ctl_port_type port_type, int no_virtual)
1285{
1286	struct ctl_softc *softc;
1287	struct ctl_port *port;
1288	int entries_dropped, entries_filled;
1289	int retval;
1290	int i;
1291
1292	softc = control_softc;
1293
1294	retval = 0;
1295	entries_filled = 0;
1296	entries_dropped = 0;
1297
1298	i = 0;
1299	mtx_lock(&softc->ctl_lock);
1300	STAILQ_FOREACH(port, &softc->port_list, links) {
1301		struct ctl_port_entry *entry;
1302
1303		if ((port->port_type & port_type) == 0)
1304			continue;
1305
1306		if ((no_virtual != 0)
1307		 && (port->virtual_port != 0))
1308			continue;
1309
1310		if (entries_filled >= num_entries_alloced) {
1311			entries_dropped++;
1312			continue;
1313		}
1314		entry = &entries[i];
1315
1316		entry->port_type = port->port_type;
1317		strlcpy(entry->port_name, port->port_name,
1318			sizeof(entry->port_name));
1319		entry->physical_port = port->physical_port;
1320		entry->virtual_port = port->virtual_port;
1321		entry->wwnn = port->wwnn;
1322		entry->wwpn = port->wwpn;
1323
1324		i++;
1325		entries_filled++;
1326	}
1327
1328	mtx_unlock(&softc->ctl_lock);
1329
1330	if (entries_dropped > 0)
1331		retval = 1;
1332
1333	*num_entries_dropped = entries_dropped;
1334	*num_entries_filled = entries_filled;
1335
1336	return (retval);
1337}
1338
1339static void
1340ctl_ioctl_online(void *arg)
1341{
1342	struct ctl_ioctl_info *ioctl_info;
1343
1344	ioctl_info = (struct ctl_ioctl_info *)arg;
1345
1346	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1347}
1348
1349static void
1350ctl_ioctl_offline(void *arg)
1351{
1352	struct ctl_ioctl_info *ioctl_info;
1353
1354	ioctl_info = (struct ctl_ioctl_info *)arg;
1355
1356	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1357}
1358
1359/*
1360 * Remove an initiator by port number and initiator ID.
1361 * Returns 0 for success, 1 for failure.
1362 */
1363int
1364ctl_remove_initiator(int32_t targ_port, uint32_t iid)
1365{
1366	struct ctl_softc *softc;
1367
1368	softc = control_softc;
1369
1370	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1371
1372	if ((targ_port < 0)
1373	 || (targ_port > CTL_MAX_PORTS)) {
1374		printf("%s: invalid port number %d\n", __func__, targ_port);
1375		return (1);
1376	}
1377	if (iid > CTL_MAX_INIT_PER_PORT) {
1378		printf("%s: initiator ID %u > maximun %u!\n",
1379		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1380		return (1);
1381	}
1382
1383	mtx_lock(&softc->ctl_lock);
1384
1385	softc->wwpn_iid[targ_port][iid].in_use = 0;
1386
1387	mtx_unlock(&softc->ctl_lock);
1388
1389	return (0);
1390}
1391
1392/*
1393 * Add an initiator to the initiator map.
1394 * Returns 0 for success, 1 for failure.
1395 */
1396int
1397ctl_add_initiator(uint64_t wwpn, int32_t targ_port, uint32_t iid)
1398{
1399	struct ctl_softc *softc;
1400	int retval;
1401
1402	softc = control_softc;
1403
1404	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1405
1406	retval = 0;
1407
1408	if ((targ_port < 0)
1409	 || (targ_port > CTL_MAX_PORTS)) {
1410		printf("%s: invalid port number %d\n", __func__, targ_port);
1411		return (1);
1412	}
1413	if (iid > CTL_MAX_INIT_PER_PORT) {
1414		printf("%s: WWPN %#jx initiator ID %u > maximun %u!\n",
1415		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1416		return (1);
1417	}
1418
1419	mtx_lock(&softc->ctl_lock);
1420
1421	if (softc->wwpn_iid[targ_port][iid].in_use != 0) {
1422		/*
1423		 * We don't treat this as an error.
1424		 */
1425		if (softc->wwpn_iid[targ_port][iid].wwpn == wwpn) {
1426			printf("%s: port %d iid %u WWPN %#jx arrived again?\n",
1427			       __func__, targ_port, iid, (uintmax_t)wwpn);
1428			goto bailout;
1429		}
1430
1431		/*
1432		 * This is an error, but what do we do about it?  The
1433		 * driver is telling us we have a new WWPN for this
1434		 * initiator ID, so we pretty much need to use it.
1435		 */
1436		printf("%s: port %d iid %u WWPN %#jx arrived, WWPN %#jx is "
1437		       "still at that address\n", __func__, targ_port, iid,
1438		       (uintmax_t)wwpn,
1439		       (uintmax_t)softc->wwpn_iid[targ_port][iid].wwpn);
1440
1441		/*
1442		 * XXX KDM clear have_ca and ua_pending on each LUN for
1443		 * this initiator.
1444		 */
1445	}
1446	softc->wwpn_iid[targ_port][iid].in_use = 1;
1447	softc->wwpn_iid[targ_port][iid].iid = iid;
1448	softc->wwpn_iid[targ_port][iid].wwpn = wwpn;
1449	softc->wwpn_iid[targ_port][iid].port = targ_port;
1450
1451bailout:
1452
1453	mtx_unlock(&softc->ctl_lock);
1454
1455	return (retval);
1456}
1457
1458static int
1459ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1460{
1461	return (0);
1462}
1463
1464static int
1465ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1466{
1467	return (0);
1468}
1469
1470/*
1471 * Data movement routine for the CTL ioctl frontend port.
1472 */
1473static int
1474ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1475{
1476	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1477	struct ctl_sg_entry ext_entry, kern_entry;
1478	int ext_sglen, ext_sg_entries, kern_sg_entries;
1479	int ext_sg_start, ext_offset;
1480	int len_to_copy, len_copied;
1481	int kern_watermark, ext_watermark;
1482	int ext_sglist_malloced;
1483	int i, j;
1484
1485	ext_sglist_malloced = 0;
1486	ext_sg_start = 0;
1487	ext_offset = 0;
1488
1489	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1490
1491	/*
1492	 * If this flag is set, fake the data transfer.
1493	 */
1494	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1495		ctsio->ext_data_filled = ctsio->ext_data_len;
1496		goto bailout;
1497	}
1498
1499	/*
1500	 * To simplify things here, if we have a single buffer, stick it in
1501	 * a S/G entry and just make it a single entry S/G list.
1502	 */
1503	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1504		int len_seen;
1505
1506		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1507
1508		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1509							   M_WAITOK);
1510		ext_sglist_malloced = 1;
1511		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1512				   ext_sglen) != 0) {
1513			ctl_set_internal_failure(ctsio,
1514						 /*sks_valid*/ 0,
1515						 /*retry_count*/ 0);
1516			goto bailout;
1517		}
1518		ext_sg_entries = ctsio->ext_sg_entries;
1519		len_seen = 0;
1520		for (i = 0; i < ext_sg_entries; i++) {
1521			if ((len_seen + ext_sglist[i].len) >=
1522			     ctsio->ext_data_filled) {
1523				ext_sg_start = i;
1524				ext_offset = ctsio->ext_data_filled - len_seen;
1525				break;
1526			}
1527			len_seen += ext_sglist[i].len;
1528		}
1529	} else {
1530		ext_sglist = &ext_entry;
1531		ext_sglist->addr = ctsio->ext_data_ptr;
1532		ext_sglist->len = ctsio->ext_data_len;
1533		ext_sg_entries = 1;
1534		ext_sg_start = 0;
1535		ext_offset = ctsio->ext_data_filled;
1536	}
1537
1538	if (ctsio->kern_sg_entries > 0) {
1539		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1540		kern_sg_entries = ctsio->kern_sg_entries;
1541	} else {
1542		kern_sglist = &kern_entry;
1543		kern_sglist->addr = ctsio->kern_data_ptr;
1544		kern_sglist->len = ctsio->kern_data_len;
1545		kern_sg_entries = 1;
1546	}
1547
1548
1549	kern_watermark = 0;
1550	ext_watermark = ext_offset;
1551	len_copied = 0;
1552	for (i = ext_sg_start, j = 0;
1553	     i < ext_sg_entries && j < kern_sg_entries;) {
1554		uint8_t *ext_ptr, *kern_ptr;
1555
1556		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1557				      kern_sglist[j].len - kern_watermark);
1558
1559		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1560		ext_ptr = ext_ptr + ext_watermark;
1561		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1562			/*
1563			 * XXX KDM fix this!
1564			 */
1565			panic("need to implement bus address support");
1566#if 0
1567			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1568#endif
1569		} else
1570			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1571		kern_ptr = kern_ptr + kern_watermark;
1572
1573		kern_watermark += len_to_copy;
1574		ext_watermark += len_to_copy;
1575
1576		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1577		     CTL_FLAG_DATA_IN) {
1578			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1579					 "bytes to user\n", len_to_copy));
1580			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1581					 "to %p\n", kern_ptr, ext_ptr));
1582			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1583				ctl_set_internal_failure(ctsio,
1584							 /*sks_valid*/ 0,
1585							 /*retry_count*/ 0);
1586				goto bailout;
1587			}
1588		} else {
1589			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1590					 "bytes from user\n", len_to_copy));
1591			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1592					 "to %p\n", ext_ptr, kern_ptr));
1593			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1594				ctl_set_internal_failure(ctsio,
1595							 /*sks_valid*/ 0,
1596							 /*retry_count*/0);
1597				goto bailout;
1598			}
1599		}
1600
1601		len_copied += len_to_copy;
1602
1603		if (ext_sglist[i].len == ext_watermark) {
1604			i++;
1605			ext_watermark = 0;
1606		}
1607
1608		if (kern_sglist[j].len == kern_watermark) {
1609			j++;
1610			kern_watermark = 0;
1611		}
1612	}
1613
1614	ctsio->ext_data_filled += len_copied;
1615
1616	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1617			 "kern_sg_entries: %d\n", ext_sg_entries,
1618			 kern_sg_entries));
1619	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1620			 "kern_data_len = %d\n", ctsio->ext_data_len,
1621			 ctsio->kern_data_len));
1622
1623
1624	/* XXX KDM set residual?? */
1625bailout:
1626
1627	if (ext_sglist_malloced != 0)
1628		free(ext_sglist, M_CTL);
1629
1630	return (CTL_RETVAL_COMPLETE);
1631}
1632
1633/*
1634 * Serialize a command that went down the "wrong" side, and so was sent to
1635 * this controller for execution.  The logic is a little different than the
1636 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1637 * sent back to the other side, but in the success case, we execute the
1638 * command on this side (XFER mode) or tell the other side to execute it
1639 * (SER_ONLY mode).
1640 */
1641static int
1642ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1643{
1644	struct ctl_softc *ctl_softc;
1645	union ctl_ha_msg msg_info;
1646	struct ctl_lun *lun;
1647	int retval = 0;
1648	uint32_t targ_lun;
1649
1650	ctl_softc = control_softc;
1651
1652	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1653	lun = ctl_softc->ctl_luns[targ_lun];
1654	if (lun==NULL)
1655	{
1656		/*
1657		 * Why isn't LUN defined? The other side wouldn't
1658		 * send a cmd if the LUN is undefined.
1659		 */
1660		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1661
1662		/* "Logical unit not supported" */
1663		ctl_set_sense_data(&msg_info.scsi.sense_data,
1664				   lun,
1665				   /*sense_format*/SSD_TYPE_NONE,
1666				   /*current_error*/ 1,
1667				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1668				   /*asc*/ 0x25,
1669				   /*ascq*/ 0x00,
1670				   SSD_ELEM_NONE);
1671
1672		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1673		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1674		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1675		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1676		msg_info.hdr.serializing_sc = NULL;
1677		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1678	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1679				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1680		}
1681		return(1);
1682
1683	}
1684
1685	mtx_lock(&lun->lun_lock);
1686    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1687
1688	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1689		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1690		 ooa_links))) {
1691	case CTL_ACTION_BLOCK:
1692		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1693		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1694				  blocked_links);
1695		break;
1696	case CTL_ACTION_PASS:
1697	case CTL_ACTION_SKIP:
1698		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1699			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1700			ctl_enqueue_rtr((union ctl_io *)ctsio);
1701		} else {
1702
1703			/* send msg back to other side */
1704			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1705			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1706			msg_info.hdr.msg_type = CTL_MSG_R2R;
1707#if 0
1708			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1709#endif
1710		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1711			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1712			}
1713		}
1714		break;
1715	case CTL_ACTION_OVERLAP:
1716		/* OVERLAPPED COMMANDS ATTEMPTED */
1717		ctl_set_sense_data(&msg_info.scsi.sense_data,
1718				   lun,
1719				   /*sense_format*/SSD_TYPE_NONE,
1720				   /*current_error*/ 1,
1721				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1722				   /*asc*/ 0x4E,
1723				   /*ascq*/ 0x00,
1724				   SSD_ELEM_NONE);
1725
1726		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1727		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1728		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1729		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1730		msg_info.hdr.serializing_sc = NULL;
1731		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1732#if 0
1733		printf("BAD JUJU:Major Bummer Overlap\n");
1734#endif
1735		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1736		retval = 1;
1737		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1738		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1739		}
1740		break;
1741	case CTL_ACTION_OVERLAP_TAG:
1742		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1743		ctl_set_sense_data(&msg_info.scsi.sense_data,
1744				   lun,
1745				   /*sense_format*/SSD_TYPE_NONE,
1746				   /*current_error*/ 1,
1747				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1748				   /*asc*/ 0x4D,
1749				   /*ascq*/ ctsio->tag_num & 0xff,
1750				   SSD_ELEM_NONE);
1751
1752		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1753		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1754		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1755		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1756		msg_info.hdr.serializing_sc = NULL;
1757		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1758#if 0
1759		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1760#endif
1761		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1762		retval = 1;
1763		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1764		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1765		}
1766		break;
1767	case CTL_ACTION_ERROR:
1768	default:
1769		/* "Internal target failure" */
1770		ctl_set_sense_data(&msg_info.scsi.sense_data,
1771				   lun,
1772				   /*sense_format*/SSD_TYPE_NONE,
1773				   /*current_error*/ 1,
1774				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1775				   /*asc*/ 0x44,
1776				   /*ascq*/ 0x00,
1777				   SSD_ELEM_NONE);
1778
1779		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1780		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1781		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1782		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1783		msg_info.hdr.serializing_sc = NULL;
1784		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1785#if 0
1786		printf("BAD JUJU:Major Bummer HW Error\n");
1787#endif
1788		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1789		retval = 1;
1790		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1791		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1792		}
1793		break;
1794	}
1795	mtx_unlock(&lun->lun_lock);
1796	return (retval);
1797}
1798
1799static int
1800ctl_ioctl_submit_wait(union ctl_io *io)
1801{
1802	struct ctl_fe_ioctl_params params;
1803	ctl_fe_ioctl_state last_state;
1804	int done, retval;
1805
1806	retval = 0;
1807
1808	bzero(&params, sizeof(params));
1809
1810	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1811	cv_init(&params.sem, "ctlioccv");
1812	params.state = CTL_IOCTL_INPROG;
1813	last_state = params.state;
1814
1815	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1816
1817	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1818
1819	/* This shouldn't happen */
1820	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1821		return (retval);
1822
1823	done = 0;
1824
1825	do {
1826		mtx_lock(&params.ioctl_mtx);
1827		/*
1828		 * Check the state here, and don't sleep if the state has
1829		 * already changed (i.e. wakeup has already occured, but we
1830		 * weren't waiting yet).
1831		 */
1832		if (params.state == last_state) {
1833			/* XXX KDM cv_wait_sig instead? */
1834			cv_wait(&params.sem, &params.ioctl_mtx);
1835		}
1836		last_state = params.state;
1837
1838		switch (params.state) {
1839		case CTL_IOCTL_INPROG:
1840			/* Why did we wake up? */
1841			/* XXX KDM error here? */
1842			mtx_unlock(&params.ioctl_mtx);
1843			break;
1844		case CTL_IOCTL_DATAMOVE:
1845			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1846
1847			/*
1848			 * change last_state back to INPROG to avoid
1849			 * deadlock on subsequent data moves.
1850			 */
1851			params.state = last_state = CTL_IOCTL_INPROG;
1852
1853			mtx_unlock(&params.ioctl_mtx);
1854			ctl_ioctl_do_datamove(&io->scsiio);
1855			/*
1856			 * Note that in some cases, most notably writes,
1857			 * this will queue the I/O and call us back later.
1858			 * In other cases, generally reads, this routine
1859			 * will immediately call back and wake us up,
1860			 * probably using our own context.
1861			 */
1862			io->scsiio.be_move_done(io);
1863			break;
1864		case CTL_IOCTL_DONE:
1865			mtx_unlock(&params.ioctl_mtx);
1866			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1867			done = 1;
1868			break;
1869		default:
1870			mtx_unlock(&params.ioctl_mtx);
1871			/* XXX KDM error here? */
1872			break;
1873		}
1874	} while (done == 0);
1875
1876	mtx_destroy(&params.ioctl_mtx);
1877	cv_destroy(&params.sem);
1878
1879	return (CTL_RETVAL_COMPLETE);
1880}
1881
1882static void
1883ctl_ioctl_datamove(union ctl_io *io)
1884{
1885	struct ctl_fe_ioctl_params *params;
1886
1887	params = (struct ctl_fe_ioctl_params *)
1888		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1889
1890	mtx_lock(&params->ioctl_mtx);
1891	params->state = CTL_IOCTL_DATAMOVE;
1892	cv_broadcast(&params->sem);
1893	mtx_unlock(&params->ioctl_mtx);
1894}
1895
1896static void
1897ctl_ioctl_done(union ctl_io *io)
1898{
1899	struct ctl_fe_ioctl_params *params;
1900
1901	params = (struct ctl_fe_ioctl_params *)
1902		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1903
1904	mtx_lock(&params->ioctl_mtx);
1905	params->state = CTL_IOCTL_DONE;
1906	cv_broadcast(&params->sem);
1907	mtx_unlock(&params->ioctl_mtx);
1908}
1909
1910static void
1911ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
1912{
1913	struct ctl_fe_ioctl_startstop_info *sd_info;
1914
1915	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
1916
1917	sd_info->hs_info.status = metatask->status;
1918	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
1919	sd_info->hs_info.luns_complete =
1920		metatask->taskinfo.startstop.luns_complete;
1921	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
1922
1923	cv_broadcast(&sd_info->sem);
1924}
1925
1926static void
1927ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
1928{
1929	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
1930
1931	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
1932
1933	mtx_lock(fe_bbr_info->lock);
1934	fe_bbr_info->bbr_info->status = metatask->status;
1935	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
1936	fe_bbr_info->wakeup_done = 1;
1937	mtx_unlock(fe_bbr_info->lock);
1938
1939	cv_broadcast(&fe_bbr_info->sem);
1940}
1941
1942/*
1943 * Returns 0 for success, errno for failure.
1944 */
1945static int
1946ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1947		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1948{
1949	union ctl_io *io;
1950	int retval;
1951
1952	retval = 0;
1953
1954	mtx_lock(&lun->lun_lock);
1955	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1956	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1957	     ooa_links)) {
1958		struct ctl_ooa_entry *entry;
1959
1960		/*
1961		 * If we've got more than we can fit, just count the
1962		 * remaining entries.
1963		 */
1964		if (*cur_fill_num >= ooa_hdr->alloc_num)
1965			continue;
1966
1967		entry = &kern_entries[*cur_fill_num];
1968
1969		entry->tag_num = io->scsiio.tag_num;
1970		entry->lun_num = lun->lun;
1971#ifdef CTL_TIME_IO
1972		entry->start_bt = io->io_hdr.start_bt;
1973#endif
1974		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1975		entry->cdb_len = io->scsiio.cdb_len;
1976		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1977			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1978
1979		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1980			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1981
1982		if (io->io_hdr.flags & CTL_FLAG_ABORT)
1983			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1984
1985		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1986			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1987
1988		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1989			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1990	}
1991	mtx_unlock(&lun->lun_lock);
1992
1993	return (retval);
1994}
1995
1996static void *
1997ctl_copyin_alloc(void *user_addr, int len, char *error_str,
1998		 size_t error_str_len)
1999{
2000	void *kptr;
2001
2002	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2003
2004	if (copyin(user_addr, kptr, len) != 0) {
2005		snprintf(error_str, error_str_len, "Error copying %d bytes "
2006			 "from user address %p to kernel address %p", len,
2007			 user_addr, kptr);
2008		free(kptr, M_CTL);
2009		return (NULL);
2010	}
2011
2012	return (kptr);
2013}
2014
2015static void
2016ctl_free_args(int num_args, struct ctl_be_arg *args)
2017{
2018	int i;
2019
2020	if (args == NULL)
2021		return;
2022
2023	for (i = 0; i < num_args; i++) {
2024		free(args[i].kname, M_CTL);
2025		free(args[i].kvalue, M_CTL);
2026	}
2027
2028	free(args, M_CTL);
2029}
2030
2031static struct ctl_be_arg *
2032ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2033		char *error_str, size_t error_str_len)
2034{
2035	struct ctl_be_arg *args;
2036	int i;
2037
2038	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2039				error_str, error_str_len);
2040
2041	if (args == NULL)
2042		goto bailout;
2043
2044	for (i = 0; i < num_args; i++) {
2045		args[i].kname = NULL;
2046		args[i].kvalue = NULL;
2047	}
2048
2049	for (i = 0; i < num_args; i++) {
2050		uint8_t *tmpptr;
2051
2052		args[i].kname = ctl_copyin_alloc(args[i].name,
2053			args[i].namelen, error_str, error_str_len);
2054		if (args[i].kname == NULL)
2055			goto bailout;
2056
2057		if (args[i].kname[args[i].namelen - 1] != '\0') {
2058			snprintf(error_str, error_str_len, "Argument %d "
2059				 "name is not NUL-terminated", i);
2060			goto bailout;
2061		}
2062
2063		if (args[i].flags & CTL_BEARG_RD) {
2064			tmpptr = ctl_copyin_alloc(args[i].value,
2065				args[i].vallen, error_str, error_str_len);
2066			if (tmpptr == NULL)
2067				goto bailout;
2068			if ((args[i].flags & CTL_BEARG_ASCII)
2069			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2070				snprintf(error_str, error_str_len, "Argument "
2071				    "%d value is not NUL-terminated", i);
2072				goto bailout;
2073			}
2074			args[i].kvalue = tmpptr;
2075		} else {
2076			args[i].kvalue = malloc(args[i].vallen,
2077			    M_CTL, M_WAITOK | M_ZERO);
2078		}
2079	}
2080
2081	return (args);
2082bailout:
2083
2084	ctl_free_args(num_args, args);
2085
2086	return (NULL);
2087}
2088
2089static void
2090ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2091{
2092	int i;
2093
2094	for (i = 0; i < num_args; i++) {
2095		if (args[i].flags & CTL_BEARG_WR)
2096			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2097	}
2098}
2099
2100/*
2101 * Escape characters that are illegal or not recommended in XML.
2102 */
2103int
2104ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2105{
2106	int retval;
2107
2108	retval = 0;
2109
2110	for (; *str; str++) {
2111		switch (*str) {
2112		case '&':
2113			retval = sbuf_printf(sb, "&amp;");
2114			break;
2115		case '>':
2116			retval = sbuf_printf(sb, "&gt;");
2117			break;
2118		case '<':
2119			retval = sbuf_printf(sb, "&lt;");
2120			break;
2121		default:
2122			retval = sbuf_putc(sb, *str);
2123			break;
2124		}
2125
2126		if (retval != 0)
2127			break;
2128
2129	}
2130
2131	return (retval);
2132}
2133
2134static int
2135ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2136	  struct thread *td)
2137{
2138	struct ctl_softc *softc;
2139	int retval;
2140
2141	softc = control_softc;
2142
2143	retval = 0;
2144
2145	switch (cmd) {
2146	case CTL_IO: {
2147		union ctl_io *io;
2148		void *pool_tmp;
2149
2150		/*
2151		 * If we haven't been "enabled", don't allow any SCSI I/O
2152		 * to this FETD.
2153		 */
2154		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2155			retval = EPERM;
2156			break;
2157		}
2158
2159		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2160		if (io == NULL) {
2161			printf("ctl_ioctl: can't allocate ctl_io!\n");
2162			retval = ENOSPC;
2163			break;
2164		}
2165
2166		/*
2167		 * Need to save the pool reference so it doesn't get
2168		 * spammed by the user's ctl_io.
2169		 */
2170		pool_tmp = io->io_hdr.pool;
2171
2172		memcpy(io, (void *)addr, sizeof(*io));
2173
2174		io->io_hdr.pool = pool_tmp;
2175		/*
2176		 * No status yet, so make sure the status is set properly.
2177		 */
2178		io->io_hdr.status = CTL_STATUS_NONE;
2179
2180		/*
2181		 * The user sets the initiator ID, target and LUN IDs.
2182		 */
2183		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2184		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2185		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2186		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2187			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2188
2189		retval = ctl_ioctl_submit_wait(io);
2190
2191		if (retval != 0) {
2192			ctl_free_io(io);
2193			break;
2194		}
2195
2196		memcpy((void *)addr, io, sizeof(*io));
2197
2198		/* return this to our pool */
2199		ctl_free_io(io);
2200
2201		break;
2202	}
2203	case CTL_ENABLE_PORT:
2204	case CTL_DISABLE_PORT:
2205	case CTL_SET_PORT_WWNS: {
2206		struct ctl_port *port;
2207		struct ctl_port_entry *entry;
2208
2209		entry = (struct ctl_port_entry *)addr;
2210
2211		mtx_lock(&softc->ctl_lock);
2212		STAILQ_FOREACH(port, &softc->port_list, links) {
2213			int action, done;
2214
2215			action = 0;
2216			done = 0;
2217
2218			if ((entry->port_type == CTL_PORT_NONE)
2219			 && (entry->targ_port == port->targ_port)) {
2220				/*
2221				 * If the user only wants to enable or
2222				 * disable or set WWNs on a specific port,
2223				 * do the operation and we're done.
2224				 */
2225				action = 1;
2226				done = 1;
2227			} else if (entry->port_type & port->port_type) {
2228				/*
2229				 * Compare the user's type mask with the
2230				 * particular frontend type to see if we
2231				 * have a match.
2232				 */
2233				action = 1;
2234				done = 0;
2235
2236				/*
2237				 * Make sure the user isn't trying to set
2238				 * WWNs on multiple ports at the same time.
2239				 */
2240				if (cmd == CTL_SET_PORT_WWNS) {
2241					printf("%s: Can't set WWNs on "
2242					       "multiple ports\n", __func__);
2243					retval = EINVAL;
2244					break;
2245				}
2246			}
2247			if (action != 0) {
2248				/*
2249				 * XXX KDM we have to drop the lock here,
2250				 * because the online/offline operations
2251				 * can potentially block.  We need to
2252				 * reference count the frontends so they
2253				 * can't go away,
2254				 */
2255				mtx_unlock(&softc->ctl_lock);
2256
2257				if (cmd == CTL_ENABLE_PORT) {
2258					struct ctl_lun *lun;
2259
2260					STAILQ_FOREACH(lun, &softc->lun_list,
2261						       links) {
2262						port->lun_enable(port->targ_lun_arg,
2263						    lun->target,
2264						    lun->lun);
2265					}
2266
2267					ctl_port_online(port);
2268				} else if (cmd == CTL_DISABLE_PORT) {
2269					struct ctl_lun *lun;
2270
2271					ctl_port_offline(port);
2272
2273					STAILQ_FOREACH(lun, &softc->lun_list,
2274						       links) {
2275						port->lun_disable(
2276						    port->targ_lun_arg,
2277						    lun->target,
2278						    lun->lun);
2279					}
2280				}
2281
2282				mtx_lock(&softc->ctl_lock);
2283
2284				if (cmd == CTL_SET_PORT_WWNS)
2285					ctl_port_set_wwns(port,
2286					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2287					    1 : 0, entry->wwnn,
2288					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2289					    1 : 0, entry->wwpn);
2290			}
2291			if (done != 0)
2292				break;
2293		}
2294		mtx_unlock(&softc->ctl_lock);
2295		break;
2296	}
2297	case CTL_GET_PORT_LIST: {
2298		struct ctl_port *port;
2299		struct ctl_port_list *list;
2300		int i;
2301
2302		list = (struct ctl_port_list *)addr;
2303
2304		if (list->alloc_len != (list->alloc_num *
2305		    sizeof(struct ctl_port_entry))) {
2306			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2307			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2308			       "%zu\n", __func__, list->alloc_len,
2309			       list->alloc_num, sizeof(struct ctl_port_entry));
2310			retval = EINVAL;
2311			break;
2312		}
2313		list->fill_len = 0;
2314		list->fill_num = 0;
2315		list->dropped_num = 0;
2316		i = 0;
2317		mtx_lock(&softc->ctl_lock);
2318		STAILQ_FOREACH(port, &softc->port_list, links) {
2319			struct ctl_port_entry entry, *list_entry;
2320
2321			if (list->fill_num >= list->alloc_num) {
2322				list->dropped_num++;
2323				continue;
2324			}
2325
2326			entry.port_type = port->port_type;
2327			strlcpy(entry.port_name, port->port_name,
2328				sizeof(entry.port_name));
2329			entry.targ_port = port->targ_port;
2330			entry.physical_port = port->physical_port;
2331			entry.virtual_port = port->virtual_port;
2332			entry.wwnn = port->wwnn;
2333			entry.wwpn = port->wwpn;
2334			if (port->status & CTL_PORT_STATUS_ONLINE)
2335				entry.online = 1;
2336			else
2337				entry.online = 0;
2338
2339			list_entry = &list->entries[i];
2340
2341			retval = copyout(&entry, list_entry, sizeof(entry));
2342			if (retval != 0) {
2343				printf("%s: CTL_GET_PORT_LIST: copyout "
2344				       "returned %d\n", __func__, retval);
2345				break;
2346			}
2347			i++;
2348			list->fill_num++;
2349			list->fill_len += sizeof(entry);
2350		}
2351		mtx_unlock(&softc->ctl_lock);
2352
2353		/*
2354		 * If this is non-zero, we had a copyout fault, so there's
2355		 * probably no point in attempting to set the status inside
2356		 * the structure.
2357		 */
2358		if (retval != 0)
2359			break;
2360
2361		if (list->dropped_num > 0)
2362			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2363		else
2364			list->status = CTL_PORT_LIST_OK;
2365		break;
2366	}
2367	case CTL_DUMP_OOA: {
2368		struct ctl_lun *lun;
2369		union ctl_io *io;
2370		char printbuf[128];
2371		struct sbuf sb;
2372
2373		mtx_lock(&softc->ctl_lock);
2374		printf("Dumping OOA queues:\n");
2375		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2376			mtx_lock(&lun->lun_lock);
2377			for (io = (union ctl_io *)TAILQ_FIRST(
2378			     &lun->ooa_queue); io != NULL;
2379			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2380			     ooa_links)) {
2381				sbuf_new(&sb, printbuf, sizeof(printbuf),
2382					 SBUF_FIXEDLEN);
2383				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2384					    (intmax_t)lun->lun,
2385					    io->scsiio.tag_num,
2386					    (io->io_hdr.flags &
2387					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2388					    (io->io_hdr.flags &
2389					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2390					    (io->io_hdr.flags &
2391					    CTL_FLAG_ABORT) ? " ABORT" : "",
2392			                    (io->io_hdr.flags &
2393		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2394				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2395				sbuf_finish(&sb);
2396				printf("%s\n", sbuf_data(&sb));
2397			}
2398			mtx_unlock(&lun->lun_lock);
2399		}
2400		printf("OOA queues dump done\n");
2401		mtx_unlock(&softc->ctl_lock);
2402		break;
2403	}
2404	case CTL_GET_OOA: {
2405		struct ctl_lun *lun;
2406		struct ctl_ooa *ooa_hdr;
2407		struct ctl_ooa_entry *entries;
2408		uint32_t cur_fill_num;
2409
2410		ooa_hdr = (struct ctl_ooa *)addr;
2411
2412		if ((ooa_hdr->alloc_len == 0)
2413		 || (ooa_hdr->alloc_num == 0)) {
2414			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2415			       "must be non-zero\n", __func__,
2416			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2417			retval = EINVAL;
2418			break;
2419		}
2420
2421		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2422		    sizeof(struct ctl_ooa_entry))) {
2423			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2424			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2425			       __func__, ooa_hdr->alloc_len,
2426			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2427			retval = EINVAL;
2428			break;
2429		}
2430
2431		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2432		if (entries == NULL) {
2433			printf("%s: could not allocate %d bytes for OOA "
2434			       "dump\n", __func__, ooa_hdr->alloc_len);
2435			retval = ENOMEM;
2436			break;
2437		}
2438
2439		mtx_lock(&softc->ctl_lock);
2440		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2441		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2442		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2443			mtx_unlock(&softc->ctl_lock);
2444			free(entries, M_CTL);
2445			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2446			       __func__, (uintmax_t)ooa_hdr->lun_num);
2447			retval = EINVAL;
2448			break;
2449		}
2450
2451		cur_fill_num = 0;
2452
2453		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2454			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2455				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2456					ooa_hdr, entries);
2457				if (retval != 0)
2458					break;
2459			}
2460			if (retval != 0) {
2461				mtx_unlock(&softc->ctl_lock);
2462				free(entries, M_CTL);
2463				break;
2464			}
2465		} else {
2466			lun = softc->ctl_luns[ooa_hdr->lun_num];
2467
2468			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2469						    entries);
2470		}
2471		mtx_unlock(&softc->ctl_lock);
2472
2473		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2474		ooa_hdr->fill_len = ooa_hdr->fill_num *
2475			sizeof(struct ctl_ooa_entry);
2476		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2477		if (retval != 0) {
2478			printf("%s: error copying out %d bytes for OOA dump\n",
2479			       __func__, ooa_hdr->fill_len);
2480		}
2481
2482		getbintime(&ooa_hdr->cur_bt);
2483
2484		if (cur_fill_num > ooa_hdr->alloc_num) {
2485			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2486			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2487		} else {
2488			ooa_hdr->dropped_num = 0;
2489			ooa_hdr->status = CTL_OOA_OK;
2490		}
2491
2492		free(entries, M_CTL);
2493		break;
2494	}
2495	case CTL_CHECK_OOA: {
2496		union ctl_io *io;
2497		struct ctl_lun *lun;
2498		struct ctl_ooa_info *ooa_info;
2499
2500
2501		ooa_info = (struct ctl_ooa_info *)addr;
2502
2503		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2504			ooa_info->status = CTL_OOA_INVALID_LUN;
2505			break;
2506		}
2507		mtx_lock(&softc->ctl_lock);
2508		lun = softc->ctl_luns[ooa_info->lun_id];
2509		if (lun == NULL) {
2510			mtx_unlock(&softc->ctl_lock);
2511			ooa_info->status = CTL_OOA_INVALID_LUN;
2512			break;
2513		}
2514		mtx_lock(&lun->lun_lock);
2515		mtx_unlock(&softc->ctl_lock);
2516		ooa_info->num_entries = 0;
2517		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2518		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2519		     &io->io_hdr, ooa_links)) {
2520			ooa_info->num_entries++;
2521		}
2522		mtx_unlock(&lun->lun_lock);
2523
2524		ooa_info->status = CTL_OOA_SUCCESS;
2525
2526		break;
2527	}
2528	case CTL_HARD_START:
2529	case CTL_HARD_STOP: {
2530		struct ctl_fe_ioctl_startstop_info ss_info;
2531		struct cfi_metatask *metatask;
2532		struct mtx hs_mtx;
2533
2534		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2535
2536		cv_init(&ss_info.sem, "hard start/stop cv" );
2537
2538		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2539		if (metatask == NULL) {
2540			retval = ENOMEM;
2541			mtx_destroy(&hs_mtx);
2542			break;
2543		}
2544
2545		if (cmd == CTL_HARD_START)
2546			metatask->tasktype = CFI_TASK_STARTUP;
2547		else
2548			metatask->tasktype = CFI_TASK_SHUTDOWN;
2549
2550		metatask->callback = ctl_ioctl_hard_startstop_callback;
2551		metatask->callback_arg = &ss_info;
2552
2553		cfi_action(metatask);
2554
2555		/* Wait for the callback */
2556		mtx_lock(&hs_mtx);
2557		cv_wait_sig(&ss_info.sem, &hs_mtx);
2558		mtx_unlock(&hs_mtx);
2559
2560		/*
2561		 * All information has been copied from the metatask by the
2562		 * time cv_broadcast() is called, so we free the metatask here.
2563		 */
2564		cfi_free_metatask(metatask);
2565
2566		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2567
2568		mtx_destroy(&hs_mtx);
2569		break;
2570	}
2571	case CTL_BBRREAD: {
2572		struct ctl_bbrread_info *bbr_info;
2573		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2574		struct mtx bbr_mtx;
2575		struct cfi_metatask *metatask;
2576
2577		bbr_info = (struct ctl_bbrread_info *)addr;
2578
2579		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2580
2581		bzero(&bbr_mtx, sizeof(bbr_mtx));
2582		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2583
2584		fe_bbr_info.bbr_info = bbr_info;
2585		fe_bbr_info.lock = &bbr_mtx;
2586
2587		cv_init(&fe_bbr_info.sem, "BBR read cv");
2588		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2589
2590		if (metatask == NULL) {
2591			mtx_destroy(&bbr_mtx);
2592			cv_destroy(&fe_bbr_info.sem);
2593			retval = ENOMEM;
2594			break;
2595		}
2596		metatask->tasktype = CFI_TASK_BBRREAD;
2597		metatask->callback = ctl_ioctl_bbrread_callback;
2598		metatask->callback_arg = &fe_bbr_info;
2599		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2600		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2601		metatask->taskinfo.bbrread.len = bbr_info->len;
2602
2603		cfi_action(metatask);
2604
2605		mtx_lock(&bbr_mtx);
2606		while (fe_bbr_info.wakeup_done == 0)
2607			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2608		mtx_unlock(&bbr_mtx);
2609
2610		bbr_info->status = metatask->status;
2611		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2612		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2613		memcpy(&bbr_info->sense_data,
2614		       &metatask->taskinfo.bbrread.sense_data,
2615		       ctl_min(sizeof(bbr_info->sense_data),
2616			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2617
2618		cfi_free_metatask(metatask);
2619
2620		mtx_destroy(&bbr_mtx);
2621		cv_destroy(&fe_bbr_info.sem);
2622
2623		break;
2624	}
2625	case CTL_DELAY_IO: {
2626		struct ctl_io_delay_info *delay_info;
2627#ifdef CTL_IO_DELAY
2628		struct ctl_lun *lun;
2629#endif /* CTL_IO_DELAY */
2630
2631		delay_info = (struct ctl_io_delay_info *)addr;
2632
2633#ifdef CTL_IO_DELAY
2634		mtx_lock(&softc->ctl_lock);
2635
2636		if ((delay_info->lun_id > CTL_MAX_LUNS)
2637		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2638			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2639		} else {
2640			lun = softc->ctl_luns[delay_info->lun_id];
2641			mtx_lock(&lun->lun_lock);
2642
2643			delay_info->status = CTL_DELAY_STATUS_OK;
2644
2645			switch (delay_info->delay_type) {
2646			case CTL_DELAY_TYPE_CONT:
2647				break;
2648			case CTL_DELAY_TYPE_ONESHOT:
2649				break;
2650			default:
2651				delay_info->status =
2652					CTL_DELAY_STATUS_INVALID_TYPE;
2653				break;
2654			}
2655
2656			switch (delay_info->delay_loc) {
2657			case CTL_DELAY_LOC_DATAMOVE:
2658				lun->delay_info.datamove_type =
2659					delay_info->delay_type;
2660				lun->delay_info.datamove_delay =
2661					delay_info->delay_secs;
2662				break;
2663			case CTL_DELAY_LOC_DONE:
2664				lun->delay_info.done_type =
2665					delay_info->delay_type;
2666				lun->delay_info.done_delay =
2667					delay_info->delay_secs;
2668				break;
2669			default:
2670				delay_info->status =
2671					CTL_DELAY_STATUS_INVALID_LOC;
2672				break;
2673			}
2674			mtx_unlock(&lun->lun_lock);
2675		}
2676
2677		mtx_unlock(&softc->ctl_lock);
2678#else
2679		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2680#endif /* CTL_IO_DELAY */
2681		break;
2682	}
2683	case CTL_REALSYNC_SET: {
2684		int *syncstate;
2685
2686		syncstate = (int *)addr;
2687
2688		mtx_lock(&softc->ctl_lock);
2689		switch (*syncstate) {
2690		case 0:
2691			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2692			break;
2693		case 1:
2694			softc->flags |= CTL_FLAG_REAL_SYNC;
2695			break;
2696		default:
2697			retval = EINVAL;
2698			break;
2699		}
2700		mtx_unlock(&softc->ctl_lock);
2701		break;
2702	}
2703	case CTL_REALSYNC_GET: {
2704		int *syncstate;
2705
2706		syncstate = (int*)addr;
2707
2708		mtx_lock(&softc->ctl_lock);
2709		if (softc->flags & CTL_FLAG_REAL_SYNC)
2710			*syncstate = 1;
2711		else
2712			*syncstate = 0;
2713		mtx_unlock(&softc->ctl_lock);
2714
2715		break;
2716	}
2717	case CTL_SETSYNC:
2718	case CTL_GETSYNC: {
2719		struct ctl_sync_info *sync_info;
2720		struct ctl_lun *lun;
2721
2722		sync_info = (struct ctl_sync_info *)addr;
2723
2724		mtx_lock(&softc->ctl_lock);
2725		lun = softc->ctl_luns[sync_info->lun_id];
2726		if (lun == NULL) {
2727			mtx_unlock(&softc->ctl_lock);
2728			sync_info->status = CTL_GS_SYNC_NO_LUN;
2729		}
2730		/*
2731		 * Get or set the sync interval.  We're not bounds checking
2732		 * in the set case, hopefully the user won't do something
2733		 * silly.
2734		 */
2735		mtx_lock(&lun->lun_lock);
2736		mtx_unlock(&softc->ctl_lock);
2737		if (cmd == CTL_GETSYNC)
2738			sync_info->sync_interval = lun->sync_interval;
2739		else
2740			lun->sync_interval = sync_info->sync_interval;
2741		mtx_unlock(&lun->lun_lock);
2742
2743		sync_info->status = CTL_GS_SYNC_OK;
2744
2745		break;
2746	}
2747	case CTL_GETSTATS: {
2748		struct ctl_stats *stats;
2749		struct ctl_lun *lun;
2750		int i;
2751
2752		stats = (struct ctl_stats *)addr;
2753
2754		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2755		     stats->alloc_len) {
2756			stats->status = CTL_SS_NEED_MORE_SPACE;
2757			stats->num_luns = softc->num_luns;
2758			break;
2759		}
2760		/*
2761		 * XXX KDM no locking here.  If the LUN list changes,
2762		 * things can blow up.
2763		 */
2764		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2765		     i++, lun = STAILQ_NEXT(lun, links)) {
2766			retval = copyout(&lun->stats, &stats->lun_stats[i],
2767					 sizeof(lun->stats));
2768			if (retval != 0)
2769				break;
2770		}
2771		stats->num_luns = softc->num_luns;
2772		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2773				 softc->num_luns;
2774		stats->status = CTL_SS_OK;
2775#ifdef CTL_TIME_IO
2776		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2777#else
2778		stats->flags = CTL_STATS_FLAG_NONE;
2779#endif
2780		getnanouptime(&stats->timestamp);
2781		break;
2782	}
2783	case CTL_ERROR_INJECT: {
2784		struct ctl_error_desc *err_desc, *new_err_desc;
2785		struct ctl_lun *lun;
2786
2787		err_desc = (struct ctl_error_desc *)addr;
2788
2789		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2790				      M_WAITOK | M_ZERO);
2791		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2792
2793		mtx_lock(&softc->ctl_lock);
2794		lun = softc->ctl_luns[err_desc->lun_id];
2795		if (lun == NULL) {
2796			mtx_unlock(&softc->ctl_lock);
2797			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2798			       __func__, (uintmax_t)err_desc->lun_id);
2799			retval = EINVAL;
2800			break;
2801		}
2802		mtx_lock(&lun->lun_lock);
2803		mtx_unlock(&softc->ctl_lock);
2804
2805		/*
2806		 * We could do some checking here to verify the validity
2807		 * of the request, but given the complexity of error
2808		 * injection requests, the checking logic would be fairly
2809		 * complex.
2810		 *
2811		 * For now, if the request is invalid, it just won't get
2812		 * executed and might get deleted.
2813		 */
2814		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2815
2816		/*
2817		 * XXX KDM check to make sure the serial number is unique,
2818		 * in case we somehow manage to wrap.  That shouldn't
2819		 * happen for a very long time, but it's the right thing to
2820		 * do.
2821		 */
2822		new_err_desc->serial = lun->error_serial;
2823		err_desc->serial = lun->error_serial;
2824		lun->error_serial++;
2825
2826		mtx_unlock(&lun->lun_lock);
2827		break;
2828	}
2829	case CTL_ERROR_INJECT_DELETE: {
2830		struct ctl_error_desc *delete_desc, *desc, *desc2;
2831		struct ctl_lun *lun;
2832		int delete_done;
2833
2834		delete_desc = (struct ctl_error_desc *)addr;
2835		delete_done = 0;
2836
2837		mtx_lock(&softc->ctl_lock);
2838		lun = softc->ctl_luns[delete_desc->lun_id];
2839		if (lun == NULL) {
2840			mtx_unlock(&softc->ctl_lock);
2841			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2842			       __func__, (uintmax_t)delete_desc->lun_id);
2843			retval = EINVAL;
2844			break;
2845		}
2846		mtx_lock(&lun->lun_lock);
2847		mtx_unlock(&softc->ctl_lock);
2848		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2849			if (desc->serial != delete_desc->serial)
2850				continue;
2851
2852			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2853				      links);
2854			free(desc, M_CTL);
2855			delete_done = 1;
2856		}
2857		mtx_unlock(&lun->lun_lock);
2858		if (delete_done == 0) {
2859			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2860			       "error serial %ju on LUN %u\n", __func__,
2861			       delete_desc->serial, delete_desc->lun_id);
2862			retval = EINVAL;
2863			break;
2864		}
2865		break;
2866	}
2867	case CTL_DUMP_STRUCTS: {
2868		int i, j, k;
2869		struct ctl_port *port;
2870		struct ctl_frontend *fe;
2871
2872		printf("CTL IID to WWPN map start:\n");
2873		for (i = 0; i < CTL_MAX_PORTS; i++) {
2874			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2875				if (softc->wwpn_iid[i][j].in_use == 0)
2876					continue;
2877
2878				printf("port %d iid %u WWPN %#jx\n",
2879				       softc->wwpn_iid[i][j].port,
2880				       softc->wwpn_iid[i][j].iid,
2881				       (uintmax_t)softc->wwpn_iid[i][j].wwpn);
2882			}
2883		}
2884		printf("CTL IID to WWPN map end\n");
2885		printf("CTL Persistent Reservation information start:\n");
2886		for (i = 0; i < CTL_MAX_LUNS; i++) {
2887			struct ctl_lun *lun;
2888
2889			lun = softc->ctl_luns[i];
2890
2891			if ((lun == NULL)
2892			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2893				continue;
2894
2895			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2896				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2897					if (lun->per_res[j+k].registered == 0)
2898						continue;
2899					printf("LUN %d port %d iid %d key "
2900					       "%#jx\n", i, j, k,
2901					       (uintmax_t)scsi_8btou64(
2902					       lun->per_res[j+k].res_key.key));
2903				}
2904			}
2905		}
2906		printf("CTL Persistent Reservation information end\n");
2907		printf("CTL Ports:\n");
2908		/*
2909		 * XXX KDM calling this without a lock.  We'd likely want
2910		 * to drop the lock before calling the frontend's dump
2911		 * routine anyway.
2912		 */
2913		STAILQ_FOREACH(port, &softc->port_list, links) {
2914			printf("Port %s Frontend %s Type %u pport %d vport %d WWNN "
2915			       "%#jx WWPN %#jx\n", port->port_name,
2916			       port->frontend->name, port->port_type,
2917			       port->physical_port, port->virtual_port,
2918			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2919		}
2920		printf("CTL Port information end\n");
2921		printf("CTL Frontends:\n");
2922		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2923			printf("Frontend %s\n", fe->name);
2924			if (fe->fe_dump != NULL)
2925				fe->fe_dump();
2926		}
2927		printf("CTL Frontend information end\n");
2928		break;
2929	}
2930	case CTL_LUN_REQ: {
2931		struct ctl_lun_req *lun_req;
2932		struct ctl_backend_driver *backend;
2933
2934		lun_req = (struct ctl_lun_req *)addr;
2935
2936		backend = ctl_backend_find(lun_req->backend);
2937		if (backend == NULL) {
2938			lun_req->status = CTL_LUN_ERROR;
2939			snprintf(lun_req->error_str,
2940				 sizeof(lun_req->error_str),
2941				 "Backend \"%s\" not found.",
2942				 lun_req->backend);
2943			break;
2944		}
2945		if (lun_req->num_be_args > 0) {
2946			lun_req->kern_be_args = ctl_copyin_args(
2947				lun_req->num_be_args,
2948				lun_req->be_args,
2949				lun_req->error_str,
2950				sizeof(lun_req->error_str));
2951			if (lun_req->kern_be_args == NULL) {
2952				lun_req->status = CTL_LUN_ERROR;
2953				break;
2954			}
2955		}
2956
2957		retval = backend->ioctl(dev, cmd, addr, flag, td);
2958
2959		if (lun_req->num_be_args > 0) {
2960			ctl_copyout_args(lun_req->num_be_args,
2961				      lun_req->kern_be_args);
2962			ctl_free_args(lun_req->num_be_args,
2963				      lun_req->kern_be_args);
2964		}
2965		break;
2966	}
2967	case CTL_LUN_LIST: {
2968		struct sbuf *sb;
2969		struct ctl_lun *lun;
2970		struct ctl_lun_list *list;
2971		struct ctl_option *opt;
2972
2973		list = (struct ctl_lun_list *)addr;
2974
2975		/*
2976		 * Allocate a fixed length sbuf here, based on the length
2977		 * of the user's buffer.  We could allocate an auto-extending
2978		 * buffer, and then tell the user how much larger our
2979		 * amount of data is than his buffer, but that presents
2980		 * some problems:
2981		 *
2982		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2983		 *     we can't hold a lock while calling them with an
2984		 *     auto-extending buffer.
2985 		 *
2986		 * 2.  There is not currently a LUN reference counting
2987		 *     mechanism, outside of outstanding transactions on
2988		 *     the LUN's OOA queue.  So a LUN could go away on us
2989		 *     while we're getting the LUN number, backend-specific
2990		 *     information, etc.  Thus, given the way things
2991		 *     currently work, we need to hold the CTL lock while
2992		 *     grabbing LUN information.
2993		 *
2994		 * So, from the user's standpoint, the best thing to do is
2995		 * allocate what he thinks is a reasonable buffer length,
2996		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2997		 * double the buffer length and try again.  (And repeat
2998		 * that until he succeeds.)
2999		 */
3000		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3001		if (sb == NULL) {
3002			list->status = CTL_LUN_LIST_ERROR;
3003			snprintf(list->error_str, sizeof(list->error_str),
3004				 "Unable to allocate %d bytes for LUN list",
3005				 list->alloc_len);
3006			break;
3007		}
3008
3009		sbuf_printf(sb, "<ctllunlist>\n");
3010
3011		mtx_lock(&softc->ctl_lock);
3012		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3013			mtx_lock(&lun->lun_lock);
3014			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3015					     (uintmax_t)lun->lun);
3016
3017			/*
3018			 * Bail out as soon as we see that we've overfilled
3019			 * the buffer.
3020			 */
3021			if (retval != 0)
3022				break;
3023
3024			retval = sbuf_printf(sb, "\t<backend_type>%s"
3025					     "</backend_type>\n",
3026					     (lun->backend == NULL) ?  "none" :
3027					     lun->backend->name);
3028
3029			if (retval != 0)
3030				break;
3031
3032			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3033					     lun->be_lun->lun_type);
3034
3035			if (retval != 0)
3036				break;
3037
3038			if (lun->backend == NULL) {
3039				retval = sbuf_printf(sb, "</lun>\n");
3040				if (retval != 0)
3041					break;
3042				continue;
3043			}
3044
3045			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3046					     (lun->be_lun->maxlba > 0) ?
3047					     lun->be_lun->maxlba + 1 : 0);
3048
3049			if (retval != 0)
3050				break;
3051
3052			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3053					     lun->be_lun->blocksize);
3054
3055			if (retval != 0)
3056				break;
3057
3058			retval = sbuf_printf(sb, "\t<serial_number>");
3059
3060			if (retval != 0)
3061				break;
3062
3063			retval = ctl_sbuf_printf_esc(sb,
3064						     lun->be_lun->serial_num);
3065
3066			if (retval != 0)
3067				break;
3068
3069			retval = sbuf_printf(sb, "</serial_number>\n");
3070
3071			if (retval != 0)
3072				break;
3073
3074			retval = sbuf_printf(sb, "\t<device_id>");
3075
3076			if (retval != 0)
3077				break;
3078
3079			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3080
3081			if (retval != 0)
3082				break;
3083
3084			retval = sbuf_printf(sb, "</device_id>\n");
3085
3086			if (retval != 0)
3087				break;
3088
3089			if (lun->backend->lun_info != NULL) {
3090				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3091				if (retval != 0)
3092					break;
3093			}
3094			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3095				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3096				    opt->name, opt->value, opt->name);
3097				if (retval != 0)
3098					break;
3099			}
3100
3101			retval = sbuf_printf(sb, "</lun>\n");
3102
3103			if (retval != 0)
3104				break;
3105			mtx_unlock(&lun->lun_lock);
3106		}
3107		if (lun != NULL)
3108			mtx_unlock(&lun->lun_lock);
3109		mtx_unlock(&softc->ctl_lock);
3110
3111		if ((retval != 0)
3112		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3113			retval = 0;
3114			sbuf_delete(sb);
3115			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3116			snprintf(list->error_str, sizeof(list->error_str),
3117				 "Out of space, %d bytes is too small",
3118				 list->alloc_len);
3119			break;
3120		}
3121
3122		sbuf_finish(sb);
3123
3124		retval = copyout(sbuf_data(sb), list->lun_xml,
3125				 sbuf_len(sb) + 1);
3126
3127		list->fill_len = sbuf_len(sb) + 1;
3128		list->status = CTL_LUN_LIST_OK;
3129		sbuf_delete(sb);
3130		break;
3131	}
3132	case CTL_ISCSI: {
3133		struct ctl_iscsi *ci;
3134		struct ctl_frontend *fe;
3135
3136		ci = (struct ctl_iscsi *)addr;
3137
3138		fe = ctl_frontend_find("iscsi");
3139		if (fe == NULL) {
3140			ci->status = CTL_ISCSI_ERROR;
3141			snprintf(ci->error_str, sizeof(ci->error_str),
3142			    "Frontend \"iscsi\" not found.");
3143			break;
3144		}
3145
3146		retval = fe->ioctl(dev, cmd, addr, flag, td);
3147		break;
3148	}
3149	case CTL_PORT_REQ: {
3150		struct ctl_req *req;
3151		struct ctl_frontend *fe;
3152
3153		req = (struct ctl_req *)addr;
3154
3155		fe = ctl_frontend_find(req->driver);
3156		if (fe == NULL) {
3157			req->status = CTL_LUN_ERROR;
3158			snprintf(req->error_str, sizeof(req->error_str),
3159			    "Frontend \"%s\" not found.", req->driver);
3160			break;
3161		}
3162		if (req->num_args > 0) {
3163			req->kern_args = ctl_copyin_args(req->num_args,
3164			    req->args, req->error_str, sizeof(req->error_str));
3165			if (req->kern_args == NULL) {
3166				req->status = CTL_LUN_ERROR;
3167				break;
3168			}
3169		}
3170
3171		retval = fe->ioctl(dev, cmd, addr, flag, td);
3172
3173		if (req->num_args > 0) {
3174			ctl_copyout_args(req->num_args, req->kern_args);
3175			ctl_free_args(req->num_args, req->kern_args);
3176		}
3177		break;
3178	}
3179	case CTL_PORT_LIST: {
3180		struct sbuf *sb;
3181		struct ctl_port *port;
3182		struct ctl_lun_list *list;
3183		struct ctl_option *opt;
3184
3185		list = (struct ctl_lun_list *)addr;
3186
3187		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3188		if (sb == NULL) {
3189			list->status = CTL_LUN_LIST_ERROR;
3190			snprintf(list->error_str, sizeof(list->error_str),
3191				 "Unable to allocate %d bytes for LUN list",
3192				 list->alloc_len);
3193			break;
3194		}
3195
3196		sbuf_printf(sb, "<ctlportlist>\n");
3197
3198		mtx_lock(&softc->ctl_lock);
3199		STAILQ_FOREACH(port, &softc->port_list, links) {
3200			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3201					     (uintmax_t)port->targ_port);
3202
3203			/*
3204			 * Bail out as soon as we see that we've overfilled
3205			 * the buffer.
3206			 */
3207			if (retval != 0)
3208				break;
3209
3210			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3211			    "</frontend_type>\n", port->frontend->name);
3212			if (retval != 0)
3213				break;
3214
3215			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3216					     port->port_type);
3217			if (retval != 0)
3218				break;
3219
3220			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3221			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3222			if (retval != 0)
3223				break;
3224
3225			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3226			    port->port_name);
3227			if (retval != 0)
3228				break;
3229
3230			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3231			    port->physical_port);
3232			if (retval != 0)
3233				break;
3234
3235			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3236			    port->virtual_port);
3237			if (retval != 0)
3238				break;
3239
3240			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3241			    (uintmax_t)port->wwnn);
3242			if (retval != 0)
3243				break;
3244
3245			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3246			    (uintmax_t)port->wwpn);
3247			if (retval != 0)
3248				break;
3249
3250			STAILQ_FOREACH(opt, &port->options, links) {
3251				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3252				    opt->name, opt->value, opt->name);
3253				if (retval != 0)
3254					break;
3255			}
3256
3257			retval = sbuf_printf(sb, "</targ_port>\n");
3258			if (retval != 0)
3259				break;
3260		}
3261		mtx_unlock(&softc->ctl_lock);
3262
3263		if ((retval != 0)
3264		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3265			retval = 0;
3266			sbuf_delete(sb);
3267			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3268			snprintf(list->error_str, sizeof(list->error_str),
3269				 "Out of space, %d bytes is too small",
3270				 list->alloc_len);
3271			break;
3272		}
3273
3274		sbuf_finish(sb);
3275
3276		retval = copyout(sbuf_data(sb), list->lun_xml,
3277				 sbuf_len(sb) + 1);
3278
3279		list->fill_len = sbuf_len(sb) + 1;
3280		list->status = CTL_LUN_LIST_OK;
3281		sbuf_delete(sb);
3282		break;
3283	}
3284	default: {
3285		/* XXX KDM should we fix this? */
3286#if 0
3287		struct ctl_backend_driver *backend;
3288		unsigned int type;
3289		int found;
3290
3291		found = 0;
3292
3293		/*
3294		 * We encode the backend type as the ioctl type for backend
3295		 * ioctls.  So parse it out here, and then search for a
3296		 * backend of this type.
3297		 */
3298		type = _IOC_TYPE(cmd);
3299
3300		STAILQ_FOREACH(backend, &softc->be_list, links) {
3301			if (backend->type == type) {
3302				found = 1;
3303				break;
3304			}
3305		}
3306		if (found == 0) {
3307			printf("ctl: unknown ioctl command %#lx or backend "
3308			       "%d\n", cmd, type);
3309			retval = EINVAL;
3310			break;
3311		}
3312		retval = backend->ioctl(dev, cmd, addr, flag, td);
3313#endif
3314		retval = ENOTTY;
3315		break;
3316	}
3317	}
3318	return (retval);
3319}
3320
3321uint32_t
3322ctl_get_initindex(struct ctl_nexus *nexus)
3323{
3324	if (nexus->targ_port < CTL_MAX_PORTS)
3325		return (nexus->initid.id +
3326			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3327	else
3328		return (nexus->initid.id +
3329		       ((nexus->targ_port - CTL_MAX_PORTS) *
3330			CTL_MAX_INIT_PER_PORT));
3331}
3332
3333uint32_t
3334ctl_get_resindex(struct ctl_nexus *nexus)
3335{
3336	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3337}
3338
3339uint32_t
3340ctl_port_idx(int port_num)
3341{
3342	if (port_num < CTL_MAX_PORTS)
3343		return(port_num);
3344	else
3345		return(port_num - CTL_MAX_PORTS);
3346}
3347
3348/*
3349 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3350 * that are a power of 2.
3351 */
3352int
3353ctl_ffz(uint32_t *mask, uint32_t size)
3354{
3355	uint32_t num_chunks, num_pieces;
3356	int i, j;
3357
3358	num_chunks = (size >> 5);
3359	if (num_chunks == 0)
3360		num_chunks++;
3361	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3362
3363	for (i = 0; i < num_chunks; i++) {
3364		for (j = 0; j < num_pieces; j++) {
3365			if ((mask[i] & (1 << j)) == 0)
3366				return ((i << 5) + j);
3367		}
3368	}
3369
3370	return (-1);
3371}
3372
3373int
3374ctl_set_mask(uint32_t *mask, uint32_t bit)
3375{
3376	uint32_t chunk, piece;
3377
3378	chunk = bit >> 5;
3379	piece = bit % (sizeof(uint32_t) * 8);
3380
3381	if ((mask[chunk] & (1 << piece)) != 0)
3382		return (-1);
3383	else
3384		mask[chunk] |= (1 << piece);
3385
3386	return (0);
3387}
3388
3389int
3390ctl_clear_mask(uint32_t *mask, uint32_t bit)
3391{
3392	uint32_t chunk, piece;
3393
3394	chunk = bit >> 5;
3395	piece = bit % (sizeof(uint32_t) * 8);
3396
3397	if ((mask[chunk] & (1 << piece)) == 0)
3398		return (-1);
3399	else
3400		mask[chunk] &= ~(1 << piece);
3401
3402	return (0);
3403}
3404
3405int
3406ctl_is_set(uint32_t *mask, uint32_t bit)
3407{
3408	uint32_t chunk, piece;
3409
3410	chunk = bit >> 5;
3411	piece = bit % (sizeof(uint32_t) * 8);
3412
3413	if ((mask[chunk] & (1 << piece)) == 0)
3414		return (0);
3415	else
3416		return (1);
3417}
3418
3419#ifdef unused
3420/*
3421 * The bus, target and lun are optional, they can be filled in later.
3422 * can_wait is used to determine whether we can wait on the malloc or not.
3423 */
3424union ctl_io*
3425ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3426	      uint32_t targ_lun, int can_wait)
3427{
3428	union ctl_io *io;
3429
3430	if (can_wait)
3431		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3432	else
3433		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3434
3435	if (io != NULL) {
3436		io->io_hdr.io_type = io_type;
3437		io->io_hdr.targ_port = targ_port;
3438		/*
3439		 * XXX KDM this needs to change/go away.  We need to move
3440		 * to a preallocated pool of ctl_scsiio structures.
3441		 */
3442		io->io_hdr.nexus.targ_target.id = targ_target;
3443		io->io_hdr.nexus.targ_lun = targ_lun;
3444	}
3445
3446	return (io);
3447}
3448
3449void
3450ctl_kfree_io(union ctl_io *io)
3451{
3452	free(io, M_CTL);
3453}
3454#endif /* unused */
3455
3456/*
3457 * ctl_softc, pool_type, total_ctl_io are passed in.
3458 * npool is passed out.
3459 */
3460int
3461ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3462		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3463{
3464	uint32_t i;
3465	union ctl_io *cur_io, *next_io;
3466	struct ctl_io_pool *pool;
3467	int retval;
3468
3469	retval = 0;
3470
3471	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3472					    M_NOWAIT | M_ZERO);
3473	if (pool == NULL) {
3474		retval = ENOMEM;
3475		goto bailout;
3476	}
3477
3478	pool->type = pool_type;
3479	pool->ctl_softc = ctl_softc;
3480
3481	mtx_lock(&ctl_softc->pool_lock);
3482	pool->id = ctl_softc->cur_pool_id++;
3483	mtx_unlock(&ctl_softc->pool_lock);
3484
3485	pool->flags = CTL_POOL_FLAG_NONE;
3486	pool->refcount = 1;		/* Reference for validity. */
3487	STAILQ_INIT(&pool->free_queue);
3488
3489	/*
3490	 * XXX KDM other options here:
3491	 * - allocate a page at a time
3492	 * - allocate one big chunk of memory.
3493	 * Page allocation might work well, but would take a little more
3494	 * tracking.
3495	 */
3496	for (i = 0; i < total_ctl_io; i++) {
3497		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3498						M_NOWAIT);
3499		if (cur_io == NULL) {
3500			retval = ENOMEM;
3501			break;
3502		}
3503		cur_io->io_hdr.pool = pool;
3504		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3505		pool->total_ctl_io++;
3506		pool->free_ctl_io++;
3507	}
3508
3509	if (retval != 0) {
3510		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3511		     cur_io != NULL; cur_io = next_io) {
3512			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3513							      links);
3514			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3515				      ctl_io_hdr, links);
3516			free(cur_io, M_CTLIO);
3517		}
3518
3519		free(pool, M_CTL);
3520		goto bailout;
3521	}
3522	mtx_lock(&ctl_softc->pool_lock);
3523	ctl_softc->num_pools++;
3524	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3525	/*
3526	 * Increment our usage count if this is an external consumer, so we
3527	 * can't get unloaded until the external consumer (most likely a
3528	 * FETD) unloads and frees his pool.
3529	 *
3530	 * XXX KDM will this increment the caller's module use count, or
3531	 * mine?
3532	 */
3533#if 0
3534	if ((pool_type != CTL_POOL_EMERGENCY)
3535	 && (pool_type != CTL_POOL_INTERNAL)
3536	 && (pool_type != CTL_POOL_4OTHERSC))
3537		MOD_INC_USE_COUNT;
3538#endif
3539
3540	mtx_unlock(&ctl_softc->pool_lock);
3541
3542	*npool = pool;
3543
3544bailout:
3545
3546	return (retval);
3547}
3548
3549static int
3550ctl_pool_acquire(struct ctl_io_pool *pool)
3551{
3552
3553	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3554
3555	if (pool->flags & CTL_POOL_FLAG_INVALID)
3556		return (EINVAL);
3557
3558	pool->refcount++;
3559
3560	return (0);
3561}
3562
3563static void
3564ctl_pool_release(struct ctl_io_pool *pool)
3565{
3566	struct ctl_softc *ctl_softc = pool->ctl_softc;
3567	union ctl_io *io;
3568
3569	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3570
3571	if (--pool->refcount != 0)
3572		return;
3573
3574	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3575		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3576			      links);
3577		free(io, M_CTLIO);
3578	}
3579
3580	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3581	ctl_softc->num_pools--;
3582
3583	/*
3584	 * XXX KDM will this decrement the caller's usage count or mine?
3585	 */
3586#if 0
3587	if ((pool->type != CTL_POOL_EMERGENCY)
3588	 && (pool->type != CTL_POOL_INTERNAL)
3589	 && (pool->type != CTL_POOL_4OTHERSC))
3590		MOD_DEC_USE_COUNT;
3591#endif
3592
3593	free(pool, M_CTL);
3594}
3595
3596void
3597ctl_pool_free(struct ctl_io_pool *pool)
3598{
3599	struct ctl_softc *ctl_softc;
3600
3601	if (pool == NULL)
3602		return;
3603
3604	ctl_softc = pool->ctl_softc;
3605	mtx_lock(&ctl_softc->pool_lock);
3606	pool->flags |= CTL_POOL_FLAG_INVALID;
3607	ctl_pool_release(pool);
3608	mtx_unlock(&ctl_softc->pool_lock);
3609}
3610
3611/*
3612 * This routine does not block (except for spinlocks of course).
3613 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3614 * possible.
3615 */
3616union ctl_io *
3617ctl_alloc_io(void *pool_ref)
3618{
3619	union ctl_io *io;
3620	struct ctl_softc *ctl_softc;
3621	struct ctl_io_pool *pool, *npool;
3622	struct ctl_io_pool *emergency_pool;
3623
3624	pool = (struct ctl_io_pool *)pool_ref;
3625
3626	if (pool == NULL) {
3627		printf("%s: pool is NULL\n", __func__);
3628		return (NULL);
3629	}
3630
3631	emergency_pool = NULL;
3632
3633	ctl_softc = pool->ctl_softc;
3634
3635	mtx_lock(&ctl_softc->pool_lock);
3636	/*
3637	 * First, try to get the io structure from the user's pool.
3638	 */
3639	if (ctl_pool_acquire(pool) == 0) {
3640		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3641		if (io != NULL) {
3642			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3643			pool->total_allocated++;
3644			pool->free_ctl_io--;
3645			mtx_unlock(&ctl_softc->pool_lock);
3646			return (io);
3647		} else
3648			ctl_pool_release(pool);
3649	}
3650	/*
3651	 * If he doesn't have any io structures left, search for an
3652	 * emergency pool and grab one from there.
3653	 */
3654	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3655		if (npool->type != CTL_POOL_EMERGENCY)
3656			continue;
3657
3658		if (ctl_pool_acquire(npool) != 0)
3659			continue;
3660
3661		emergency_pool = npool;
3662
3663		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3664		if (io != NULL) {
3665			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3666			npool->total_allocated++;
3667			npool->free_ctl_io--;
3668			mtx_unlock(&ctl_softc->pool_lock);
3669			return (io);
3670		} else
3671			ctl_pool_release(npool);
3672	}
3673
3674	/* Drop the spinlock before we malloc */
3675	mtx_unlock(&ctl_softc->pool_lock);
3676
3677	/*
3678	 * The emergency pool (if it exists) didn't have one, so try an
3679	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3680	 */
3681	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3682	if (io != NULL) {
3683		/*
3684		 * If the emergency pool exists but is empty, add this
3685		 * ctl_io to its list when it gets freed.
3686		 */
3687		if (emergency_pool != NULL) {
3688			mtx_lock(&ctl_softc->pool_lock);
3689			if (ctl_pool_acquire(emergency_pool) == 0) {
3690				io->io_hdr.pool = emergency_pool;
3691				emergency_pool->total_ctl_io++;
3692				/*
3693				 * Need to bump this, otherwise
3694				 * total_allocated and total_freed won't
3695				 * match when we no longer have anything
3696				 * outstanding.
3697				 */
3698				emergency_pool->total_allocated++;
3699			}
3700			mtx_unlock(&ctl_softc->pool_lock);
3701		} else
3702			io->io_hdr.pool = NULL;
3703	}
3704
3705	return (io);
3706}
3707
3708void
3709ctl_free_io(union ctl_io *io)
3710{
3711	if (io == NULL)
3712		return;
3713
3714	/*
3715	 * If this ctl_io has a pool, return it to that pool.
3716	 */
3717	if (io->io_hdr.pool != NULL) {
3718		struct ctl_io_pool *pool;
3719
3720		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3721		mtx_lock(&pool->ctl_softc->pool_lock);
3722		io->io_hdr.io_type = 0xff;
3723		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3724		pool->total_freed++;
3725		pool->free_ctl_io++;
3726		ctl_pool_release(pool);
3727		mtx_unlock(&pool->ctl_softc->pool_lock);
3728	} else {
3729		/*
3730		 * Otherwise, just free it.  We probably malloced it and
3731		 * the emergency pool wasn't available.
3732		 */
3733		free(io, M_CTLIO);
3734	}
3735
3736}
3737
3738void
3739ctl_zero_io(union ctl_io *io)
3740{
3741	void *pool_ref;
3742
3743	if (io == NULL)
3744		return;
3745
3746	/*
3747	 * May need to preserve linked list pointers at some point too.
3748	 */
3749	pool_ref = io->io_hdr.pool;
3750
3751	memset(io, 0, sizeof(*io));
3752
3753	io->io_hdr.pool = pool_ref;
3754}
3755
3756/*
3757 * This routine is currently used for internal copies of ctl_ios that need
3758 * to persist for some reason after we've already returned status to the
3759 * FETD.  (Thus the flag set.)
3760 *
3761 * XXX XXX
3762 * Note that this makes a blind copy of all fields in the ctl_io, except
3763 * for the pool reference.  This includes any memory that has been
3764 * allocated!  That memory will no longer be valid after done has been
3765 * called, so this would be VERY DANGEROUS for command that actually does
3766 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3767 * start and stop commands, which don't transfer any data, so this is not a
3768 * problem.  If it is used for anything else, the caller would also need to
3769 * allocate data buffer space and this routine would need to be modified to
3770 * copy the data buffer(s) as well.
3771 */
3772void
3773ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3774{
3775	void *pool_ref;
3776
3777	if ((src == NULL)
3778	 || (dest == NULL))
3779		return;
3780
3781	/*
3782	 * May need to preserve linked list pointers at some point too.
3783	 */
3784	pool_ref = dest->io_hdr.pool;
3785
3786	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3787
3788	dest->io_hdr.pool = pool_ref;
3789	/*
3790	 * We need to know that this is an internal copy, and doesn't need
3791	 * to get passed back to the FETD that allocated it.
3792	 */
3793	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3794}
3795
3796#ifdef NEEDTOPORT
3797static void
3798ctl_update_power_subpage(struct copan_power_subpage *page)
3799{
3800	int num_luns, num_partitions, config_type;
3801	struct ctl_softc *softc;
3802	cs_BOOL_t aor_present, shelf_50pct_power;
3803	cs_raidset_personality_t rs_type;
3804	int max_active_luns;
3805
3806	softc = control_softc;
3807
3808	/* subtract out the processor LUN */
3809	num_luns = softc->num_luns - 1;
3810	/*
3811	 * Default to 7 LUNs active, which was the only number we allowed
3812	 * in the past.
3813	 */
3814	max_active_luns = 7;
3815
3816	num_partitions = config_GetRsPartitionInfo();
3817	config_type = config_GetConfigType();
3818	shelf_50pct_power = config_GetShelfPowerMode();
3819	aor_present = config_IsAorRsPresent();
3820
3821	rs_type = ddb_GetRsRaidType(1);
3822	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3823	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3824		EPRINT(0, "Unsupported RS type %d!", rs_type);
3825	}
3826
3827
3828	page->total_luns = num_luns;
3829
3830	switch (config_type) {
3831	case 40:
3832		/*
3833		 * In a 40 drive configuration, it doesn't matter what DC
3834		 * cards we have, whether we have AOR enabled or not,
3835		 * partitioning or not, or what type of RAIDset we have.
3836		 * In that scenario, we can power up every LUN we present
3837		 * to the user.
3838		 */
3839		max_active_luns = num_luns;
3840
3841		break;
3842	case 64:
3843		if (shelf_50pct_power == CS_FALSE) {
3844			/* 25% power */
3845			if (aor_present == CS_TRUE) {
3846				if (rs_type ==
3847				     CS_RAIDSET_PERSONALITY_RAID5) {
3848					max_active_luns = 7;
3849				} else if (rs_type ==
3850					 CS_RAIDSET_PERSONALITY_RAID1){
3851					max_active_luns = 14;
3852				} else {
3853					/* XXX KDM now what?? */
3854				}
3855			} else {
3856				if (rs_type ==
3857				     CS_RAIDSET_PERSONALITY_RAID5) {
3858					max_active_luns = 8;
3859				} else if (rs_type ==
3860					 CS_RAIDSET_PERSONALITY_RAID1){
3861					max_active_luns = 16;
3862				} else {
3863					/* XXX KDM now what?? */
3864				}
3865			}
3866		} else {
3867			/* 50% power */
3868			/*
3869			 * With 50% power in a 64 drive configuration, we
3870			 * can power all LUNs we present.
3871			 */
3872			max_active_luns = num_luns;
3873		}
3874		break;
3875	case 112:
3876		if (shelf_50pct_power == CS_FALSE) {
3877			/* 25% power */
3878			if (aor_present == CS_TRUE) {
3879				if (rs_type ==
3880				     CS_RAIDSET_PERSONALITY_RAID5) {
3881					max_active_luns = 7;
3882				} else if (rs_type ==
3883					 CS_RAIDSET_PERSONALITY_RAID1){
3884					max_active_luns = 14;
3885				} else {
3886					/* XXX KDM now what?? */
3887				}
3888			} else {
3889				if (rs_type ==
3890				     CS_RAIDSET_PERSONALITY_RAID5) {
3891					max_active_luns = 8;
3892				} else if (rs_type ==
3893					 CS_RAIDSET_PERSONALITY_RAID1){
3894					max_active_luns = 16;
3895				} else {
3896					/* XXX KDM now what?? */
3897				}
3898			}
3899		} else {
3900			/* 50% power */
3901			if (aor_present == CS_TRUE) {
3902				if (rs_type ==
3903				     CS_RAIDSET_PERSONALITY_RAID5) {
3904					max_active_luns = 14;
3905				} else if (rs_type ==
3906					 CS_RAIDSET_PERSONALITY_RAID1){
3907					/*
3908					 * We're assuming here that disk
3909					 * caching is enabled, and so we're
3910					 * able to power up half of each
3911					 * LUN, and cache all writes.
3912					 */
3913					max_active_luns = num_luns;
3914				} else {
3915					/* XXX KDM now what?? */
3916				}
3917			} else {
3918				if (rs_type ==
3919				     CS_RAIDSET_PERSONALITY_RAID5) {
3920					max_active_luns = 15;
3921				} else if (rs_type ==
3922					 CS_RAIDSET_PERSONALITY_RAID1){
3923					max_active_luns = 30;
3924				} else {
3925					/* XXX KDM now what?? */
3926				}
3927			}
3928		}
3929		break;
3930	default:
3931		/*
3932		 * In this case, we have an unknown configuration, so we
3933		 * just use the default from above.
3934		 */
3935		break;
3936	}
3937
3938	page->max_active_luns = max_active_luns;
3939#if 0
3940	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
3941	       page->total_luns, page->max_active_luns);
3942#endif
3943}
3944#endif /* NEEDTOPORT */
3945
3946/*
3947 * This routine could be used in the future to load default and/or saved
3948 * mode page parameters for a particuar lun.
3949 */
3950static int
3951ctl_init_page_index(struct ctl_lun *lun)
3952{
3953	int i;
3954	struct ctl_page_index *page_index;
3955	struct ctl_softc *softc;
3956
3957	memcpy(&lun->mode_pages.index, page_index_template,
3958	       sizeof(page_index_template));
3959
3960	softc = lun->ctl_softc;
3961
3962	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3963
3964		page_index = &lun->mode_pages.index[i];
3965		/*
3966		 * If this is a disk-only mode page, there's no point in
3967		 * setting it up.  For some pages, we have to have some
3968		 * basic information about the disk in order to calculate the
3969		 * mode page data.
3970		 */
3971		if ((lun->be_lun->lun_type != T_DIRECT)
3972		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3973			continue;
3974
3975		switch (page_index->page_code & SMPH_PC_MASK) {
3976		case SMS_FORMAT_DEVICE_PAGE: {
3977			struct scsi_format_page *format_page;
3978
3979			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3980				panic("subpage is incorrect!");
3981
3982			/*
3983			 * Sectors per track are set above.  Bytes per
3984			 * sector need to be set here on a per-LUN basis.
3985			 */
3986			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3987			       &format_page_default,
3988			       sizeof(format_page_default));
3989			memcpy(&lun->mode_pages.format_page[
3990			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3991			       sizeof(format_page_changeable));
3992			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3993			       &format_page_default,
3994			       sizeof(format_page_default));
3995			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3996			       &format_page_default,
3997			       sizeof(format_page_default));
3998
3999			format_page = &lun->mode_pages.format_page[
4000				CTL_PAGE_CURRENT];
4001			scsi_ulto2b(lun->be_lun->blocksize,
4002				    format_page->bytes_per_sector);
4003
4004			format_page = &lun->mode_pages.format_page[
4005				CTL_PAGE_DEFAULT];
4006			scsi_ulto2b(lun->be_lun->blocksize,
4007				    format_page->bytes_per_sector);
4008
4009			format_page = &lun->mode_pages.format_page[
4010				CTL_PAGE_SAVED];
4011			scsi_ulto2b(lun->be_lun->blocksize,
4012				    format_page->bytes_per_sector);
4013
4014			page_index->page_data =
4015				(uint8_t *)lun->mode_pages.format_page;
4016			break;
4017		}
4018		case SMS_RIGID_DISK_PAGE: {
4019			struct scsi_rigid_disk_page *rigid_disk_page;
4020			uint32_t sectors_per_cylinder;
4021			uint64_t cylinders;
4022#ifndef	__XSCALE__
4023			int shift;
4024#endif /* !__XSCALE__ */
4025
4026			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4027				panic("invalid subpage value %d",
4028				      page_index->subpage);
4029
4030			/*
4031			 * Rotation rate and sectors per track are set
4032			 * above.  We calculate the cylinders here based on
4033			 * capacity.  Due to the number of heads and
4034			 * sectors per track we're using, smaller arrays
4035			 * may turn out to have 0 cylinders.  Linux and
4036			 * FreeBSD don't pay attention to these mode pages
4037			 * to figure out capacity, but Solaris does.  It
4038			 * seems to deal with 0 cylinders just fine, and
4039			 * works out a fake geometry based on the capacity.
4040			 */
4041			memcpy(&lun->mode_pages.rigid_disk_page[
4042			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4043			       sizeof(rigid_disk_page_default));
4044			memcpy(&lun->mode_pages.rigid_disk_page[
4045			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4046			       sizeof(rigid_disk_page_changeable));
4047			memcpy(&lun->mode_pages.rigid_disk_page[
4048			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4049			       sizeof(rigid_disk_page_default));
4050			memcpy(&lun->mode_pages.rigid_disk_page[
4051			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4052			       sizeof(rigid_disk_page_default));
4053
4054			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4055				CTL_DEFAULT_HEADS;
4056
4057			/*
4058			 * The divide method here will be more accurate,
4059			 * probably, but results in floating point being
4060			 * used in the kernel on i386 (__udivdi3()).  On the
4061			 * XScale, though, __udivdi3() is implemented in
4062			 * software.
4063			 *
4064			 * The shift method for cylinder calculation is
4065			 * accurate if sectors_per_cylinder is a power of
4066			 * 2.  Otherwise it might be slightly off -- you
4067			 * might have a bit of a truncation problem.
4068			 */
4069#ifdef	__XSCALE__
4070			cylinders = (lun->be_lun->maxlba + 1) /
4071				sectors_per_cylinder;
4072#else
4073			for (shift = 31; shift > 0; shift--) {
4074				if (sectors_per_cylinder & (1 << shift))
4075					break;
4076			}
4077			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4078#endif
4079
4080			/*
4081			 * We've basically got 3 bytes, or 24 bits for the
4082			 * cylinder size in the mode page.  If we're over,
4083			 * just round down to 2^24.
4084			 */
4085			if (cylinders > 0xffffff)
4086				cylinders = 0xffffff;
4087
4088			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4089				CTL_PAGE_CURRENT];
4090			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4091
4092			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4093				CTL_PAGE_DEFAULT];
4094			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4095
4096			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4097				CTL_PAGE_SAVED];
4098			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4099
4100			page_index->page_data =
4101				(uint8_t *)lun->mode_pages.rigid_disk_page;
4102			break;
4103		}
4104		case SMS_CACHING_PAGE: {
4105
4106			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4107				panic("invalid subpage value %d",
4108				      page_index->subpage);
4109			/*
4110			 * Defaults should be okay here, no calculations
4111			 * needed.
4112			 */
4113			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4114			       &caching_page_default,
4115			       sizeof(caching_page_default));
4116			memcpy(&lun->mode_pages.caching_page[
4117			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4118			       sizeof(caching_page_changeable));
4119			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4120			       &caching_page_default,
4121			       sizeof(caching_page_default));
4122			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4123			       &caching_page_default,
4124			       sizeof(caching_page_default));
4125			page_index->page_data =
4126				(uint8_t *)lun->mode_pages.caching_page;
4127			break;
4128		}
4129		case SMS_CONTROL_MODE_PAGE: {
4130
4131			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4132				panic("invalid subpage value %d",
4133				      page_index->subpage);
4134
4135			/*
4136			 * Defaults should be okay here, no calculations
4137			 * needed.
4138			 */
4139			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4140			       &control_page_default,
4141			       sizeof(control_page_default));
4142			memcpy(&lun->mode_pages.control_page[
4143			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4144			       sizeof(control_page_changeable));
4145			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4146			       &control_page_default,
4147			       sizeof(control_page_default));
4148			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4149			       &control_page_default,
4150			       sizeof(control_page_default));
4151			page_index->page_data =
4152				(uint8_t *)lun->mode_pages.control_page;
4153			break;
4154
4155		}
4156		case SMS_VENDOR_SPECIFIC_PAGE:{
4157			switch (page_index->subpage) {
4158			case PWR_SUBPAGE_CODE: {
4159				struct copan_power_subpage *current_page,
4160							   *saved_page;
4161
4162				memcpy(&lun->mode_pages.power_subpage[
4163				       CTL_PAGE_CURRENT],
4164				       &power_page_default,
4165				       sizeof(power_page_default));
4166				memcpy(&lun->mode_pages.power_subpage[
4167				       CTL_PAGE_CHANGEABLE],
4168				       &power_page_changeable,
4169				       sizeof(power_page_changeable));
4170				memcpy(&lun->mode_pages.power_subpage[
4171				       CTL_PAGE_DEFAULT],
4172				       &power_page_default,
4173				       sizeof(power_page_default));
4174				memcpy(&lun->mode_pages.power_subpage[
4175				       CTL_PAGE_SAVED],
4176				       &power_page_default,
4177				       sizeof(power_page_default));
4178				page_index->page_data =
4179				    (uint8_t *)lun->mode_pages.power_subpage;
4180
4181				current_page = (struct copan_power_subpage *)
4182					(page_index->page_data +
4183					 (page_index->page_len *
4184					  CTL_PAGE_CURRENT));
4185			        saved_page = (struct copan_power_subpage *)
4186				        (page_index->page_data +
4187					 (page_index->page_len *
4188					  CTL_PAGE_SAVED));
4189				break;
4190			}
4191			case APS_SUBPAGE_CODE: {
4192				struct copan_aps_subpage *current_page,
4193							 *saved_page;
4194
4195				// This gets set multiple times but
4196				// it should always be the same. It's
4197				// only done during init so who cares.
4198				index_to_aps_page = i;
4199
4200				memcpy(&lun->mode_pages.aps_subpage[
4201				       CTL_PAGE_CURRENT],
4202				       &aps_page_default,
4203				       sizeof(aps_page_default));
4204				memcpy(&lun->mode_pages.aps_subpage[
4205				       CTL_PAGE_CHANGEABLE],
4206				       &aps_page_changeable,
4207				       sizeof(aps_page_changeable));
4208				memcpy(&lun->mode_pages.aps_subpage[
4209				       CTL_PAGE_DEFAULT],
4210				       &aps_page_default,
4211				       sizeof(aps_page_default));
4212				memcpy(&lun->mode_pages.aps_subpage[
4213				       CTL_PAGE_SAVED],
4214				       &aps_page_default,
4215				       sizeof(aps_page_default));
4216				page_index->page_data =
4217					(uint8_t *)lun->mode_pages.aps_subpage;
4218
4219				current_page = (struct copan_aps_subpage *)
4220					(page_index->page_data +
4221					 (page_index->page_len *
4222					  CTL_PAGE_CURRENT));
4223				saved_page = (struct copan_aps_subpage *)
4224					(page_index->page_data +
4225					 (page_index->page_len *
4226					  CTL_PAGE_SAVED));
4227				break;
4228			}
4229			case DBGCNF_SUBPAGE_CODE: {
4230				struct copan_debugconf_subpage *current_page,
4231							       *saved_page;
4232
4233				memcpy(&lun->mode_pages.debugconf_subpage[
4234				       CTL_PAGE_CURRENT],
4235				       &debugconf_page_default,
4236				       sizeof(debugconf_page_default));
4237				memcpy(&lun->mode_pages.debugconf_subpage[
4238				       CTL_PAGE_CHANGEABLE],
4239				       &debugconf_page_changeable,
4240				       sizeof(debugconf_page_changeable));
4241				memcpy(&lun->mode_pages.debugconf_subpage[
4242				       CTL_PAGE_DEFAULT],
4243				       &debugconf_page_default,
4244				       sizeof(debugconf_page_default));
4245				memcpy(&lun->mode_pages.debugconf_subpage[
4246				       CTL_PAGE_SAVED],
4247				       &debugconf_page_default,
4248				       sizeof(debugconf_page_default));
4249				page_index->page_data =
4250					(uint8_t *)lun->mode_pages.debugconf_subpage;
4251
4252				current_page = (struct copan_debugconf_subpage *)
4253					(page_index->page_data +
4254					 (page_index->page_len *
4255					  CTL_PAGE_CURRENT));
4256				saved_page = (struct copan_debugconf_subpage *)
4257					(page_index->page_data +
4258					 (page_index->page_len *
4259					  CTL_PAGE_SAVED));
4260				break;
4261			}
4262			default:
4263				panic("invalid subpage value %d",
4264				      page_index->subpage);
4265				break;
4266			}
4267   			break;
4268		}
4269		default:
4270			panic("invalid page value %d",
4271			      page_index->page_code & SMPH_PC_MASK);
4272			break;
4273    	}
4274	}
4275
4276	return (CTL_RETVAL_COMPLETE);
4277}
4278
4279/*
4280 * LUN allocation.
4281 *
4282 * Requirements:
4283 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4284 *   wants us to allocate the LUN and he can block.
4285 * - ctl_softc is always set
4286 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4287 *
4288 * Returns 0 for success, non-zero (errno) for failure.
4289 */
4290static int
4291ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4292	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4293{
4294	struct ctl_lun *nlun, *lun;
4295	struct ctl_port *port;
4296	struct scsi_vpd_id_descriptor *desc;
4297	struct scsi_vpd_id_t10 *t10id;
4298	const char *scsiname, *vendor;
4299	int lun_number, i, lun_malloced;
4300	int devidlen, idlen1, idlen2, len;
4301
4302	if (be_lun == NULL)
4303		return (EINVAL);
4304
4305	/*
4306	 * We currently only support Direct Access or Processor LUN types.
4307	 */
4308	switch (be_lun->lun_type) {
4309	case T_DIRECT:
4310		break;
4311	case T_PROCESSOR:
4312		break;
4313	case T_SEQUENTIAL:
4314	case T_CHANGER:
4315	default:
4316		be_lun->lun_config_status(be_lun->be_lun,
4317					  CTL_LUN_CONFIG_FAILURE);
4318		break;
4319	}
4320	if (ctl_lun == NULL) {
4321		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4322		lun_malloced = 1;
4323	} else {
4324		lun_malloced = 0;
4325		lun = ctl_lun;
4326	}
4327
4328	memset(lun, 0, sizeof(*lun));
4329	if (lun_malloced)
4330		lun->flags = CTL_LUN_MALLOCED;
4331
4332	/* Generate LUN ID. */
4333	devidlen = max(CTL_DEVID_MIN_LEN,
4334	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4335	idlen1 = sizeof(*t10id) + devidlen;
4336	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4337	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4338	if (scsiname != NULL) {
4339		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4340		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4341	}
4342	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4343	    M_CTL, M_WAITOK | M_ZERO);
4344	lun->lun_devid->len = len;
4345	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4346	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4347	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4348	desc->length = idlen1;
4349	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4350	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4351	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4352		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4353	} else {
4354		strncpy(t10id->vendor, vendor,
4355		    min(sizeof(t10id->vendor), strlen(vendor)));
4356	}
4357	strncpy((char *)t10id->vendor_spec_id,
4358	    (char *)be_lun->device_id, devidlen);
4359	if (scsiname != NULL) {
4360		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4361		    desc->length);
4362		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4363		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4364		    SVPD_ID_TYPE_SCSI_NAME;
4365		desc->length = idlen2;
4366		strlcpy(desc->identifier, scsiname, idlen2);
4367	}
4368
4369	mtx_lock(&ctl_softc->ctl_lock);
4370	/*
4371	 * See if the caller requested a particular LUN number.  If so, see
4372	 * if it is available.  Otherwise, allocate the first available LUN.
4373	 */
4374	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4375		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4376		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4377			mtx_unlock(&ctl_softc->ctl_lock);
4378			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4379				printf("ctl: requested LUN ID %d is higher "
4380				       "than CTL_MAX_LUNS - 1 (%d)\n",
4381				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4382			} else {
4383				/*
4384				 * XXX KDM return an error, or just assign
4385				 * another LUN ID in this case??
4386				 */
4387				printf("ctl: requested LUN ID %d is already "
4388				       "in use\n", be_lun->req_lun_id);
4389			}
4390			if (lun->flags & CTL_LUN_MALLOCED)
4391				free(lun, M_CTL);
4392			be_lun->lun_config_status(be_lun->be_lun,
4393						  CTL_LUN_CONFIG_FAILURE);
4394			return (ENOSPC);
4395		}
4396		lun_number = be_lun->req_lun_id;
4397	} else {
4398		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4399		if (lun_number == -1) {
4400			mtx_unlock(&ctl_softc->ctl_lock);
4401			printf("ctl: can't allocate LUN on target %ju, out of "
4402			       "LUNs\n", (uintmax_t)target_id.id);
4403			if (lun->flags & CTL_LUN_MALLOCED)
4404				free(lun, M_CTL);
4405			be_lun->lun_config_status(be_lun->be_lun,
4406						  CTL_LUN_CONFIG_FAILURE);
4407			return (ENOSPC);
4408		}
4409	}
4410	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4411
4412	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4413	lun->target = target_id;
4414	lun->lun = lun_number;
4415	lun->be_lun = be_lun;
4416	/*
4417	 * The processor LUN is always enabled.  Disk LUNs come on line
4418	 * disabled, and must be enabled by the backend.
4419	 */
4420	lun->flags |= CTL_LUN_DISABLED;
4421	lun->backend = be_lun->be;
4422	be_lun->ctl_lun = lun;
4423	be_lun->lun_id = lun_number;
4424	atomic_add_int(&be_lun->be->num_luns, 1);
4425	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4426		lun->flags |= CTL_LUN_STOPPED;
4427
4428	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4429		lun->flags |= CTL_LUN_INOPERABLE;
4430
4431	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4432		lun->flags |= CTL_LUN_PRIMARY_SC;
4433
4434	lun->ctl_softc = ctl_softc;
4435	TAILQ_INIT(&lun->ooa_queue);
4436	TAILQ_INIT(&lun->blocked_queue);
4437	STAILQ_INIT(&lun->error_list);
4438
4439	/*
4440	 * Initialize the mode page index.
4441	 */
4442	ctl_init_page_index(lun);
4443
4444	/*
4445	 * Set the poweron UA for all initiators on this LUN only.
4446	 */
4447	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4448		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4449
4450	/*
4451	 * Now, before we insert this lun on the lun list, set the lun
4452	 * inventory changed UA for all other luns.
4453	 */
4454	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4455		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4456			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4457		}
4458	}
4459
4460	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4461
4462	ctl_softc->ctl_luns[lun_number] = lun;
4463
4464	ctl_softc->num_luns++;
4465
4466	/* Setup statistics gathering */
4467	lun->stats.device_type = be_lun->lun_type;
4468	lun->stats.lun_number = lun_number;
4469	if (lun->stats.device_type == T_DIRECT)
4470		lun->stats.blocksize = be_lun->blocksize;
4471	else
4472		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4473	for (i = 0;i < CTL_MAX_PORTS;i++)
4474		lun->stats.ports[i].targ_port = i;
4475
4476	mtx_unlock(&ctl_softc->ctl_lock);
4477
4478	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4479
4480	/*
4481	 * Run through each registered FETD and bring it online if it isn't
4482	 * already.  Enable the target ID if it hasn't been enabled, and
4483	 * enable this particular LUN.
4484	 */
4485	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4486		int retval;
4487
4488		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4489		if (retval != 0) {
4490			printf("ctl_alloc_lun: FETD %s port %d returned error "
4491			       "%d for lun_enable on target %ju lun %d\n",
4492			       port->port_name, port->targ_port, retval,
4493			       (uintmax_t)target_id.id, lun_number);
4494		} else
4495			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4496	}
4497	return (0);
4498}
4499
4500/*
4501 * Delete a LUN.
4502 * Assumptions:
4503 * - LUN has already been marked invalid and any pending I/O has been taken
4504 *   care of.
4505 */
4506static int
4507ctl_free_lun(struct ctl_lun *lun)
4508{
4509	struct ctl_softc *softc;
4510#if 0
4511	struct ctl_port *port;
4512#endif
4513	struct ctl_lun *nlun;
4514	int i;
4515
4516	softc = lun->ctl_softc;
4517
4518	mtx_assert(&softc->ctl_lock, MA_OWNED);
4519
4520	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4521
4522	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4523
4524	softc->ctl_luns[lun->lun] = NULL;
4525
4526	if (!TAILQ_EMPTY(&lun->ooa_queue))
4527		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4528
4529	softc->num_luns--;
4530
4531	/*
4532	 * XXX KDM this scheme only works for a single target/multiple LUN
4533	 * setup.  It needs to be revamped for a multiple target scheme.
4534	 *
4535	 * XXX KDM this results in port->lun_disable() getting called twice,
4536	 * once when ctl_disable_lun() is called, and a second time here.
4537	 * We really need to re-think the LUN disable semantics.  There
4538	 * should probably be several steps/levels to LUN removal:
4539	 *  - disable
4540	 *  - invalidate
4541	 *  - free
4542 	 *
4543	 * Right now we only have a disable method when communicating to
4544	 * the front end ports, at least for individual LUNs.
4545	 */
4546#if 0
4547	STAILQ_FOREACH(port, &softc->port_list, links) {
4548		int retval;
4549
4550		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4551					 lun->lun);
4552		if (retval != 0) {
4553			printf("ctl_free_lun: FETD %s port %d returned error "
4554			       "%d for lun_disable on target %ju lun %jd\n",
4555			       port->port_name, port->targ_port, retval,
4556			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4557		}
4558
4559		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4560			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4561
4562			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4563			if (retval != 0) {
4564				printf("ctl_free_lun: FETD %s port %d "
4565				       "returned error %d for targ_disable on "
4566				       "target %ju\n", port->port_name,
4567				       port->targ_port, retval,
4568				       (uintmax_t)lun->target.id);
4569			} else
4570				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4571
4572			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4573				continue;
4574
4575#if 0
4576			port->port_offline(port->onoff_arg);
4577			port->status &= ~CTL_PORT_STATUS_ONLINE;
4578#endif
4579		}
4580	}
4581#endif
4582
4583	/*
4584	 * Tell the backend to free resources, if this LUN has a backend.
4585	 */
4586	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4587	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4588
4589	mtx_destroy(&lun->lun_lock);
4590	free(lun->lun_devid, M_CTL);
4591	if (lun->flags & CTL_LUN_MALLOCED)
4592		free(lun, M_CTL);
4593
4594	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4595		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4596			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4597		}
4598	}
4599
4600	return (0);
4601}
4602
4603static void
4604ctl_create_lun(struct ctl_be_lun *be_lun)
4605{
4606	struct ctl_softc *ctl_softc;
4607
4608	ctl_softc = control_softc;
4609
4610	/*
4611	 * ctl_alloc_lun() should handle all potential failure cases.
4612	 */
4613	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4614}
4615
4616int
4617ctl_add_lun(struct ctl_be_lun *be_lun)
4618{
4619	struct ctl_softc *ctl_softc = control_softc;
4620
4621	mtx_lock(&ctl_softc->ctl_lock);
4622	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4623	mtx_unlock(&ctl_softc->ctl_lock);
4624	wakeup(&ctl_softc->pending_lun_queue);
4625
4626	return (0);
4627}
4628
4629int
4630ctl_enable_lun(struct ctl_be_lun *be_lun)
4631{
4632	struct ctl_softc *ctl_softc;
4633	struct ctl_port *port, *nport;
4634	struct ctl_lun *lun;
4635	int retval;
4636
4637	ctl_softc = control_softc;
4638
4639	lun = (struct ctl_lun *)be_lun->ctl_lun;
4640
4641	mtx_lock(&ctl_softc->ctl_lock);
4642	mtx_lock(&lun->lun_lock);
4643	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4644		/*
4645		 * eh?  Why did we get called if the LUN is already
4646		 * enabled?
4647		 */
4648		mtx_unlock(&lun->lun_lock);
4649		mtx_unlock(&ctl_softc->ctl_lock);
4650		return (0);
4651	}
4652	lun->flags &= ~CTL_LUN_DISABLED;
4653	mtx_unlock(&lun->lun_lock);
4654
4655	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4656		nport = STAILQ_NEXT(port, links);
4657
4658		/*
4659		 * Drop the lock while we call the FETD's enable routine.
4660		 * This can lead to a callback into CTL (at least in the
4661		 * case of the internal initiator frontend.
4662		 */
4663		mtx_unlock(&ctl_softc->ctl_lock);
4664		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4665		mtx_lock(&ctl_softc->ctl_lock);
4666		if (retval != 0) {
4667			printf("%s: FETD %s port %d returned error "
4668			       "%d for lun_enable on target %ju lun %jd\n",
4669			       __func__, port->port_name, port->targ_port, retval,
4670			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4671		}
4672#if 0
4673		 else {
4674            /* NOTE:  TODO:  why does lun enable affect port status? */
4675			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4676		}
4677#endif
4678	}
4679
4680	mtx_unlock(&ctl_softc->ctl_lock);
4681
4682	return (0);
4683}
4684
4685int
4686ctl_disable_lun(struct ctl_be_lun *be_lun)
4687{
4688	struct ctl_softc *ctl_softc;
4689	struct ctl_port *port;
4690	struct ctl_lun *lun;
4691	int retval;
4692
4693	ctl_softc = control_softc;
4694
4695	lun = (struct ctl_lun *)be_lun->ctl_lun;
4696
4697	mtx_lock(&ctl_softc->ctl_lock);
4698	mtx_lock(&lun->lun_lock);
4699	if (lun->flags & CTL_LUN_DISABLED) {
4700		mtx_unlock(&lun->lun_lock);
4701		mtx_unlock(&ctl_softc->ctl_lock);
4702		return (0);
4703	}
4704	lun->flags |= CTL_LUN_DISABLED;
4705	mtx_unlock(&lun->lun_lock);
4706
4707	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4708		mtx_unlock(&ctl_softc->ctl_lock);
4709		/*
4710		 * Drop the lock before we call the frontend's disable
4711		 * routine, to avoid lock order reversals.
4712		 *
4713		 * XXX KDM what happens if the frontend list changes while
4714		 * we're traversing it?  It's unlikely, but should be handled.
4715		 */
4716		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4717					 lun->lun);
4718		mtx_lock(&ctl_softc->ctl_lock);
4719		if (retval != 0) {
4720			printf("ctl_alloc_lun: FETD %s port %d returned error "
4721			       "%d for lun_disable on target %ju lun %jd\n",
4722			       port->port_name, port->targ_port, retval,
4723			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4724		}
4725	}
4726
4727	mtx_unlock(&ctl_softc->ctl_lock);
4728
4729	return (0);
4730}
4731
4732int
4733ctl_start_lun(struct ctl_be_lun *be_lun)
4734{
4735	struct ctl_softc *ctl_softc;
4736	struct ctl_lun *lun;
4737
4738	ctl_softc = control_softc;
4739
4740	lun = (struct ctl_lun *)be_lun->ctl_lun;
4741
4742	mtx_lock(&lun->lun_lock);
4743	lun->flags &= ~CTL_LUN_STOPPED;
4744	mtx_unlock(&lun->lun_lock);
4745
4746	return (0);
4747}
4748
4749int
4750ctl_stop_lun(struct ctl_be_lun *be_lun)
4751{
4752	struct ctl_softc *ctl_softc;
4753	struct ctl_lun *lun;
4754
4755	ctl_softc = control_softc;
4756
4757	lun = (struct ctl_lun *)be_lun->ctl_lun;
4758
4759	mtx_lock(&lun->lun_lock);
4760	lun->flags |= CTL_LUN_STOPPED;
4761	mtx_unlock(&lun->lun_lock);
4762
4763	return (0);
4764}
4765
4766int
4767ctl_lun_offline(struct ctl_be_lun *be_lun)
4768{
4769	struct ctl_softc *ctl_softc;
4770	struct ctl_lun *lun;
4771
4772	ctl_softc = control_softc;
4773
4774	lun = (struct ctl_lun *)be_lun->ctl_lun;
4775
4776	mtx_lock(&lun->lun_lock);
4777	lun->flags |= CTL_LUN_OFFLINE;
4778	mtx_unlock(&lun->lun_lock);
4779
4780	return (0);
4781}
4782
4783int
4784ctl_lun_online(struct ctl_be_lun *be_lun)
4785{
4786	struct ctl_softc *ctl_softc;
4787	struct ctl_lun *lun;
4788
4789	ctl_softc = control_softc;
4790
4791	lun = (struct ctl_lun *)be_lun->ctl_lun;
4792
4793	mtx_lock(&lun->lun_lock);
4794	lun->flags &= ~CTL_LUN_OFFLINE;
4795	mtx_unlock(&lun->lun_lock);
4796
4797	return (0);
4798}
4799
4800int
4801ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4802{
4803	struct ctl_softc *ctl_softc;
4804	struct ctl_lun *lun;
4805
4806	ctl_softc = control_softc;
4807
4808	lun = (struct ctl_lun *)be_lun->ctl_lun;
4809
4810	mtx_lock(&lun->lun_lock);
4811
4812	/*
4813	 * The LUN needs to be disabled before it can be marked invalid.
4814	 */
4815	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4816		mtx_unlock(&lun->lun_lock);
4817		return (-1);
4818	}
4819	/*
4820	 * Mark the LUN invalid.
4821	 */
4822	lun->flags |= CTL_LUN_INVALID;
4823
4824	/*
4825	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4826	 * If we have something in the OOA queue, we'll free it when the
4827	 * last I/O completes.
4828	 */
4829	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4830		mtx_unlock(&lun->lun_lock);
4831		mtx_lock(&ctl_softc->ctl_lock);
4832		ctl_free_lun(lun);
4833		mtx_unlock(&ctl_softc->ctl_lock);
4834	} else
4835		mtx_unlock(&lun->lun_lock);
4836
4837	return (0);
4838}
4839
4840int
4841ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4842{
4843	struct ctl_softc *ctl_softc;
4844	struct ctl_lun *lun;
4845
4846	ctl_softc = control_softc;
4847	lun = (struct ctl_lun *)be_lun->ctl_lun;
4848
4849	mtx_lock(&lun->lun_lock);
4850	lun->flags |= CTL_LUN_INOPERABLE;
4851	mtx_unlock(&lun->lun_lock);
4852
4853	return (0);
4854}
4855
4856int
4857ctl_lun_operable(struct ctl_be_lun *be_lun)
4858{
4859	struct ctl_softc *ctl_softc;
4860	struct ctl_lun *lun;
4861
4862	ctl_softc = control_softc;
4863	lun = (struct ctl_lun *)be_lun->ctl_lun;
4864
4865	mtx_lock(&lun->lun_lock);
4866	lun->flags &= ~CTL_LUN_INOPERABLE;
4867	mtx_unlock(&lun->lun_lock);
4868
4869	return (0);
4870}
4871
4872int
4873ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
4874		   int lock)
4875{
4876	struct ctl_softc *softc;
4877	struct ctl_lun *lun;
4878	struct copan_aps_subpage *current_sp;
4879	struct ctl_page_index *page_index;
4880	int i;
4881
4882	softc = control_softc;
4883
4884	mtx_lock(&softc->ctl_lock);
4885
4886	lun = (struct ctl_lun *)be_lun->ctl_lun;
4887	mtx_lock(&lun->lun_lock);
4888
4889	page_index = NULL;
4890	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4891		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
4892		     APS_PAGE_CODE)
4893			continue;
4894
4895		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
4896			continue;
4897		page_index = &lun->mode_pages.index[i];
4898	}
4899
4900	if (page_index == NULL) {
4901		mtx_unlock(&lun->lun_lock);
4902		mtx_unlock(&softc->ctl_lock);
4903		printf("%s: APS subpage not found for lun %ju!\n", __func__,
4904		       (uintmax_t)lun->lun);
4905		return (1);
4906	}
4907#if 0
4908	if ((softc->aps_locked_lun != 0)
4909	 && (softc->aps_locked_lun != lun->lun)) {
4910		printf("%s: attempt to lock LUN %llu when %llu is already "
4911		       "locked\n");
4912		mtx_unlock(&lun->lun_lock);
4913		mtx_unlock(&softc->ctl_lock);
4914		return (1);
4915	}
4916#endif
4917
4918	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
4919		(page_index->page_len * CTL_PAGE_CURRENT));
4920
4921	if (lock != 0) {
4922		current_sp->lock_active = APS_LOCK_ACTIVE;
4923		softc->aps_locked_lun = lun->lun;
4924	} else {
4925		current_sp->lock_active = 0;
4926		softc->aps_locked_lun = 0;
4927	}
4928
4929
4930	/*
4931	 * If we're in HA mode, try to send the lock message to the other
4932	 * side.
4933	 */
4934	if (ctl_is_single == 0) {
4935		int isc_retval;
4936		union ctl_ha_msg lock_msg;
4937
4938		lock_msg.hdr.nexus = *nexus;
4939		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
4940		if (lock != 0)
4941			lock_msg.aps.lock_flag = 1;
4942		else
4943			lock_msg.aps.lock_flag = 0;
4944		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
4945					 sizeof(lock_msg), 0);
4946		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
4947			printf("%s: APS (lock=%d) error returned from "
4948			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
4949			mtx_unlock(&lun->lun_lock);
4950			mtx_unlock(&softc->ctl_lock);
4951			return (1);
4952		}
4953	}
4954
4955	mtx_unlock(&lun->lun_lock);
4956	mtx_unlock(&softc->ctl_lock);
4957
4958	return (0);
4959}
4960
4961void
4962ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4963{
4964	struct ctl_lun *lun;
4965	struct ctl_softc *softc;
4966	int i;
4967
4968	softc = control_softc;
4969
4970	lun = (struct ctl_lun *)be_lun->ctl_lun;
4971
4972	mtx_lock(&lun->lun_lock);
4973
4974	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4975		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
4976
4977	mtx_unlock(&lun->lun_lock);
4978}
4979
4980/*
4981 * Backend "memory move is complete" callback for requests that never
4982 * make it down to say RAIDCore's configuration code.
4983 */
4984int
4985ctl_config_move_done(union ctl_io *io)
4986{
4987	int retval;
4988
4989	retval = CTL_RETVAL_COMPLETE;
4990
4991
4992	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4993	/*
4994	 * XXX KDM this shouldn't happen, but what if it does?
4995	 */
4996	if (io->io_hdr.io_type != CTL_IO_SCSI)
4997		panic("I/O type isn't CTL_IO_SCSI!");
4998
4999	if ((io->io_hdr.port_status == 0)
5000	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5001	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5002		io->io_hdr.status = CTL_SUCCESS;
5003	else if ((io->io_hdr.port_status != 0)
5004	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5005	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5006		/*
5007		 * For hardware error sense keys, the sense key
5008		 * specific value is defined to be a retry count,
5009		 * but we use it to pass back an internal FETD
5010		 * error code.  XXX KDM  Hopefully the FETD is only
5011		 * using 16 bits for an error code, since that's
5012		 * all the space we have in the sks field.
5013		 */
5014		ctl_set_internal_failure(&io->scsiio,
5015					 /*sks_valid*/ 1,
5016					 /*retry_count*/
5017					 io->io_hdr.port_status);
5018		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5019			free(io->scsiio.kern_data_ptr, M_CTL);
5020		ctl_done(io);
5021		goto bailout;
5022	}
5023
5024	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5025	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5026	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5027		/*
5028		 * XXX KDM just assuming a single pointer here, and not a
5029		 * S/G list.  If we start using S/G lists for config data,
5030		 * we'll need to know how to clean them up here as well.
5031		 */
5032		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5033			free(io->scsiio.kern_data_ptr, M_CTL);
5034		/* Hopefully the user has already set the status... */
5035		ctl_done(io);
5036	} else {
5037		/*
5038		 * XXX KDM now we need to continue data movement.  Some
5039		 * options:
5040		 * - call ctl_scsiio() again?  We don't do this for data
5041		 *   writes, because for those at least we know ahead of
5042		 *   time where the write will go and how long it is.  For
5043		 *   config writes, though, that information is largely
5044		 *   contained within the write itself, thus we need to
5045		 *   parse out the data again.
5046		 *
5047		 * - Call some other function once the data is in?
5048		 */
5049
5050		/*
5051		 * XXX KDM call ctl_scsiio() again for now, and check flag
5052		 * bits to see whether we're allocated or not.
5053		 */
5054		retval = ctl_scsiio(&io->scsiio);
5055	}
5056bailout:
5057	return (retval);
5058}
5059
5060/*
5061 * This gets called by a backend driver when it is done with a
5062 * data_submit method.
5063 */
5064void
5065ctl_data_submit_done(union ctl_io *io)
5066{
5067	/*
5068	 * If the IO_CONT flag is set, we need to call the supplied
5069	 * function to continue processing the I/O, instead of completing
5070	 * the I/O just yet.
5071	 *
5072	 * If there is an error, though, we don't want to keep processing.
5073	 * Instead, just send status back to the initiator.
5074	 */
5075	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5076	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5077	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5078	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5079		io->scsiio.io_cont(io);
5080		return;
5081	}
5082	ctl_done(io);
5083}
5084
5085/*
5086 * This gets called by a backend driver when it is done with a
5087 * configuration write.
5088 */
5089void
5090ctl_config_write_done(union ctl_io *io)
5091{
5092	/*
5093	 * If the IO_CONT flag is set, we need to call the supplied
5094	 * function to continue processing the I/O, instead of completing
5095	 * the I/O just yet.
5096	 *
5097	 * If there is an error, though, we don't want to keep processing.
5098	 * Instead, just send status back to the initiator.
5099	 */
5100	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5101	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5102	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5103		io->scsiio.io_cont(io);
5104		return;
5105	}
5106	/*
5107	 * Since a configuration write can be done for commands that actually
5108	 * have data allocated, like write buffer, and commands that have
5109	 * no data, like start/stop unit, we need to check here.
5110	 */
5111	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5112		free(io->scsiio.kern_data_ptr, M_CTL);
5113	ctl_done(io);
5114}
5115
5116/*
5117 * SCSI release command.
5118 */
5119int
5120ctl_scsi_release(struct ctl_scsiio *ctsio)
5121{
5122	int length, longid, thirdparty_id, resv_id;
5123	struct ctl_softc *ctl_softc;
5124	struct ctl_lun *lun;
5125
5126	length = 0;
5127	resv_id = 0;
5128
5129	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5130
5131	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5132	ctl_softc = control_softc;
5133
5134	switch (ctsio->cdb[0]) {
5135	case RELEASE_10: {
5136		struct scsi_release_10 *cdb;
5137
5138		cdb = (struct scsi_release_10 *)ctsio->cdb;
5139
5140		if (cdb->byte2 & SR10_LONGID)
5141			longid = 1;
5142		else
5143			thirdparty_id = cdb->thirdparty_id;
5144
5145		resv_id = cdb->resv_id;
5146		length = scsi_2btoul(cdb->length);
5147		break;
5148	}
5149	}
5150
5151
5152	/*
5153	 * XXX KDM right now, we only support LUN reservation.  We don't
5154	 * support 3rd party reservations, or extent reservations, which
5155	 * might actually need the parameter list.  If we've gotten this
5156	 * far, we've got a LUN reservation.  Anything else got kicked out
5157	 * above.  So, according to SPC, ignore the length.
5158	 */
5159	length = 0;
5160
5161	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5162	 && (length > 0)) {
5163		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5164		ctsio->kern_data_len = length;
5165		ctsio->kern_total_len = length;
5166		ctsio->kern_data_resid = 0;
5167		ctsio->kern_rel_offset = 0;
5168		ctsio->kern_sg_entries = 0;
5169		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5170		ctsio->be_move_done = ctl_config_move_done;
5171		ctl_datamove((union ctl_io *)ctsio);
5172
5173		return (CTL_RETVAL_COMPLETE);
5174	}
5175
5176	if (length > 0)
5177		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5178
5179	mtx_lock(&lun->lun_lock);
5180
5181	/*
5182	 * According to SPC, it is not an error for an intiator to attempt
5183	 * to release a reservation on a LUN that isn't reserved, or that
5184	 * is reserved by another initiator.  The reservation can only be
5185	 * released, though, by the initiator who made it or by one of
5186	 * several reset type events.
5187	 */
5188	if (lun->flags & CTL_LUN_RESERVED) {
5189		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5190		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5191		 && (ctsio->io_hdr.nexus.targ_target.id ==
5192		     lun->rsv_nexus.targ_target.id)) {
5193			lun->flags &= ~CTL_LUN_RESERVED;
5194		}
5195	}
5196
5197	mtx_unlock(&lun->lun_lock);
5198
5199	ctsio->scsi_status = SCSI_STATUS_OK;
5200	ctsio->io_hdr.status = CTL_SUCCESS;
5201
5202	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5203		free(ctsio->kern_data_ptr, M_CTL);
5204		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5205	}
5206
5207	ctl_done((union ctl_io *)ctsio);
5208	return (CTL_RETVAL_COMPLETE);
5209}
5210
5211int
5212ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5213{
5214	int extent, thirdparty, longid;
5215	int resv_id, length;
5216	uint64_t thirdparty_id;
5217	struct ctl_softc *ctl_softc;
5218	struct ctl_lun *lun;
5219
5220	extent = 0;
5221	thirdparty = 0;
5222	longid = 0;
5223	resv_id = 0;
5224	length = 0;
5225	thirdparty_id = 0;
5226
5227	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5228
5229	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5230	ctl_softc = control_softc;
5231
5232	switch (ctsio->cdb[0]) {
5233	case RESERVE_10: {
5234		struct scsi_reserve_10 *cdb;
5235
5236		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5237
5238		if (cdb->byte2 & SR10_LONGID)
5239			longid = 1;
5240		else
5241			thirdparty_id = cdb->thirdparty_id;
5242
5243		resv_id = cdb->resv_id;
5244		length = scsi_2btoul(cdb->length);
5245		break;
5246	}
5247	}
5248
5249	/*
5250	 * XXX KDM right now, we only support LUN reservation.  We don't
5251	 * support 3rd party reservations, or extent reservations, which
5252	 * might actually need the parameter list.  If we've gotten this
5253	 * far, we've got a LUN reservation.  Anything else got kicked out
5254	 * above.  So, according to SPC, ignore the length.
5255	 */
5256	length = 0;
5257
5258	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5259	 && (length > 0)) {
5260		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5261		ctsio->kern_data_len = length;
5262		ctsio->kern_total_len = length;
5263		ctsio->kern_data_resid = 0;
5264		ctsio->kern_rel_offset = 0;
5265		ctsio->kern_sg_entries = 0;
5266		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5267		ctsio->be_move_done = ctl_config_move_done;
5268		ctl_datamove((union ctl_io *)ctsio);
5269
5270		return (CTL_RETVAL_COMPLETE);
5271	}
5272
5273	if (length > 0)
5274		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5275
5276	mtx_lock(&lun->lun_lock);
5277	if (lun->flags & CTL_LUN_RESERVED) {
5278		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5279		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5280		 || (ctsio->io_hdr.nexus.targ_target.id !=
5281		     lun->rsv_nexus.targ_target.id)) {
5282			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5283			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5284			goto bailout;
5285		}
5286	}
5287
5288	lun->flags |= CTL_LUN_RESERVED;
5289	lun->rsv_nexus = ctsio->io_hdr.nexus;
5290
5291	ctsio->scsi_status = SCSI_STATUS_OK;
5292	ctsio->io_hdr.status = CTL_SUCCESS;
5293
5294bailout:
5295	mtx_unlock(&lun->lun_lock);
5296
5297	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5298		free(ctsio->kern_data_ptr, M_CTL);
5299		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5300	}
5301
5302	ctl_done((union ctl_io *)ctsio);
5303	return (CTL_RETVAL_COMPLETE);
5304}
5305
5306int
5307ctl_start_stop(struct ctl_scsiio *ctsio)
5308{
5309	struct scsi_start_stop_unit *cdb;
5310	struct ctl_lun *lun;
5311	struct ctl_softc *ctl_softc;
5312	int retval;
5313
5314	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5315
5316	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5317	ctl_softc = control_softc;
5318	retval = 0;
5319
5320	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5321
5322	/*
5323	 * XXX KDM
5324	 * We don't support the immediate bit on a stop unit.  In order to
5325	 * do that, we would need to code up a way to know that a stop is
5326	 * pending, and hold off any new commands until it completes, one
5327	 * way or another.  Then we could accept or reject those commands
5328	 * depending on its status.  We would almost need to do the reverse
5329	 * of what we do below for an immediate start -- return the copy of
5330	 * the ctl_io to the FETD with status to send to the host (and to
5331	 * free the copy!) and then free the original I/O once the stop
5332	 * actually completes.  That way, the OOA queue mechanism can work
5333	 * to block commands that shouldn't proceed.  Another alternative
5334	 * would be to put the copy in the queue in place of the original,
5335	 * and return the original back to the caller.  That could be
5336	 * slightly safer..
5337	 */
5338	if ((cdb->byte2 & SSS_IMMED)
5339	 && ((cdb->how & SSS_START) == 0)) {
5340		ctl_set_invalid_field(ctsio,
5341				      /*sks_valid*/ 1,
5342				      /*command*/ 1,
5343				      /*field*/ 1,
5344				      /*bit_valid*/ 1,
5345				      /*bit*/ 0);
5346		ctl_done((union ctl_io *)ctsio);
5347		return (CTL_RETVAL_COMPLETE);
5348	}
5349
5350	if ((lun->flags & CTL_LUN_PR_RESERVED)
5351	 && ((cdb->how & SSS_START)==0)) {
5352		uint32_t residx;
5353
5354		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5355		if (!lun->per_res[residx].registered
5356		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5357
5358			ctl_set_reservation_conflict(ctsio);
5359			ctl_done((union ctl_io *)ctsio);
5360			return (CTL_RETVAL_COMPLETE);
5361		}
5362	}
5363
5364	/*
5365	 * If there is no backend on this device, we can't start or stop
5366	 * it.  In theory we shouldn't get any start/stop commands in the
5367	 * first place at this level if the LUN doesn't have a backend.
5368	 * That should get stopped by the command decode code.
5369	 */
5370	if (lun->backend == NULL) {
5371		ctl_set_invalid_opcode(ctsio);
5372		ctl_done((union ctl_io *)ctsio);
5373		return (CTL_RETVAL_COMPLETE);
5374	}
5375
5376	/*
5377	 * XXX KDM Copan-specific offline behavior.
5378	 * Figure out a reasonable way to port this?
5379	 */
5380#ifdef NEEDTOPORT
5381	mtx_lock(&lun->lun_lock);
5382
5383	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5384	 && (lun->flags & CTL_LUN_OFFLINE)) {
5385		/*
5386		 * If the LUN is offline, and the on/offline bit isn't set,
5387		 * reject the start or stop.  Otherwise, let it through.
5388		 */
5389		mtx_unlock(&lun->lun_lock);
5390		ctl_set_lun_not_ready(ctsio);
5391		ctl_done((union ctl_io *)ctsio);
5392	} else {
5393		mtx_unlock(&lun->lun_lock);
5394#endif /* NEEDTOPORT */
5395		/*
5396		 * This could be a start or a stop when we're online,
5397		 * or a stop/offline or start/online.  A start or stop when
5398		 * we're offline is covered in the case above.
5399		 */
5400		/*
5401		 * In the non-immediate case, we send the request to
5402		 * the backend and return status to the user when
5403		 * it is done.
5404		 *
5405		 * In the immediate case, we allocate a new ctl_io
5406		 * to hold a copy of the request, and send that to
5407		 * the backend.  We then set good status on the
5408		 * user's request and return it immediately.
5409		 */
5410		if (cdb->byte2 & SSS_IMMED) {
5411			union ctl_io *new_io;
5412
5413			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5414			if (new_io == NULL) {
5415				ctl_set_busy(ctsio);
5416				ctl_done((union ctl_io *)ctsio);
5417			} else {
5418				ctl_copy_io((union ctl_io *)ctsio,
5419					    new_io);
5420				retval = lun->backend->config_write(new_io);
5421				ctl_set_success(ctsio);
5422				ctl_done((union ctl_io *)ctsio);
5423			}
5424		} else {
5425			retval = lun->backend->config_write(
5426				(union ctl_io *)ctsio);
5427		}
5428#ifdef NEEDTOPORT
5429	}
5430#endif
5431	return (retval);
5432}
5433
5434/*
5435 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5436 * we don't really do anything with the LBA and length fields if the user
5437 * passes them in.  Instead we'll just flush out the cache for the entire
5438 * LUN.
5439 */
5440int
5441ctl_sync_cache(struct ctl_scsiio *ctsio)
5442{
5443	struct ctl_lun *lun;
5444	struct ctl_softc *ctl_softc;
5445	uint64_t starting_lba;
5446	uint32_t block_count;
5447	int retval;
5448
5449	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5450
5451	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5452	ctl_softc = control_softc;
5453	retval = 0;
5454
5455	switch (ctsio->cdb[0]) {
5456	case SYNCHRONIZE_CACHE: {
5457		struct scsi_sync_cache *cdb;
5458		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5459
5460		starting_lba = scsi_4btoul(cdb->begin_lba);
5461		block_count = scsi_2btoul(cdb->lb_count);
5462		break;
5463	}
5464	case SYNCHRONIZE_CACHE_16: {
5465		struct scsi_sync_cache_16 *cdb;
5466		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5467
5468		starting_lba = scsi_8btou64(cdb->begin_lba);
5469		block_count = scsi_4btoul(cdb->lb_count);
5470		break;
5471	}
5472	default:
5473		ctl_set_invalid_opcode(ctsio);
5474		ctl_done((union ctl_io *)ctsio);
5475		goto bailout;
5476		break; /* NOTREACHED */
5477	}
5478
5479	/*
5480	 * We check the LBA and length, but don't do anything with them.
5481	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5482	 * get flushed.  This check will just help satisfy anyone who wants
5483	 * to see an error for an out of range LBA.
5484	 */
5485	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5486		ctl_set_lba_out_of_range(ctsio);
5487		ctl_done((union ctl_io *)ctsio);
5488		goto bailout;
5489	}
5490
5491	/*
5492	 * If this LUN has no backend, we can't flush the cache anyway.
5493	 */
5494	if (lun->backend == NULL) {
5495		ctl_set_invalid_opcode(ctsio);
5496		ctl_done((union ctl_io *)ctsio);
5497		goto bailout;
5498	}
5499
5500	/*
5501	 * Check to see whether we're configured to send the SYNCHRONIZE
5502	 * CACHE command directly to the back end.
5503	 */
5504	mtx_lock(&lun->lun_lock);
5505	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5506	 && (++(lun->sync_count) >= lun->sync_interval)) {
5507		lun->sync_count = 0;
5508		mtx_unlock(&lun->lun_lock);
5509		retval = lun->backend->config_write((union ctl_io *)ctsio);
5510	} else {
5511		mtx_unlock(&lun->lun_lock);
5512		ctl_set_success(ctsio);
5513		ctl_done((union ctl_io *)ctsio);
5514	}
5515
5516bailout:
5517
5518	return (retval);
5519}
5520
5521int
5522ctl_format(struct ctl_scsiio *ctsio)
5523{
5524	struct scsi_format *cdb;
5525	struct ctl_lun *lun;
5526	struct ctl_softc *ctl_softc;
5527	int length, defect_list_len;
5528
5529	CTL_DEBUG_PRINT(("ctl_format\n"));
5530
5531	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5532	ctl_softc = control_softc;
5533
5534	cdb = (struct scsi_format *)ctsio->cdb;
5535
5536	length = 0;
5537	if (cdb->byte2 & SF_FMTDATA) {
5538		if (cdb->byte2 & SF_LONGLIST)
5539			length = sizeof(struct scsi_format_header_long);
5540		else
5541			length = sizeof(struct scsi_format_header_short);
5542	}
5543
5544	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5545	 && (length > 0)) {
5546		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5547		ctsio->kern_data_len = length;
5548		ctsio->kern_total_len = length;
5549		ctsio->kern_data_resid = 0;
5550		ctsio->kern_rel_offset = 0;
5551		ctsio->kern_sg_entries = 0;
5552		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5553		ctsio->be_move_done = ctl_config_move_done;
5554		ctl_datamove((union ctl_io *)ctsio);
5555
5556		return (CTL_RETVAL_COMPLETE);
5557	}
5558
5559	defect_list_len = 0;
5560
5561	if (cdb->byte2 & SF_FMTDATA) {
5562		if (cdb->byte2 & SF_LONGLIST) {
5563			struct scsi_format_header_long *header;
5564
5565			header = (struct scsi_format_header_long *)
5566				ctsio->kern_data_ptr;
5567
5568			defect_list_len = scsi_4btoul(header->defect_list_len);
5569			if (defect_list_len != 0) {
5570				ctl_set_invalid_field(ctsio,
5571						      /*sks_valid*/ 1,
5572						      /*command*/ 0,
5573						      /*field*/ 2,
5574						      /*bit_valid*/ 0,
5575						      /*bit*/ 0);
5576				goto bailout;
5577			}
5578		} else {
5579			struct scsi_format_header_short *header;
5580
5581			header = (struct scsi_format_header_short *)
5582				ctsio->kern_data_ptr;
5583
5584			defect_list_len = scsi_2btoul(header->defect_list_len);
5585			if (defect_list_len != 0) {
5586				ctl_set_invalid_field(ctsio,
5587						      /*sks_valid*/ 1,
5588						      /*command*/ 0,
5589						      /*field*/ 2,
5590						      /*bit_valid*/ 0,
5591						      /*bit*/ 0);
5592				goto bailout;
5593			}
5594		}
5595	}
5596
5597	/*
5598	 * The format command will clear out the "Medium format corrupted"
5599	 * status if set by the configuration code.  That status is really
5600	 * just a way to notify the host that we have lost the media, and
5601	 * get them to issue a command that will basically make them think
5602	 * they're blowing away the media.
5603	 */
5604	mtx_lock(&lun->lun_lock);
5605	lun->flags &= ~CTL_LUN_INOPERABLE;
5606	mtx_unlock(&lun->lun_lock);
5607
5608	ctsio->scsi_status = SCSI_STATUS_OK;
5609	ctsio->io_hdr.status = CTL_SUCCESS;
5610bailout:
5611
5612	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5613		free(ctsio->kern_data_ptr, M_CTL);
5614		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5615	}
5616
5617	ctl_done((union ctl_io *)ctsio);
5618	return (CTL_RETVAL_COMPLETE);
5619}
5620
5621int
5622ctl_read_buffer(struct ctl_scsiio *ctsio)
5623{
5624	struct scsi_read_buffer *cdb;
5625	struct ctl_lun *lun;
5626	int buffer_offset, len;
5627	static uint8_t descr[4];
5628	static uint8_t echo_descr[4] = { 0 };
5629
5630	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5631
5632	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5633	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5634
5635	if (lun->flags & CTL_LUN_PR_RESERVED) {
5636		uint32_t residx;
5637
5638		/*
5639		 * XXX KDM need a lock here.
5640		 */
5641		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5642		if ((lun->res_type == SPR_TYPE_EX_AC
5643		  && residx != lun->pr_res_idx)
5644		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5645		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5646		  && !lun->per_res[residx].registered)) {
5647			ctl_set_reservation_conflict(ctsio);
5648			ctl_done((union ctl_io *)ctsio);
5649			return (CTL_RETVAL_COMPLETE);
5650	        }
5651	}
5652
5653	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5654	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5655	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5656		ctl_set_invalid_field(ctsio,
5657				      /*sks_valid*/ 1,
5658				      /*command*/ 1,
5659				      /*field*/ 1,
5660				      /*bit_valid*/ 1,
5661				      /*bit*/ 4);
5662		ctl_done((union ctl_io *)ctsio);
5663		return (CTL_RETVAL_COMPLETE);
5664	}
5665
5666	len = scsi_3btoul(cdb->length);
5667	buffer_offset = scsi_3btoul(cdb->offset);
5668
5669	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5670		ctl_set_invalid_field(ctsio,
5671				      /*sks_valid*/ 1,
5672				      /*command*/ 1,
5673				      /*field*/ 6,
5674				      /*bit_valid*/ 0,
5675				      /*bit*/ 0);
5676		ctl_done((union ctl_io *)ctsio);
5677		return (CTL_RETVAL_COMPLETE);
5678	}
5679
5680	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5681		descr[0] = 0;
5682		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5683		ctsio->kern_data_ptr = descr;
5684		len = min(len, sizeof(descr));
5685	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5686		ctsio->kern_data_ptr = echo_descr;
5687		len = min(len, sizeof(echo_descr));
5688	} else
5689		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5690	ctsio->kern_data_len = len;
5691	ctsio->kern_total_len = len;
5692	ctsio->kern_data_resid = 0;
5693	ctsio->kern_rel_offset = 0;
5694	ctsio->kern_sg_entries = 0;
5695	ctsio->be_move_done = ctl_config_move_done;
5696	ctl_datamove((union ctl_io *)ctsio);
5697
5698	return (CTL_RETVAL_COMPLETE);
5699}
5700
5701int
5702ctl_write_buffer(struct ctl_scsiio *ctsio)
5703{
5704	struct scsi_write_buffer *cdb;
5705	struct ctl_lun *lun;
5706	int buffer_offset, len;
5707
5708	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5709
5710	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5711	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5712
5713	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5714		ctl_set_invalid_field(ctsio,
5715				      /*sks_valid*/ 1,
5716				      /*command*/ 1,
5717				      /*field*/ 1,
5718				      /*bit_valid*/ 1,
5719				      /*bit*/ 4);
5720		ctl_done((union ctl_io *)ctsio);
5721		return (CTL_RETVAL_COMPLETE);
5722	}
5723
5724	len = scsi_3btoul(cdb->length);
5725	buffer_offset = scsi_3btoul(cdb->offset);
5726
5727	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5728		ctl_set_invalid_field(ctsio,
5729				      /*sks_valid*/ 1,
5730				      /*command*/ 1,
5731				      /*field*/ 6,
5732				      /*bit_valid*/ 0,
5733				      /*bit*/ 0);
5734		ctl_done((union ctl_io *)ctsio);
5735		return (CTL_RETVAL_COMPLETE);
5736	}
5737
5738	/*
5739	 * If we've got a kernel request that hasn't been malloced yet,
5740	 * malloc it and tell the caller the data buffer is here.
5741	 */
5742	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5743		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5744		ctsio->kern_data_len = len;
5745		ctsio->kern_total_len = len;
5746		ctsio->kern_data_resid = 0;
5747		ctsio->kern_rel_offset = 0;
5748		ctsio->kern_sg_entries = 0;
5749		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5750		ctsio->be_move_done = ctl_config_move_done;
5751		ctl_datamove((union ctl_io *)ctsio);
5752
5753		return (CTL_RETVAL_COMPLETE);
5754	}
5755
5756	ctl_done((union ctl_io *)ctsio);
5757
5758	return (CTL_RETVAL_COMPLETE);
5759}
5760
5761int
5762ctl_write_same(struct ctl_scsiio *ctsio)
5763{
5764	struct ctl_lun *lun;
5765	struct ctl_lba_len_flags *lbalen;
5766	uint64_t lba;
5767	uint32_t num_blocks;
5768	int len, retval;
5769	uint8_t byte2;
5770
5771	retval = CTL_RETVAL_COMPLETE;
5772
5773	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5774
5775	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5776
5777	switch (ctsio->cdb[0]) {
5778	case WRITE_SAME_10: {
5779		struct scsi_write_same_10 *cdb;
5780
5781		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5782
5783		lba = scsi_4btoul(cdb->addr);
5784		num_blocks = scsi_2btoul(cdb->length);
5785		byte2 = cdb->byte2;
5786		break;
5787	}
5788	case WRITE_SAME_16: {
5789		struct scsi_write_same_16 *cdb;
5790
5791		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5792
5793		lba = scsi_8btou64(cdb->addr);
5794		num_blocks = scsi_4btoul(cdb->length);
5795		byte2 = cdb->byte2;
5796		break;
5797	}
5798	default:
5799		/*
5800		 * We got a command we don't support.  This shouldn't
5801		 * happen, commands should be filtered out above us.
5802		 */
5803		ctl_set_invalid_opcode(ctsio);
5804		ctl_done((union ctl_io *)ctsio);
5805
5806		return (CTL_RETVAL_COMPLETE);
5807		break; /* NOTREACHED */
5808	}
5809
5810	/*
5811	 * The first check is to make sure we're in bounds, the second
5812	 * check is to catch wrap-around problems.  If the lba + num blocks
5813	 * is less than the lba, then we've wrapped around and the block
5814	 * range is invalid anyway.
5815	 */
5816	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5817	 || ((lba + num_blocks) < lba)) {
5818		ctl_set_lba_out_of_range(ctsio);
5819		ctl_done((union ctl_io *)ctsio);
5820		return (CTL_RETVAL_COMPLETE);
5821	}
5822
5823	/* Zero number of blocks means "to the last logical block" */
5824	if (num_blocks == 0) {
5825		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5826			ctl_set_invalid_field(ctsio,
5827					      /*sks_valid*/ 0,
5828					      /*command*/ 1,
5829					      /*field*/ 0,
5830					      /*bit_valid*/ 0,
5831					      /*bit*/ 0);
5832			ctl_done((union ctl_io *)ctsio);
5833			return (CTL_RETVAL_COMPLETE);
5834		}
5835		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5836	}
5837
5838	len = lun->be_lun->blocksize;
5839
5840	/*
5841	 * If we've got a kernel request that hasn't been malloced yet,
5842	 * malloc it and tell the caller the data buffer is here.
5843	 */
5844	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5845		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5846		ctsio->kern_data_len = len;
5847		ctsio->kern_total_len = len;
5848		ctsio->kern_data_resid = 0;
5849		ctsio->kern_rel_offset = 0;
5850		ctsio->kern_sg_entries = 0;
5851		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5852		ctsio->be_move_done = ctl_config_move_done;
5853		ctl_datamove((union ctl_io *)ctsio);
5854
5855		return (CTL_RETVAL_COMPLETE);
5856	}
5857
5858	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5859	lbalen->lba = lba;
5860	lbalen->len = num_blocks;
5861	lbalen->flags = byte2;
5862	retval = lun->backend->config_write((union ctl_io *)ctsio);
5863
5864	return (retval);
5865}
5866
5867int
5868ctl_unmap(struct ctl_scsiio *ctsio)
5869{
5870	struct ctl_lun *lun;
5871	struct scsi_unmap *cdb;
5872	struct ctl_ptr_len_flags *ptrlen;
5873	struct scsi_unmap_header *hdr;
5874	struct scsi_unmap_desc *buf, *end;
5875	uint64_t lba;
5876	uint32_t num_blocks;
5877	int len, retval;
5878	uint8_t byte2;
5879
5880	retval = CTL_RETVAL_COMPLETE;
5881
5882	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5883
5884	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5885	cdb = (struct scsi_unmap *)ctsio->cdb;
5886
5887	len = scsi_2btoul(cdb->length);
5888	byte2 = cdb->byte2;
5889
5890	/*
5891	 * If we've got a kernel request that hasn't been malloced yet,
5892	 * malloc it and tell the caller the data buffer is here.
5893	 */
5894	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5895		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5896		ctsio->kern_data_len = len;
5897		ctsio->kern_total_len = len;
5898		ctsio->kern_data_resid = 0;
5899		ctsio->kern_rel_offset = 0;
5900		ctsio->kern_sg_entries = 0;
5901		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5902		ctsio->be_move_done = ctl_config_move_done;
5903		ctl_datamove((union ctl_io *)ctsio);
5904
5905		return (CTL_RETVAL_COMPLETE);
5906	}
5907
5908	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5909	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5910	if (len < sizeof (*hdr) ||
5911	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5912	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5913	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5914		ctl_set_invalid_field(ctsio,
5915				      /*sks_valid*/ 0,
5916				      /*command*/ 0,
5917				      /*field*/ 0,
5918				      /*bit_valid*/ 0,
5919				      /*bit*/ 0);
5920		ctl_done((union ctl_io *)ctsio);
5921		return (CTL_RETVAL_COMPLETE);
5922	}
5923	len = scsi_2btoul(hdr->desc_length);
5924	buf = (struct scsi_unmap_desc *)(hdr + 1);
5925	end = buf + len / sizeof(*buf);
5926
5927	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5928	ptrlen->ptr = (void *)buf;
5929	ptrlen->len = len;
5930	ptrlen->flags = byte2;
5931
5932	for (; buf < end; buf++) {
5933		lba = scsi_8btou64(buf->lba);
5934		num_blocks = scsi_4btoul(buf->length);
5935		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5936		 || ((lba + num_blocks) < lba)) {
5937			ctl_set_lba_out_of_range(ctsio);
5938			ctl_done((union ctl_io *)ctsio);
5939			return (CTL_RETVAL_COMPLETE);
5940		}
5941	}
5942
5943	retval = lun->backend->config_write((union ctl_io *)ctsio);
5944
5945	return (retval);
5946}
5947
5948/*
5949 * Note that this function currently doesn't actually do anything inside
5950 * CTL to enforce things if the DQue bit is turned on.
5951 *
5952 * Also note that this function can't be used in the default case, because
5953 * the DQue bit isn't set in the changeable mask for the control mode page
5954 * anyway.  This is just here as an example for how to implement a page
5955 * handler, and a placeholder in case we want to allow the user to turn
5956 * tagged queueing on and off.
5957 *
5958 * The D_SENSE bit handling is functional, however, and will turn
5959 * descriptor sense on and off for a given LUN.
5960 */
5961int
5962ctl_control_page_handler(struct ctl_scsiio *ctsio,
5963			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5964{
5965	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5966	struct ctl_lun *lun;
5967	struct ctl_softc *softc;
5968	int set_ua;
5969	uint32_t initidx;
5970
5971	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5972	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5973	set_ua = 0;
5974
5975	user_cp = (struct scsi_control_page *)page_ptr;
5976	current_cp = (struct scsi_control_page *)
5977		(page_index->page_data + (page_index->page_len *
5978		CTL_PAGE_CURRENT));
5979	saved_cp = (struct scsi_control_page *)
5980		(page_index->page_data + (page_index->page_len *
5981		CTL_PAGE_SAVED));
5982
5983	softc = control_softc;
5984
5985	mtx_lock(&lun->lun_lock);
5986	if (((current_cp->rlec & SCP_DSENSE) == 0)
5987	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5988		/*
5989		 * Descriptor sense is currently turned off and the user
5990		 * wants to turn it on.
5991		 */
5992		current_cp->rlec |= SCP_DSENSE;
5993		saved_cp->rlec |= SCP_DSENSE;
5994		lun->flags |= CTL_LUN_SENSE_DESC;
5995		set_ua = 1;
5996	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5997		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5998		/*
5999		 * Descriptor sense is currently turned on, and the user
6000		 * wants to turn it off.
6001		 */
6002		current_cp->rlec &= ~SCP_DSENSE;
6003		saved_cp->rlec &= ~SCP_DSENSE;
6004		lun->flags &= ~CTL_LUN_SENSE_DESC;
6005		set_ua = 1;
6006	}
6007	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6008		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6009#ifdef NEEDTOPORT
6010			csevent_log(CSC_CTL | CSC_SHELF_SW |
6011				    CTL_UNTAG_TO_UNTAG,
6012				    csevent_LogType_Trace,
6013				    csevent_Severity_Information,
6014				    csevent_AlertLevel_Green,
6015				    csevent_FRU_Firmware,
6016				    csevent_FRU_Unknown,
6017				    "Received untagged to untagged transition");
6018#endif /* NEEDTOPORT */
6019		} else {
6020#ifdef NEEDTOPORT
6021			csevent_log(CSC_CTL | CSC_SHELF_SW |
6022				    CTL_UNTAG_TO_TAG,
6023				    csevent_LogType_ConfigChange,
6024				    csevent_Severity_Information,
6025				    csevent_AlertLevel_Green,
6026				    csevent_FRU_Firmware,
6027				    csevent_FRU_Unknown,
6028				    "Received untagged to tagged "
6029				    "queueing transition");
6030#endif /* NEEDTOPORT */
6031
6032			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6033			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6034			set_ua = 1;
6035		}
6036	} else {
6037		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6038#ifdef NEEDTOPORT
6039			csevent_log(CSC_CTL | CSC_SHELF_SW |
6040				    CTL_TAG_TO_UNTAG,
6041				    csevent_LogType_ConfigChange,
6042				    csevent_Severity_Warning,
6043				    csevent_AlertLevel_Yellow,
6044				    csevent_FRU_Firmware,
6045				    csevent_FRU_Unknown,
6046				    "Received tagged queueing to untagged "
6047				    "transition");
6048#endif /* NEEDTOPORT */
6049
6050			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6051			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6052			set_ua = 1;
6053		} else {
6054#ifdef NEEDTOPORT
6055			csevent_log(CSC_CTL | CSC_SHELF_SW |
6056				    CTL_TAG_TO_TAG,
6057				    csevent_LogType_Trace,
6058				    csevent_Severity_Information,
6059				    csevent_AlertLevel_Green,
6060				    csevent_FRU_Firmware,
6061				    csevent_FRU_Unknown,
6062				    "Received tagged queueing to tagged "
6063				    "queueing transition");
6064#endif /* NEEDTOPORT */
6065		}
6066	}
6067	if (set_ua != 0) {
6068		int i;
6069		/*
6070		 * Let other initiators know that the mode
6071		 * parameters for this LUN have changed.
6072		 */
6073		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6074			if (i == initidx)
6075				continue;
6076
6077			lun->pending_sense[i].ua_pending |=
6078				CTL_UA_MODE_CHANGE;
6079		}
6080	}
6081	mtx_unlock(&lun->lun_lock);
6082
6083	return (0);
6084}
6085
6086int
6087ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6088		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6089{
6090	return (0);
6091}
6092
6093int
6094ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6095			   struct ctl_page_index *page_index, int pc)
6096{
6097	struct copan_power_subpage *page;
6098
6099	page = (struct copan_power_subpage *)page_index->page_data +
6100		(page_index->page_len * pc);
6101
6102	switch (pc) {
6103	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6104		/*
6105		 * We don't update the changable bits for this page.
6106		 */
6107		break;
6108	case SMS_PAGE_CTRL_CURRENT >> 6:
6109	case SMS_PAGE_CTRL_DEFAULT >> 6:
6110	case SMS_PAGE_CTRL_SAVED >> 6:
6111#ifdef NEEDTOPORT
6112		ctl_update_power_subpage(page);
6113#endif
6114		break;
6115	default:
6116#ifdef NEEDTOPORT
6117		EPRINT(0, "Invalid PC %d!!", pc);
6118#endif
6119		break;
6120	}
6121	return (0);
6122}
6123
6124
6125int
6126ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6127		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6128{
6129	struct copan_aps_subpage *user_sp;
6130	struct copan_aps_subpage *current_sp;
6131	union ctl_modepage_info *modepage_info;
6132	struct ctl_softc *softc;
6133	struct ctl_lun *lun;
6134	int retval;
6135
6136	retval = CTL_RETVAL_COMPLETE;
6137	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6138		     (page_index->page_len * CTL_PAGE_CURRENT));
6139	softc = control_softc;
6140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6141
6142	user_sp = (struct copan_aps_subpage *)page_ptr;
6143
6144	modepage_info = (union ctl_modepage_info *)
6145		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6146
6147	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6148	modepage_info->header.subpage = page_index->subpage;
6149	modepage_info->aps.lock_active = user_sp->lock_active;
6150
6151	mtx_lock(&softc->ctl_lock);
6152
6153	/*
6154	 * If there is a request to lock the LUN and another LUN is locked
6155	 * this is an error. If the requested LUN is already locked ignore
6156	 * the request. If no LUN is locked attempt to lock it.
6157	 * if there is a request to unlock the LUN and the LUN is currently
6158	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6159	 * if another LUN is locked or no LUN is locked.
6160	 */
6161	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6162		if (softc->aps_locked_lun == lun->lun) {
6163			/*
6164			 * This LUN is already locked, so we're done.
6165			 */
6166			retval = CTL_RETVAL_COMPLETE;
6167		} else if (softc->aps_locked_lun == 0) {
6168			/*
6169			 * No one has the lock, pass the request to the
6170			 * backend.
6171			 */
6172			retval = lun->backend->config_write(
6173				(union ctl_io *)ctsio);
6174		} else {
6175			/*
6176			 * Someone else has the lock, throw out the request.
6177			 */
6178			ctl_set_already_locked(ctsio);
6179			free(ctsio->kern_data_ptr, M_CTL);
6180			ctl_done((union ctl_io *)ctsio);
6181
6182			/*
6183			 * Set the return value so that ctl_do_mode_select()
6184			 * won't try to complete the command.  We already
6185			 * completed it here.
6186			 */
6187			retval = CTL_RETVAL_ERROR;
6188		}
6189	} else if (softc->aps_locked_lun == lun->lun) {
6190		/*
6191		 * This LUN is locked, so pass the unlock request to the
6192		 * backend.
6193		 */
6194		retval = lun->backend->config_write((union ctl_io *)ctsio);
6195	}
6196	mtx_unlock(&softc->ctl_lock);
6197
6198	return (retval);
6199}
6200
6201int
6202ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6203				struct ctl_page_index *page_index,
6204				uint8_t *page_ptr)
6205{
6206	uint8_t *c;
6207	int i;
6208
6209	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6210	ctl_time_io_secs =
6211		(c[0] << 8) |
6212		(c[1] << 0) |
6213		0;
6214	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6215	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6216	printf("page data:");
6217	for (i=0; i<8; i++)
6218		printf(" %.2x",page_ptr[i]);
6219	printf("\n");
6220	return (0);
6221}
6222
6223int
6224ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6225			       struct ctl_page_index *page_index,
6226			       int pc)
6227{
6228	struct copan_debugconf_subpage *page;
6229
6230	page = (struct copan_debugconf_subpage *)page_index->page_data +
6231		(page_index->page_len * pc);
6232
6233	switch (pc) {
6234	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6235	case SMS_PAGE_CTRL_DEFAULT >> 6:
6236	case SMS_PAGE_CTRL_SAVED >> 6:
6237		/*
6238		 * We don't update the changable or default bits for this page.
6239		 */
6240		break;
6241	case SMS_PAGE_CTRL_CURRENT >> 6:
6242		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6243		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6244		break;
6245	default:
6246#ifdef NEEDTOPORT
6247		EPRINT(0, "Invalid PC %d!!", pc);
6248#endif /* NEEDTOPORT */
6249		break;
6250	}
6251	return (0);
6252}
6253
6254
6255static int
6256ctl_do_mode_select(union ctl_io *io)
6257{
6258	struct scsi_mode_page_header *page_header;
6259	struct ctl_page_index *page_index;
6260	struct ctl_scsiio *ctsio;
6261	int control_dev, page_len;
6262	int page_len_offset, page_len_size;
6263	union ctl_modepage_info *modepage_info;
6264	struct ctl_lun *lun;
6265	int *len_left, *len_used;
6266	int retval, i;
6267
6268	ctsio = &io->scsiio;
6269	page_index = NULL;
6270	page_len = 0;
6271	retval = CTL_RETVAL_COMPLETE;
6272
6273	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6274
6275	if (lun->be_lun->lun_type != T_DIRECT)
6276		control_dev = 1;
6277	else
6278		control_dev = 0;
6279
6280	modepage_info = (union ctl_modepage_info *)
6281		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6282	len_left = &modepage_info->header.len_left;
6283	len_used = &modepage_info->header.len_used;
6284
6285do_next_page:
6286
6287	page_header = (struct scsi_mode_page_header *)
6288		(ctsio->kern_data_ptr + *len_used);
6289
6290	if (*len_left == 0) {
6291		free(ctsio->kern_data_ptr, M_CTL);
6292		ctl_set_success(ctsio);
6293		ctl_done((union ctl_io *)ctsio);
6294		return (CTL_RETVAL_COMPLETE);
6295	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6296
6297		free(ctsio->kern_data_ptr, M_CTL);
6298		ctl_set_param_len_error(ctsio);
6299		ctl_done((union ctl_io *)ctsio);
6300		return (CTL_RETVAL_COMPLETE);
6301
6302	} else if ((page_header->page_code & SMPH_SPF)
6303		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6304
6305		free(ctsio->kern_data_ptr, M_CTL);
6306		ctl_set_param_len_error(ctsio);
6307		ctl_done((union ctl_io *)ctsio);
6308		return (CTL_RETVAL_COMPLETE);
6309	}
6310
6311
6312	/*
6313	 * XXX KDM should we do something with the block descriptor?
6314	 */
6315	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6316
6317		if ((control_dev != 0)
6318		 && (lun->mode_pages.index[i].page_flags &
6319		     CTL_PAGE_FLAG_DISK_ONLY))
6320			continue;
6321
6322		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6323		    (page_header->page_code & SMPH_PC_MASK))
6324			continue;
6325
6326		/*
6327		 * If neither page has a subpage code, then we've got a
6328		 * match.
6329		 */
6330		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6331		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6332			page_index = &lun->mode_pages.index[i];
6333			page_len = page_header->page_length;
6334			break;
6335		}
6336
6337		/*
6338		 * If both pages have subpages, then the subpage numbers
6339		 * have to match.
6340		 */
6341		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6342		  && (page_header->page_code & SMPH_SPF)) {
6343			struct scsi_mode_page_header_sp *sph;
6344
6345			sph = (struct scsi_mode_page_header_sp *)page_header;
6346
6347			if (lun->mode_pages.index[i].subpage ==
6348			    sph->subpage) {
6349				page_index = &lun->mode_pages.index[i];
6350				page_len = scsi_2btoul(sph->page_length);
6351				break;
6352			}
6353		}
6354	}
6355
6356	/*
6357	 * If we couldn't find the page, or if we don't have a mode select
6358	 * handler for it, send back an error to the user.
6359	 */
6360	if ((page_index == NULL)
6361	 || (page_index->select_handler == NULL)) {
6362		ctl_set_invalid_field(ctsio,
6363				      /*sks_valid*/ 1,
6364				      /*command*/ 0,
6365				      /*field*/ *len_used,
6366				      /*bit_valid*/ 0,
6367				      /*bit*/ 0);
6368		free(ctsio->kern_data_ptr, M_CTL);
6369		ctl_done((union ctl_io *)ctsio);
6370		return (CTL_RETVAL_COMPLETE);
6371	}
6372
6373	if (page_index->page_code & SMPH_SPF) {
6374		page_len_offset = 2;
6375		page_len_size = 2;
6376	} else {
6377		page_len_size = 1;
6378		page_len_offset = 1;
6379	}
6380
6381	/*
6382	 * If the length the initiator gives us isn't the one we specify in
6383	 * the mode page header, or if they didn't specify enough data in
6384	 * the CDB to avoid truncating this page, kick out the request.
6385	 */
6386	if ((page_len != (page_index->page_len - page_len_offset -
6387			  page_len_size))
6388	 || (*len_left < page_index->page_len)) {
6389
6390
6391		ctl_set_invalid_field(ctsio,
6392				      /*sks_valid*/ 1,
6393				      /*command*/ 0,
6394				      /*field*/ *len_used + page_len_offset,
6395				      /*bit_valid*/ 0,
6396				      /*bit*/ 0);
6397		free(ctsio->kern_data_ptr, M_CTL);
6398		ctl_done((union ctl_io *)ctsio);
6399		return (CTL_RETVAL_COMPLETE);
6400	}
6401
6402	/*
6403	 * Run through the mode page, checking to make sure that the bits
6404	 * the user changed are actually legal for him to change.
6405	 */
6406	for (i = 0; i < page_index->page_len; i++) {
6407		uint8_t *user_byte, *change_mask, *current_byte;
6408		int bad_bit;
6409		int j;
6410
6411		user_byte = (uint8_t *)page_header + i;
6412		change_mask = page_index->page_data +
6413			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6414		current_byte = page_index->page_data +
6415			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6416
6417		/*
6418		 * Check to see whether the user set any bits in this byte
6419		 * that he is not allowed to set.
6420		 */
6421		if ((*user_byte & ~(*change_mask)) ==
6422		    (*current_byte & ~(*change_mask)))
6423			continue;
6424
6425		/*
6426		 * Go through bit by bit to determine which one is illegal.
6427		 */
6428		bad_bit = 0;
6429		for (j = 7; j >= 0; j--) {
6430			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6431			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6432				bad_bit = i;
6433				break;
6434			}
6435		}
6436		ctl_set_invalid_field(ctsio,
6437				      /*sks_valid*/ 1,
6438				      /*command*/ 0,
6439				      /*field*/ *len_used + i,
6440				      /*bit_valid*/ 1,
6441				      /*bit*/ bad_bit);
6442		free(ctsio->kern_data_ptr, M_CTL);
6443		ctl_done((union ctl_io *)ctsio);
6444		return (CTL_RETVAL_COMPLETE);
6445	}
6446
6447	/*
6448	 * Decrement these before we call the page handler, since we may
6449	 * end up getting called back one way or another before the handler
6450	 * returns to this context.
6451	 */
6452	*len_left -= page_index->page_len;
6453	*len_used += page_index->page_len;
6454
6455	retval = page_index->select_handler(ctsio, page_index,
6456					    (uint8_t *)page_header);
6457
6458	/*
6459	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6460	 * wait until this queued command completes to finish processing
6461	 * the mode page.  If it returns anything other than
6462	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6463	 * already set the sense information, freed the data pointer, and
6464	 * completed the io for us.
6465	 */
6466	if (retval != CTL_RETVAL_COMPLETE)
6467		goto bailout_no_done;
6468
6469	/*
6470	 * If the initiator sent us more than one page, parse the next one.
6471	 */
6472	if (*len_left > 0)
6473		goto do_next_page;
6474
6475	ctl_set_success(ctsio);
6476	free(ctsio->kern_data_ptr, M_CTL);
6477	ctl_done((union ctl_io *)ctsio);
6478
6479bailout_no_done:
6480
6481	return (CTL_RETVAL_COMPLETE);
6482
6483}
6484
6485int
6486ctl_mode_select(struct ctl_scsiio *ctsio)
6487{
6488	int param_len, pf, sp;
6489	int header_size, bd_len;
6490	int len_left, len_used;
6491	struct ctl_page_index *page_index;
6492	struct ctl_lun *lun;
6493	int control_dev, page_len;
6494	union ctl_modepage_info *modepage_info;
6495	int retval;
6496
6497	pf = 0;
6498	sp = 0;
6499	page_len = 0;
6500	len_used = 0;
6501	len_left = 0;
6502	retval = 0;
6503	bd_len = 0;
6504	page_index = NULL;
6505
6506	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6507
6508	if (lun->be_lun->lun_type != T_DIRECT)
6509		control_dev = 1;
6510	else
6511		control_dev = 0;
6512
6513	switch (ctsio->cdb[0]) {
6514	case MODE_SELECT_6: {
6515		struct scsi_mode_select_6 *cdb;
6516
6517		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6518
6519		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6520		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6521
6522		param_len = cdb->length;
6523		header_size = sizeof(struct scsi_mode_header_6);
6524		break;
6525	}
6526	case MODE_SELECT_10: {
6527		struct scsi_mode_select_10 *cdb;
6528
6529		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6530
6531		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6532		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6533
6534		param_len = scsi_2btoul(cdb->length);
6535		header_size = sizeof(struct scsi_mode_header_10);
6536		break;
6537	}
6538	default:
6539		ctl_set_invalid_opcode(ctsio);
6540		ctl_done((union ctl_io *)ctsio);
6541		return (CTL_RETVAL_COMPLETE);
6542		break; /* NOTREACHED */
6543	}
6544
6545	/*
6546	 * From SPC-3:
6547	 * "A parameter list length of zero indicates that the Data-Out Buffer
6548	 * shall be empty. This condition shall not be considered as an error."
6549	 */
6550	if (param_len == 0) {
6551		ctl_set_success(ctsio);
6552		ctl_done((union ctl_io *)ctsio);
6553		return (CTL_RETVAL_COMPLETE);
6554	}
6555
6556	/*
6557	 * Since we'll hit this the first time through, prior to
6558	 * allocation, we don't need to free a data buffer here.
6559	 */
6560	if (param_len < header_size) {
6561		ctl_set_param_len_error(ctsio);
6562		ctl_done((union ctl_io *)ctsio);
6563		return (CTL_RETVAL_COMPLETE);
6564	}
6565
6566	/*
6567	 * Allocate the data buffer and grab the user's data.  In theory,
6568	 * we shouldn't have to sanity check the parameter list length here
6569	 * because the maximum size is 64K.  We should be able to malloc
6570	 * that much without too many problems.
6571	 */
6572	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6573		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6574		ctsio->kern_data_len = param_len;
6575		ctsio->kern_total_len = param_len;
6576		ctsio->kern_data_resid = 0;
6577		ctsio->kern_rel_offset = 0;
6578		ctsio->kern_sg_entries = 0;
6579		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6580		ctsio->be_move_done = ctl_config_move_done;
6581		ctl_datamove((union ctl_io *)ctsio);
6582
6583		return (CTL_RETVAL_COMPLETE);
6584	}
6585
6586	switch (ctsio->cdb[0]) {
6587	case MODE_SELECT_6: {
6588		struct scsi_mode_header_6 *mh6;
6589
6590		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6591		bd_len = mh6->blk_desc_len;
6592		break;
6593	}
6594	case MODE_SELECT_10: {
6595		struct scsi_mode_header_10 *mh10;
6596
6597		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6598		bd_len = scsi_2btoul(mh10->blk_desc_len);
6599		break;
6600	}
6601	default:
6602		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6603		break;
6604	}
6605
6606	if (param_len < (header_size + bd_len)) {
6607		free(ctsio->kern_data_ptr, M_CTL);
6608		ctl_set_param_len_error(ctsio);
6609		ctl_done((union ctl_io *)ctsio);
6610		return (CTL_RETVAL_COMPLETE);
6611	}
6612
6613	/*
6614	 * Set the IO_CONT flag, so that if this I/O gets passed to
6615	 * ctl_config_write_done(), it'll get passed back to
6616	 * ctl_do_mode_select() for further processing, or completion if
6617	 * we're all done.
6618	 */
6619	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6620	ctsio->io_cont = ctl_do_mode_select;
6621
6622	modepage_info = (union ctl_modepage_info *)
6623		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6624
6625	memset(modepage_info, 0, sizeof(*modepage_info));
6626
6627	len_left = param_len - header_size - bd_len;
6628	len_used = header_size + bd_len;
6629
6630	modepage_info->header.len_left = len_left;
6631	modepage_info->header.len_used = len_used;
6632
6633	return (ctl_do_mode_select((union ctl_io *)ctsio));
6634}
6635
6636int
6637ctl_mode_sense(struct ctl_scsiio *ctsio)
6638{
6639	struct ctl_lun *lun;
6640	int pc, page_code, dbd, llba, subpage;
6641	int alloc_len, page_len, header_len, total_len;
6642	struct scsi_mode_block_descr *block_desc;
6643	struct ctl_page_index *page_index;
6644	int control_dev;
6645
6646	dbd = 0;
6647	llba = 0;
6648	block_desc = NULL;
6649	page_index = NULL;
6650
6651	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6652
6653	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6654
6655	if (lun->be_lun->lun_type != T_DIRECT)
6656		control_dev = 1;
6657	else
6658		control_dev = 0;
6659
6660	if (lun->flags & CTL_LUN_PR_RESERVED) {
6661		uint32_t residx;
6662
6663		/*
6664		 * XXX KDM need a lock here.
6665		 */
6666		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6667		if ((lun->res_type == SPR_TYPE_EX_AC
6668		  && residx != lun->pr_res_idx)
6669		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6670		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6671		  && !lun->per_res[residx].registered)) {
6672			ctl_set_reservation_conflict(ctsio);
6673			ctl_done((union ctl_io *)ctsio);
6674			return (CTL_RETVAL_COMPLETE);
6675		}
6676	}
6677
6678	switch (ctsio->cdb[0]) {
6679	case MODE_SENSE_6: {
6680		struct scsi_mode_sense_6 *cdb;
6681
6682		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6683
6684		header_len = sizeof(struct scsi_mode_hdr_6);
6685		if (cdb->byte2 & SMS_DBD)
6686			dbd = 1;
6687		else
6688			header_len += sizeof(struct scsi_mode_block_descr);
6689
6690		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6691		page_code = cdb->page & SMS_PAGE_CODE;
6692		subpage = cdb->subpage;
6693		alloc_len = cdb->length;
6694		break;
6695	}
6696	case MODE_SENSE_10: {
6697		struct scsi_mode_sense_10 *cdb;
6698
6699		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6700
6701		header_len = sizeof(struct scsi_mode_hdr_10);
6702
6703		if (cdb->byte2 & SMS_DBD)
6704			dbd = 1;
6705		else
6706			header_len += sizeof(struct scsi_mode_block_descr);
6707		if (cdb->byte2 & SMS10_LLBAA)
6708			llba = 1;
6709		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6710		page_code = cdb->page & SMS_PAGE_CODE;
6711		subpage = cdb->subpage;
6712		alloc_len = scsi_2btoul(cdb->length);
6713		break;
6714	}
6715	default:
6716		ctl_set_invalid_opcode(ctsio);
6717		ctl_done((union ctl_io *)ctsio);
6718		return (CTL_RETVAL_COMPLETE);
6719		break; /* NOTREACHED */
6720	}
6721
6722	/*
6723	 * We have to make a first pass through to calculate the size of
6724	 * the pages that match the user's query.  Then we allocate enough
6725	 * memory to hold it, and actually copy the data into the buffer.
6726	 */
6727	switch (page_code) {
6728	case SMS_ALL_PAGES_PAGE: {
6729		int i;
6730
6731		page_len = 0;
6732
6733		/*
6734		 * At the moment, values other than 0 and 0xff here are
6735		 * reserved according to SPC-3.
6736		 */
6737		if ((subpage != SMS_SUBPAGE_PAGE_0)
6738		 && (subpage != SMS_SUBPAGE_ALL)) {
6739			ctl_set_invalid_field(ctsio,
6740					      /*sks_valid*/ 1,
6741					      /*command*/ 1,
6742					      /*field*/ 3,
6743					      /*bit_valid*/ 0,
6744					      /*bit*/ 0);
6745			ctl_done((union ctl_io *)ctsio);
6746			return (CTL_RETVAL_COMPLETE);
6747		}
6748
6749		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6750			if ((control_dev != 0)
6751			 && (lun->mode_pages.index[i].page_flags &
6752			     CTL_PAGE_FLAG_DISK_ONLY))
6753				continue;
6754
6755			/*
6756			 * We don't use this subpage if the user didn't
6757			 * request all subpages.
6758			 */
6759			if ((lun->mode_pages.index[i].subpage != 0)
6760			 && (subpage == SMS_SUBPAGE_PAGE_0))
6761				continue;
6762
6763#if 0
6764			printf("found page %#x len %d\n",
6765			       lun->mode_pages.index[i].page_code &
6766			       SMPH_PC_MASK,
6767			       lun->mode_pages.index[i].page_len);
6768#endif
6769			page_len += lun->mode_pages.index[i].page_len;
6770		}
6771		break;
6772	}
6773	default: {
6774		int i;
6775
6776		page_len = 0;
6777
6778		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6779			/* Look for the right page code */
6780			if ((lun->mode_pages.index[i].page_code &
6781			     SMPH_PC_MASK) != page_code)
6782				continue;
6783
6784			/* Look for the right subpage or the subpage wildcard*/
6785			if ((lun->mode_pages.index[i].subpage != subpage)
6786			 && (subpage != SMS_SUBPAGE_ALL))
6787				continue;
6788
6789			/* Make sure the page is supported for this dev type */
6790			if ((control_dev != 0)
6791			 && (lun->mode_pages.index[i].page_flags &
6792			     CTL_PAGE_FLAG_DISK_ONLY))
6793				continue;
6794
6795#if 0
6796			printf("found page %#x len %d\n",
6797			       lun->mode_pages.index[i].page_code &
6798			       SMPH_PC_MASK,
6799			       lun->mode_pages.index[i].page_len);
6800#endif
6801
6802			page_len += lun->mode_pages.index[i].page_len;
6803		}
6804
6805		if (page_len == 0) {
6806			ctl_set_invalid_field(ctsio,
6807					      /*sks_valid*/ 1,
6808					      /*command*/ 1,
6809					      /*field*/ 2,
6810					      /*bit_valid*/ 1,
6811					      /*bit*/ 5);
6812			ctl_done((union ctl_io *)ctsio);
6813			return (CTL_RETVAL_COMPLETE);
6814		}
6815		break;
6816	}
6817	}
6818
6819	total_len = header_len + page_len;
6820#if 0
6821	printf("header_len = %d, page_len = %d, total_len = %d\n",
6822	       header_len, page_len, total_len);
6823#endif
6824
6825	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6826	ctsio->kern_sg_entries = 0;
6827	ctsio->kern_data_resid = 0;
6828	ctsio->kern_rel_offset = 0;
6829	if (total_len < alloc_len) {
6830		ctsio->residual = alloc_len - total_len;
6831		ctsio->kern_data_len = total_len;
6832		ctsio->kern_total_len = total_len;
6833	} else {
6834		ctsio->residual = 0;
6835		ctsio->kern_data_len = alloc_len;
6836		ctsio->kern_total_len = alloc_len;
6837	}
6838
6839	switch (ctsio->cdb[0]) {
6840	case MODE_SENSE_6: {
6841		struct scsi_mode_hdr_6 *header;
6842
6843		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6844
6845		header->datalen = ctl_min(total_len - 1, 254);
6846
6847		if (dbd)
6848			header->block_descr_len = 0;
6849		else
6850			header->block_descr_len =
6851				sizeof(struct scsi_mode_block_descr);
6852		block_desc = (struct scsi_mode_block_descr *)&header[1];
6853		break;
6854	}
6855	case MODE_SENSE_10: {
6856		struct scsi_mode_hdr_10 *header;
6857		int datalen;
6858
6859		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6860
6861		datalen = ctl_min(total_len - 2, 65533);
6862		scsi_ulto2b(datalen, header->datalen);
6863		if (dbd)
6864			scsi_ulto2b(0, header->block_descr_len);
6865		else
6866			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6867				    header->block_descr_len);
6868		block_desc = (struct scsi_mode_block_descr *)&header[1];
6869		break;
6870	}
6871	default:
6872		panic("invalid CDB type %#x", ctsio->cdb[0]);
6873		break; /* NOTREACHED */
6874	}
6875
6876	/*
6877	 * If we've got a disk, use its blocksize in the block
6878	 * descriptor.  Otherwise, just set it to 0.
6879	 */
6880	if (dbd == 0) {
6881		if (control_dev != 0)
6882			scsi_ulto3b(lun->be_lun->blocksize,
6883				    block_desc->block_len);
6884		else
6885			scsi_ulto3b(0, block_desc->block_len);
6886	}
6887
6888	switch (page_code) {
6889	case SMS_ALL_PAGES_PAGE: {
6890		int i, data_used;
6891
6892		data_used = header_len;
6893		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6894			struct ctl_page_index *page_index;
6895
6896			page_index = &lun->mode_pages.index[i];
6897
6898			if ((control_dev != 0)
6899			 && (page_index->page_flags &
6900			    CTL_PAGE_FLAG_DISK_ONLY))
6901				continue;
6902
6903			/*
6904			 * We don't use this subpage if the user didn't
6905			 * request all subpages.  We already checked (above)
6906			 * to make sure the user only specified a subpage
6907			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6908			 */
6909			if ((page_index->subpage != 0)
6910			 && (subpage == SMS_SUBPAGE_PAGE_0))
6911				continue;
6912
6913			/*
6914			 * Call the handler, if it exists, to update the
6915			 * page to the latest values.
6916			 */
6917			if (page_index->sense_handler != NULL)
6918				page_index->sense_handler(ctsio, page_index,pc);
6919
6920			memcpy(ctsio->kern_data_ptr + data_used,
6921			       page_index->page_data +
6922			       (page_index->page_len * pc),
6923			       page_index->page_len);
6924			data_used += page_index->page_len;
6925		}
6926		break;
6927	}
6928	default: {
6929		int i, data_used;
6930
6931		data_used = header_len;
6932
6933		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6934			struct ctl_page_index *page_index;
6935
6936			page_index = &lun->mode_pages.index[i];
6937
6938			/* Look for the right page code */
6939			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6940				continue;
6941
6942			/* Look for the right subpage or the subpage wildcard*/
6943			if ((page_index->subpage != subpage)
6944			 && (subpage != SMS_SUBPAGE_ALL))
6945				continue;
6946
6947			/* Make sure the page is supported for this dev type */
6948			if ((control_dev != 0)
6949			 && (page_index->page_flags &
6950			     CTL_PAGE_FLAG_DISK_ONLY))
6951				continue;
6952
6953			/*
6954			 * Call the handler, if it exists, to update the
6955			 * page to the latest values.
6956			 */
6957			if (page_index->sense_handler != NULL)
6958				page_index->sense_handler(ctsio, page_index,pc);
6959
6960			memcpy(ctsio->kern_data_ptr + data_used,
6961			       page_index->page_data +
6962			       (page_index->page_len * pc),
6963			       page_index->page_len);
6964			data_used += page_index->page_len;
6965		}
6966		break;
6967	}
6968	}
6969
6970	ctsio->scsi_status = SCSI_STATUS_OK;
6971
6972	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6973	ctsio->be_move_done = ctl_config_move_done;
6974	ctl_datamove((union ctl_io *)ctsio);
6975
6976	return (CTL_RETVAL_COMPLETE);
6977}
6978
6979int
6980ctl_read_capacity(struct ctl_scsiio *ctsio)
6981{
6982	struct scsi_read_capacity *cdb;
6983	struct scsi_read_capacity_data *data;
6984	struct ctl_lun *lun;
6985	uint32_t lba;
6986
6987	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6988
6989	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6990
6991	lba = scsi_4btoul(cdb->addr);
6992	if (((cdb->pmi & SRC_PMI) == 0)
6993	 && (lba != 0)) {
6994		ctl_set_invalid_field(/*ctsio*/ ctsio,
6995				      /*sks_valid*/ 1,
6996				      /*command*/ 1,
6997				      /*field*/ 2,
6998				      /*bit_valid*/ 0,
6999				      /*bit*/ 0);
7000		ctl_done((union ctl_io *)ctsio);
7001		return (CTL_RETVAL_COMPLETE);
7002	}
7003
7004	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7005
7006	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7007	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7008	ctsio->residual = 0;
7009	ctsio->kern_data_len = sizeof(*data);
7010	ctsio->kern_total_len = sizeof(*data);
7011	ctsio->kern_data_resid = 0;
7012	ctsio->kern_rel_offset = 0;
7013	ctsio->kern_sg_entries = 0;
7014
7015	/*
7016	 * If the maximum LBA is greater than 0xfffffffe, the user must
7017	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7018	 * serivce action set.
7019	 */
7020	if (lun->be_lun->maxlba > 0xfffffffe)
7021		scsi_ulto4b(0xffffffff, data->addr);
7022	else
7023		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7024
7025	/*
7026	 * XXX KDM this may not be 512 bytes...
7027	 */
7028	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7029
7030	ctsio->scsi_status = SCSI_STATUS_OK;
7031
7032	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7033	ctsio->be_move_done = ctl_config_move_done;
7034	ctl_datamove((union ctl_io *)ctsio);
7035
7036	return (CTL_RETVAL_COMPLETE);
7037}
7038
7039int
7040ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7041{
7042	struct scsi_read_capacity_16 *cdb;
7043	struct scsi_read_capacity_data_long *data;
7044	struct ctl_lun *lun;
7045	uint64_t lba;
7046	uint32_t alloc_len;
7047
7048	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7049
7050	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7051
7052	alloc_len = scsi_4btoul(cdb->alloc_len);
7053	lba = scsi_8btou64(cdb->addr);
7054
7055	if ((cdb->reladr & SRC16_PMI)
7056	 && (lba != 0)) {
7057		ctl_set_invalid_field(/*ctsio*/ ctsio,
7058				      /*sks_valid*/ 1,
7059				      /*command*/ 1,
7060				      /*field*/ 2,
7061				      /*bit_valid*/ 0,
7062				      /*bit*/ 0);
7063		ctl_done((union ctl_io *)ctsio);
7064		return (CTL_RETVAL_COMPLETE);
7065	}
7066
7067	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7068
7069	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7070	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7071
7072	if (sizeof(*data) < alloc_len) {
7073		ctsio->residual = alloc_len - sizeof(*data);
7074		ctsio->kern_data_len = sizeof(*data);
7075		ctsio->kern_total_len = sizeof(*data);
7076	} else {
7077		ctsio->residual = 0;
7078		ctsio->kern_data_len = alloc_len;
7079		ctsio->kern_total_len = alloc_len;
7080	}
7081	ctsio->kern_data_resid = 0;
7082	ctsio->kern_rel_offset = 0;
7083	ctsio->kern_sg_entries = 0;
7084
7085	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7086	/* XXX KDM this may not be 512 bytes... */
7087	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7088	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7089	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7090	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7091		data->lalba_lbp[0] |= SRC16_LBPME;
7092
7093	ctsio->scsi_status = SCSI_STATUS_OK;
7094
7095	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7096	ctsio->be_move_done = ctl_config_move_done;
7097	ctl_datamove((union ctl_io *)ctsio);
7098
7099	return (CTL_RETVAL_COMPLETE);
7100}
7101
7102int
7103ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7104{
7105	struct scsi_maintenance_in *cdb;
7106	int retval;
7107	int alloc_len, total_len = 0;
7108	int num_target_port_groups, single;
7109	struct ctl_lun *lun;
7110	struct ctl_softc *softc;
7111	struct scsi_target_group_data *rtg_ptr;
7112	struct scsi_target_port_group_descriptor *tpg_desc_ptr1, *tpg_desc_ptr2;
7113	struct scsi_target_port_descriptor  *tp_desc_ptr1_1, *tp_desc_ptr1_2,
7114	                                    *tp_desc_ptr2_1, *tp_desc_ptr2_2;
7115
7116	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7117
7118	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7119	softc = control_softc;
7120	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7121
7122	retval = CTL_RETVAL_COMPLETE;
7123
7124	single = ctl_is_single;
7125	if (single)
7126        	num_target_port_groups = NUM_TARGET_PORT_GROUPS - 1;
7127	else
7128        	num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7129
7130	total_len = sizeof(struct scsi_target_group_data) +
7131		sizeof(struct scsi_target_port_group_descriptor) *
7132		num_target_port_groups +
7133		sizeof(struct scsi_target_port_descriptor) *
7134		NUM_PORTS_PER_GRP * num_target_port_groups;
7135
7136	alloc_len = scsi_4btoul(cdb->length);
7137
7138	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7139
7140	ctsio->kern_sg_entries = 0;
7141
7142	if (total_len < alloc_len) {
7143		ctsio->residual = alloc_len - total_len;
7144		ctsio->kern_data_len = total_len;
7145		ctsio->kern_total_len = total_len;
7146	} else {
7147		ctsio->residual = 0;
7148		ctsio->kern_data_len = alloc_len;
7149		ctsio->kern_total_len = alloc_len;
7150	}
7151	ctsio->kern_data_resid = 0;
7152	ctsio->kern_rel_offset = 0;
7153
7154	rtg_ptr = (struct scsi_target_group_data *)ctsio->kern_data_ptr;
7155
7156	tpg_desc_ptr1 = &rtg_ptr->groups[0];
7157	tp_desc_ptr1_1 = &tpg_desc_ptr1->descriptors[0];
7158	tp_desc_ptr1_2 = (struct scsi_target_port_descriptor *)
7159	        &tp_desc_ptr1_1->desc_list[0];
7160
7161	if (single == 0) {
7162		tpg_desc_ptr2 = (struct scsi_target_port_group_descriptor *)
7163	                &tp_desc_ptr1_2->desc_list[0];
7164		tp_desc_ptr2_1 = &tpg_desc_ptr2->descriptors[0];
7165		tp_desc_ptr2_2 = (struct scsi_target_port_descriptor *)
7166	        	&tp_desc_ptr2_1->desc_list[0];
7167        } else {
7168		tpg_desc_ptr2 = NULL;
7169		tp_desc_ptr2_1 = NULL;
7170		tp_desc_ptr2_2 = NULL;
7171	}
7172
7173	scsi_ulto4b(total_len - 4, rtg_ptr->length);
7174	if (single == 0) {
7175        	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7176			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7177				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7178				tpg_desc_ptr2->pref_state =
7179					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7180			} else {
7181				tpg_desc_ptr1->pref_state =
7182					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7183				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7184			}
7185		} else {
7186			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7187				tpg_desc_ptr1->pref_state =
7188					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7189				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7190			} else {
7191				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7192				tpg_desc_ptr2->pref_state =
7193					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7194			}
7195		}
7196	} else {
7197		tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7198	}
7199	tpg_desc_ptr1->support = 0;
7200	tpg_desc_ptr1->target_port_group[1] = 1;
7201	tpg_desc_ptr1->status = TPG_IMPLICIT;
7202	tpg_desc_ptr1->target_port_count= NUM_PORTS_PER_GRP;
7203
7204	if (single == 0) {
7205		tpg_desc_ptr2->support = 0;
7206		tpg_desc_ptr2->target_port_group[1] = 2;
7207		tpg_desc_ptr2->status = TPG_IMPLICIT;
7208		tpg_desc_ptr2->target_port_count = NUM_PORTS_PER_GRP;
7209
7210		tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7211		tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7212
7213		tp_desc_ptr2_1->relative_target_port_identifier[1] = 9;
7214		tp_desc_ptr2_2->relative_target_port_identifier[1] = 10;
7215	} else {
7216        	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7217			tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7218			tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7219		} else {
7220			tp_desc_ptr1_1->relative_target_port_identifier[1] = 9;
7221			tp_desc_ptr1_2->relative_target_port_identifier[1] = 10;
7222		}
7223	}
7224
7225	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7226	ctsio->be_move_done = ctl_config_move_done;
7227
7228	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7229			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7230			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7231			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7232			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7233
7234	ctl_datamove((union ctl_io *)ctsio);
7235	return(retval);
7236}
7237
7238int
7239ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7240{
7241	struct ctl_lun *lun;
7242	struct scsi_report_supported_opcodes *cdb;
7243	const struct ctl_cmd_entry *entry, *sentry;
7244	struct scsi_report_supported_opcodes_all *all;
7245	struct scsi_report_supported_opcodes_descr *descr;
7246	struct scsi_report_supported_opcodes_one *one;
7247	int retval;
7248	int alloc_len, total_len;
7249	int opcode, service_action, i, j, num;
7250
7251	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7252
7253	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7254	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7255
7256	retval = CTL_RETVAL_COMPLETE;
7257
7258	opcode = cdb->requested_opcode;
7259	service_action = scsi_2btoul(cdb->requested_service_action);
7260	switch (cdb->options & RSO_OPTIONS_MASK) {
7261	case RSO_OPTIONS_ALL:
7262		num = 0;
7263		for (i = 0; i < 256; i++) {
7264			entry = &ctl_cmd_table[i];
7265			if (entry->flags & CTL_CMD_FLAG_SA5) {
7266				for (j = 0; j < 32; j++) {
7267					sentry = &((const struct ctl_cmd_entry *)
7268					    entry->execute)[j];
7269					if (ctl_cmd_applicable(
7270					    lun->be_lun->lun_type, sentry))
7271						num++;
7272				}
7273			} else {
7274				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7275				    entry))
7276					num++;
7277			}
7278		}
7279		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7280		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7281		break;
7282	case RSO_OPTIONS_OC:
7283		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7284			ctl_set_invalid_field(/*ctsio*/ ctsio,
7285					      /*sks_valid*/ 1,
7286					      /*command*/ 1,
7287					      /*field*/ 2,
7288					      /*bit_valid*/ 1,
7289					      /*bit*/ 2);
7290			ctl_done((union ctl_io *)ctsio);
7291			return (CTL_RETVAL_COMPLETE);
7292		}
7293		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7294		break;
7295	case RSO_OPTIONS_OC_SA:
7296		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7297		    service_action >= 32) {
7298			ctl_set_invalid_field(/*ctsio*/ ctsio,
7299					      /*sks_valid*/ 1,
7300					      /*command*/ 1,
7301					      /*field*/ 2,
7302					      /*bit_valid*/ 1,
7303					      /*bit*/ 2);
7304			ctl_done((union ctl_io *)ctsio);
7305			return (CTL_RETVAL_COMPLETE);
7306		}
7307		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7308		break;
7309	default:
7310		ctl_set_invalid_field(/*ctsio*/ ctsio,
7311				      /*sks_valid*/ 1,
7312				      /*command*/ 1,
7313				      /*field*/ 2,
7314				      /*bit_valid*/ 1,
7315				      /*bit*/ 2);
7316		ctl_done((union ctl_io *)ctsio);
7317		return (CTL_RETVAL_COMPLETE);
7318	}
7319
7320	alloc_len = scsi_4btoul(cdb->length);
7321
7322	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7323
7324	ctsio->kern_sg_entries = 0;
7325
7326	if (total_len < alloc_len) {
7327		ctsio->residual = alloc_len - total_len;
7328		ctsio->kern_data_len = total_len;
7329		ctsio->kern_total_len = total_len;
7330	} else {
7331		ctsio->residual = 0;
7332		ctsio->kern_data_len = alloc_len;
7333		ctsio->kern_total_len = alloc_len;
7334	}
7335	ctsio->kern_data_resid = 0;
7336	ctsio->kern_rel_offset = 0;
7337
7338	switch (cdb->options & RSO_OPTIONS_MASK) {
7339	case RSO_OPTIONS_ALL:
7340		all = (struct scsi_report_supported_opcodes_all *)
7341		    ctsio->kern_data_ptr;
7342		num = 0;
7343		for (i = 0; i < 256; i++) {
7344			entry = &ctl_cmd_table[i];
7345			if (entry->flags & CTL_CMD_FLAG_SA5) {
7346				for (j = 0; j < 32; j++) {
7347					sentry = &((const struct ctl_cmd_entry *)
7348					    entry->execute)[j];
7349					if (!ctl_cmd_applicable(
7350					    lun->be_lun->lun_type, sentry))
7351						continue;
7352					descr = &all->descr[num++];
7353					descr->opcode = i;
7354					scsi_ulto2b(j, descr->service_action);
7355					descr->flags = RSO_SERVACTV;
7356					scsi_ulto2b(sentry->length,
7357					    descr->cdb_length);
7358				}
7359			} else {
7360				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7361				    entry))
7362					continue;
7363				descr = &all->descr[num++];
7364				descr->opcode = i;
7365				scsi_ulto2b(0, descr->service_action);
7366				descr->flags = 0;
7367				scsi_ulto2b(entry->length, descr->cdb_length);
7368			}
7369		}
7370		scsi_ulto4b(
7371		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7372		    all->length);
7373		break;
7374	case RSO_OPTIONS_OC:
7375		one = (struct scsi_report_supported_opcodes_one *)
7376		    ctsio->kern_data_ptr;
7377		entry = &ctl_cmd_table[opcode];
7378		goto fill_one;
7379	case RSO_OPTIONS_OC_SA:
7380		one = (struct scsi_report_supported_opcodes_one *)
7381		    ctsio->kern_data_ptr;
7382		entry = &ctl_cmd_table[opcode];
7383		entry = &((const struct ctl_cmd_entry *)
7384		    entry->execute)[service_action];
7385fill_one:
7386		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7387			one->support = 3;
7388			scsi_ulto2b(entry->length, one->cdb_length);
7389			one->cdb_usage[0] = opcode;
7390			memcpy(&one->cdb_usage[1], entry->usage,
7391			    entry->length - 1);
7392		} else
7393			one->support = 1;
7394		break;
7395	}
7396
7397	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7398	ctsio->be_move_done = ctl_config_move_done;
7399
7400	ctl_datamove((union ctl_io *)ctsio);
7401	return(retval);
7402}
7403
7404int
7405ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7406{
7407	struct ctl_lun *lun;
7408	struct scsi_report_supported_tmf *cdb;
7409	struct scsi_report_supported_tmf_data *data;
7410	int retval;
7411	int alloc_len, total_len;
7412
7413	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7414
7415	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7416	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7417
7418	retval = CTL_RETVAL_COMPLETE;
7419
7420	total_len = sizeof(struct scsi_report_supported_tmf_data);
7421	alloc_len = scsi_4btoul(cdb->length);
7422
7423	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7424
7425	ctsio->kern_sg_entries = 0;
7426
7427	if (total_len < alloc_len) {
7428		ctsio->residual = alloc_len - total_len;
7429		ctsio->kern_data_len = total_len;
7430		ctsio->kern_total_len = total_len;
7431	} else {
7432		ctsio->residual = 0;
7433		ctsio->kern_data_len = alloc_len;
7434		ctsio->kern_total_len = alloc_len;
7435	}
7436	ctsio->kern_data_resid = 0;
7437	ctsio->kern_rel_offset = 0;
7438
7439	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7440	data->byte1 |= RST_ATS | RST_LURS | RST_TRS;
7441
7442	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7443	ctsio->be_move_done = ctl_config_move_done;
7444
7445	ctl_datamove((union ctl_io *)ctsio);
7446	return (retval);
7447}
7448
7449int
7450ctl_report_timestamp(struct ctl_scsiio *ctsio)
7451{
7452	struct ctl_lun *lun;
7453	struct scsi_report_timestamp *cdb;
7454	struct scsi_report_timestamp_data *data;
7455	struct timeval tv;
7456	int64_t timestamp;
7457	int retval;
7458	int alloc_len, total_len;
7459
7460	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7461
7462	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7463	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7464
7465	retval = CTL_RETVAL_COMPLETE;
7466
7467	total_len = sizeof(struct scsi_report_timestamp_data);
7468	alloc_len = scsi_4btoul(cdb->length);
7469
7470	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7471
7472	ctsio->kern_sg_entries = 0;
7473
7474	if (total_len < alloc_len) {
7475		ctsio->residual = alloc_len - total_len;
7476		ctsio->kern_data_len = total_len;
7477		ctsio->kern_total_len = total_len;
7478	} else {
7479		ctsio->residual = 0;
7480		ctsio->kern_data_len = alloc_len;
7481		ctsio->kern_total_len = alloc_len;
7482	}
7483	ctsio->kern_data_resid = 0;
7484	ctsio->kern_rel_offset = 0;
7485
7486	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7487	scsi_ulto2b(sizeof(*data) - 2, data->length);
7488	data->origin = RTS_ORIG_OUTSIDE;
7489	getmicrotime(&tv);
7490	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7491	scsi_ulto4b(timestamp >> 16, data->timestamp);
7492	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7493
7494	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7495	ctsio->be_move_done = ctl_config_move_done;
7496
7497	ctl_datamove((union ctl_io *)ctsio);
7498	return (retval);
7499}
7500
7501int
7502ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7503{
7504	struct scsi_per_res_in *cdb;
7505	int alloc_len, total_len = 0;
7506	/* struct scsi_per_res_in_rsrv in_data; */
7507	struct ctl_lun *lun;
7508	struct ctl_softc *softc;
7509
7510	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7511
7512	softc = control_softc;
7513
7514	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7515
7516	alloc_len = scsi_2btoul(cdb->length);
7517
7518	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7519
7520retry:
7521	mtx_lock(&lun->lun_lock);
7522	switch (cdb->action) {
7523	case SPRI_RK: /* read keys */
7524		total_len = sizeof(struct scsi_per_res_in_keys) +
7525			lun->pr_key_count *
7526			sizeof(struct scsi_per_res_key);
7527		break;
7528	case SPRI_RR: /* read reservation */
7529		if (lun->flags & CTL_LUN_PR_RESERVED)
7530			total_len = sizeof(struct scsi_per_res_in_rsrv);
7531		else
7532			total_len = sizeof(struct scsi_per_res_in_header);
7533		break;
7534	case SPRI_RC: /* report capabilities */
7535		total_len = sizeof(struct scsi_per_res_cap);
7536		break;
7537	default:
7538		panic("Invalid PR type %x", cdb->action);
7539	}
7540	mtx_unlock(&lun->lun_lock);
7541
7542	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7543
7544	if (total_len < alloc_len) {
7545		ctsio->residual = alloc_len - total_len;
7546		ctsio->kern_data_len = total_len;
7547		ctsio->kern_total_len = total_len;
7548	} else {
7549		ctsio->residual = 0;
7550		ctsio->kern_data_len = alloc_len;
7551		ctsio->kern_total_len = alloc_len;
7552	}
7553
7554	ctsio->kern_data_resid = 0;
7555	ctsio->kern_rel_offset = 0;
7556	ctsio->kern_sg_entries = 0;
7557
7558	mtx_lock(&lun->lun_lock);
7559	switch (cdb->action) {
7560	case SPRI_RK: { // read keys
7561        struct scsi_per_res_in_keys *res_keys;
7562		int i, key_count;
7563
7564		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7565
7566		/*
7567		 * We had to drop the lock to allocate our buffer, which
7568		 * leaves time for someone to come in with another
7569		 * persistent reservation.  (That is unlikely, though,
7570		 * since this should be the only persistent reservation
7571		 * command active right now.)
7572		 */
7573		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7574		    (lun->pr_key_count *
7575		     sizeof(struct scsi_per_res_key)))){
7576			mtx_unlock(&lun->lun_lock);
7577			free(ctsio->kern_data_ptr, M_CTL);
7578			printf("%s: reservation length changed, retrying\n",
7579			       __func__);
7580			goto retry;
7581		}
7582
7583		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7584
7585		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7586			     lun->pr_key_count, res_keys->header.length);
7587
7588		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7589			if (!lun->per_res[i].registered)
7590				continue;
7591
7592			/*
7593			 * We used lun->pr_key_count to calculate the
7594			 * size to allocate.  If it turns out the number of
7595			 * initiators with the registered flag set is
7596			 * larger than that (i.e. they haven't been kept in
7597			 * sync), we've got a problem.
7598			 */
7599			if (key_count >= lun->pr_key_count) {
7600#ifdef NEEDTOPORT
7601				csevent_log(CSC_CTL | CSC_SHELF_SW |
7602					    CTL_PR_ERROR,
7603					    csevent_LogType_Fault,
7604					    csevent_AlertLevel_Yellow,
7605					    csevent_FRU_ShelfController,
7606					    csevent_FRU_Firmware,
7607				        csevent_FRU_Unknown,
7608					    "registered keys %d >= key "
7609					    "count %d", key_count,
7610					    lun->pr_key_count);
7611#endif
7612				key_count++;
7613				continue;
7614			}
7615			memcpy(res_keys->keys[key_count].key,
7616			       lun->per_res[i].res_key.key,
7617			       ctl_min(sizeof(res_keys->keys[key_count].key),
7618			       sizeof(lun->per_res[i].res_key)));
7619			key_count++;
7620		}
7621		break;
7622	}
7623	case SPRI_RR: { // read reservation
7624		struct scsi_per_res_in_rsrv *res;
7625		int tmp_len, header_only;
7626
7627		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7628
7629		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7630
7631		if (lun->flags & CTL_LUN_PR_RESERVED)
7632		{
7633			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7634			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7635				    res->header.length);
7636			header_only = 0;
7637		} else {
7638			tmp_len = sizeof(struct scsi_per_res_in_header);
7639			scsi_ulto4b(0, res->header.length);
7640			header_only = 1;
7641		}
7642
7643		/*
7644		 * We had to drop the lock to allocate our buffer, which
7645		 * leaves time for someone to come in with another
7646		 * persistent reservation.  (That is unlikely, though,
7647		 * since this should be the only persistent reservation
7648		 * command active right now.)
7649		 */
7650		if (tmp_len != total_len) {
7651			mtx_unlock(&lun->lun_lock);
7652			free(ctsio->kern_data_ptr, M_CTL);
7653			printf("%s: reservation status changed, retrying\n",
7654			       __func__);
7655			goto retry;
7656		}
7657
7658		/*
7659		 * No reservation held, so we're done.
7660		 */
7661		if (header_only != 0)
7662			break;
7663
7664		/*
7665		 * If the registration is an All Registrants type, the key
7666		 * is 0, since it doesn't really matter.
7667		 */
7668		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7669			memcpy(res->data.reservation,
7670			       &lun->per_res[lun->pr_res_idx].res_key,
7671			       sizeof(struct scsi_per_res_key));
7672		}
7673		res->data.scopetype = lun->res_type;
7674		break;
7675	}
7676	case SPRI_RC:     //report capabilities
7677	{
7678		struct scsi_per_res_cap *res_cap;
7679		uint16_t type_mask;
7680
7681		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7682		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7683		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7684		type_mask = SPRI_TM_WR_EX_AR |
7685			    SPRI_TM_EX_AC_RO |
7686			    SPRI_TM_WR_EX_RO |
7687			    SPRI_TM_EX_AC |
7688			    SPRI_TM_WR_EX |
7689			    SPRI_TM_EX_AC_AR;
7690		scsi_ulto2b(type_mask, res_cap->type_mask);
7691		break;
7692	}
7693	case SPRI_RS: //read full status
7694	default:
7695		/*
7696		 * This is a bug, because we just checked for this above,
7697		 * and should have returned an error.
7698		 */
7699		panic("Invalid PR type %x", cdb->action);
7700		break; /* NOTREACHED */
7701	}
7702	mtx_unlock(&lun->lun_lock);
7703
7704	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7705	ctsio->be_move_done = ctl_config_move_done;
7706
7707	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7708			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7709			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7710			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7711			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7712
7713	ctl_datamove((union ctl_io *)ctsio);
7714
7715	return (CTL_RETVAL_COMPLETE);
7716}
7717
7718/*
7719 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7720 * it should return.
7721 */
7722static int
7723ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7724		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7725		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7726		struct scsi_per_res_out_parms* param)
7727{
7728	union ctl_ha_msg persis_io;
7729	int retval, i;
7730	int isc_retval;
7731
7732	retval = 0;
7733
7734	mtx_lock(&lun->lun_lock);
7735	if (sa_res_key == 0) {
7736		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7737			/* validate scope and type */
7738			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7739			     SPR_LU_SCOPE) {
7740				mtx_unlock(&lun->lun_lock);
7741				ctl_set_invalid_field(/*ctsio*/ ctsio,
7742						      /*sks_valid*/ 1,
7743						      /*command*/ 1,
7744						      /*field*/ 2,
7745						      /*bit_valid*/ 1,
7746						      /*bit*/ 4);
7747				ctl_done((union ctl_io *)ctsio);
7748				return (1);
7749			}
7750
7751		        if (type>8 || type==2 || type==4 || type==0) {
7752				mtx_unlock(&lun->lun_lock);
7753				ctl_set_invalid_field(/*ctsio*/ ctsio,
7754       	           				      /*sks_valid*/ 1,
7755						      /*command*/ 1,
7756						      /*field*/ 2,
7757						      /*bit_valid*/ 1,
7758						      /*bit*/ 0);
7759				ctl_done((union ctl_io *)ctsio);
7760				return (1);
7761		        }
7762
7763			/* temporarily unregister this nexus */
7764			lun->per_res[residx].registered = 0;
7765
7766			/*
7767			 * Unregister everybody else and build UA for
7768			 * them
7769			 */
7770			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7771				if (lun->per_res[i].registered == 0)
7772					continue;
7773
7774				if (!persis_offset
7775				 && i <CTL_MAX_INITIATORS)
7776					lun->pending_sense[i].ua_pending |=
7777						CTL_UA_REG_PREEMPT;
7778				else if (persis_offset
7779				      && i >= persis_offset)
7780					lun->pending_sense[i-persis_offset
7781						].ua_pending |=
7782						CTL_UA_REG_PREEMPT;
7783				lun->per_res[i].registered = 0;
7784				memset(&lun->per_res[i].res_key, 0,
7785				       sizeof(struct scsi_per_res_key));
7786			}
7787			lun->per_res[residx].registered = 1;
7788			lun->pr_key_count = 1;
7789			lun->res_type = type;
7790			if (lun->res_type != SPR_TYPE_WR_EX_AR
7791			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7792				lun->pr_res_idx = residx;
7793
7794			/* send msg to other side */
7795			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7796			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7797			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7798			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7799			persis_io.pr.pr_info.res_type = type;
7800			memcpy(persis_io.pr.pr_info.sa_res_key,
7801			       param->serv_act_res_key,
7802			       sizeof(param->serv_act_res_key));
7803			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7804			     &persis_io, sizeof(persis_io), 0)) >
7805			     CTL_HA_STATUS_SUCCESS) {
7806				printf("CTL:Persis Out error returned "
7807				       "from ctl_ha_msg_send %d\n",
7808				       isc_retval);
7809			}
7810		} else {
7811			/* not all registrants */
7812			mtx_unlock(&lun->lun_lock);
7813			free(ctsio->kern_data_ptr, M_CTL);
7814			ctl_set_invalid_field(ctsio,
7815					      /*sks_valid*/ 1,
7816					      /*command*/ 0,
7817					      /*field*/ 8,
7818					      /*bit_valid*/ 0,
7819					      /*bit*/ 0);
7820			ctl_done((union ctl_io *)ctsio);
7821			return (1);
7822		}
7823	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7824		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7825		int found = 0;
7826
7827		if (res_key == sa_res_key) {
7828			/* special case */
7829			/*
7830			 * The spec implies this is not good but doesn't
7831			 * say what to do. There are two choices either
7832			 * generate a res conflict or check condition
7833			 * with illegal field in parameter data. Since
7834			 * that is what is done when the sa_res_key is
7835			 * zero I'll take that approach since this has
7836			 * to do with the sa_res_key.
7837			 */
7838			mtx_unlock(&lun->lun_lock);
7839			free(ctsio->kern_data_ptr, M_CTL);
7840			ctl_set_invalid_field(ctsio,
7841					      /*sks_valid*/ 1,
7842					      /*command*/ 0,
7843					      /*field*/ 8,
7844					      /*bit_valid*/ 0,
7845					      /*bit*/ 0);
7846			ctl_done((union ctl_io *)ctsio);
7847			return (1);
7848		}
7849
7850		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7851			if (lun->per_res[i].registered
7852			 && memcmp(param->serv_act_res_key,
7853			    lun->per_res[i].res_key.key,
7854			    sizeof(struct scsi_per_res_key)) != 0)
7855				continue;
7856
7857			found = 1;
7858			lun->per_res[i].registered = 0;
7859			memset(&lun->per_res[i].res_key, 0,
7860			       sizeof(struct scsi_per_res_key));
7861			lun->pr_key_count--;
7862
7863			if (!persis_offset
7864			 && i < CTL_MAX_INITIATORS)
7865				lun->pending_sense[i].ua_pending |=
7866					CTL_UA_REG_PREEMPT;
7867			else if (persis_offset
7868			      && i >= persis_offset)
7869				lun->pending_sense[i-persis_offset].ua_pending|=
7870					CTL_UA_REG_PREEMPT;
7871		}
7872		if (!found) {
7873			mtx_unlock(&lun->lun_lock);
7874			free(ctsio->kern_data_ptr, M_CTL);
7875			ctl_set_reservation_conflict(ctsio);
7876			ctl_done((union ctl_io *)ctsio);
7877			return (CTL_RETVAL_COMPLETE);
7878		}
7879		/* send msg to other side */
7880		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7881		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7882		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7883		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7884		persis_io.pr.pr_info.res_type = type;
7885		memcpy(persis_io.pr.pr_info.sa_res_key,
7886		       param->serv_act_res_key,
7887		       sizeof(param->serv_act_res_key));
7888		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7889		     &persis_io, sizeof(persis_io), 0)) >
7890		     CTL_HA_STATUS_SUCCESS) {
7891			printf("CTL:Persis Out error returned from "
7892			       "ctl_ha_msg_send %d\n", isc_retval);
7893		}
7894	} else {
7895		/* Reserved but not all registrants */
7896		/* sa_res_key is res holder */
7897		if (memcmp(param->serv_act_res_key,
7898                   lun->per_res[lun->pr_res_idx].res_key.key,
7899                   sizeof(struct scsi_per_res_key)) == 0) {
7900			/* validate scope and type */
7901			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7902			     SPR_LU_SCOPE) {
7903				mtx_unlock(&lun->lun_lock);
7904				ctl_set_invalid_field(/*ctsio*/ ctsio,
7905						      /*sks_valid*/ 1,
7906						      /*command*/ 1,
7907						      /*field*/ 2,
7908						      /*bit_valid*/ 1,
7909						      /*bit*/ 4);
7910				ctl_done((union ctl_io *)ctsio);
7911				return (1);
7912			}
7913
7914			if (type>8 || type==2 || type==4 || type==0) {
7915				mtx_unlock(&lun->lun_lock);
7916				ctl_set_invalid_field(/*ctsio*/ ctsio,
7917						      /*sks_valid*/ 1,
7918						      /*command*/ 1,
7919						      /*field*/ 2,
7920						      /*bit_valid*/ 1,
7921						      /*bit*/ 0);
7922				ctl_done((union ctl_io *)ctsio);
7923				return (1);
7924			}
7925
7926			/*
7927			 * Do the following:
7928			 * if sa_res_key != res_key remove all
7929			 * registrants w/sa_res_key and generate UA
7930			 * for these registrants(Registrations
7931			 * Preempted) if it wasn't an exclusive
7932			 * reservation generate UA(Reservations
7933			 * Preempted) for all other registered nexuses
7934			 * if the type has changed. Establish the new
7935			 * reservation and holder. If res_key and
7936			 * sa_res_key are the same do the above
7937			 * except don't unregister the res holder.
7938			 */
7939
7940			/*
7941			 * Temporarily unregister so it won't get
7942			 * removed or UA generated
7943			 */
7944			lun->per_res[residx].registered = 0;
7945			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7946				if (lun->per_res[i].registered == 0)
7947					continue;
7948
7949				if (memcmp(param->serv_act_res_key,
7950				    lun->per_res[i].res_key.key,
7951				    sizeof(struct scsi_per_res_key)) == 0) {
7952					lun->per_res[i].registered = 0;
7953					memset(&lun->per_res[i].res_key,
7954					       0,
7955					       sizeof(struct scsi_per_res_key));
7956					lun->pr_key_count--;
7957
7958					if (!persis_offset
7959					 && i < CTL_MAX_INITIATORS)
7960						lun->pending_sense[i
7961							].ua_pending |=
7962							CTL_UA_REG_PREEMPT;
7963					else if (persis_offset
7964					      && i >= persis_offset)
7965						lun->pending_sense[
7966						  i-persis_offset].ua_pending |=
7967						  CTL_UA_REG_PREEMPT;
7968				} else if (type != lun->res_type
7969					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7970					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7971						if (!persis_offset
7972						 && i < CTL_MAX_INITIATORS)
7973							lun->pending_sense[i
7974							].ua_pending |=
7975							CTL_UA_RES_RELEASE;
7976						else if (persis_offset
7977						      && i >= persis_offset)
7978							lun->pending_sense[
7979							i-persis_offset
7980							].ua_pending |=
7981							CTL_UA_RES_RELEASE;
7982				}
7983			}
7984			lun->per_res[residx].registered = 1;
7985			lun->res_type = type;
7986			if (lun->res_type != SPR_TYPE_WR_EX_AR
7987			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7988				lun->pr_res_idx = residx;
7989			else
7990				lun->pr_res_idx =
7991					CTL_PR_ALL_REGISTRANTS;
7992
7993			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7994			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7995			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7996			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7997			persis_io.pr.pr_info.res_type = type;
7998			memcpy(persis_io.pr.pr_info.sa_res_key,
7999			       param->serv_act_res_key,
8000			       sizeof(param->serv_act_res_key));
8001			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8002			     &persis_io, sizeof(persis_io), 0)) >
8003			     CTL_HA_STATUS_SUCCESS) {
8004				printf("CTL:Persis Out error returned "
8005				       "from ctl_ha_msg_send %d\n",
8006				       isc_retval);
8007			}
8008		} else {
8009			/*
8010			 * sa_res_key is not the res holder just
8011			 * remove registrants
8012			 */
8013			int found=0;
8014
8015			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8016				if (memcmp(param->serv_act_res_key,
8017				    lun->per_res[i].res_key.key,
8018				    sizeof(struct scsi_per_res_key)) != 0)
8019					continue;
8020
8021				found = 1;
8022				lun->per_res[i].registered = 0;
8023				memset(&lun->per_res[i].res_key, 0,
8024				       sizeof(struct scsi_per_res_key));
8025				lun->pr_key_count--;
8026
8027				if (!persis_offset
8028				 && i < CTL_MAX_INITIATORS)
8029					lun->pending_sense[i].ua_pending |=
8030						CTL_UA_REG_PREEMPT;
8031				else if (persis_offset
8032				      && i >= persis_offset)
8033					lun->pending_sense[
8034						i-persis_offset].ua_pending |=
8035						CTL_UA_REG_PREEMPT;
8036			}
8037
8038			if (!found) {
8039				mtx_unlock(&lun->lun_lock);
8040				free(ctsio->kern_data_ptr, M_CTL);
8041				ctl_set_reservation_conflict(ctsio);
8042				ctl_done((union ctl_io *)ctsio);
8043		        	return (1);
8044			}
8045			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8046			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8047			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8048			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8049			persis_io.pr.pr_info.res_type = type;
8050			memcpy(persis_io.pr.pr_info.sa_res_key,
8051			       param->serv_act_res_key,
8052			       sizeof(param->serv_act_res_key));
8053			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8054			     &persis_io, sizeof(persis_io), 0)) >
8055			     CTL_HA_STATUS_SUCCESS) {
8056				printf("CTL:Persis Out error returned "
8057				       "from ctl_ha_msg_send %d\n",
8058				isc_retval);
8059			}
8060		}
8061	}
8062
8063	lun->PRGeneration++;
8064	mtx_unlock(&lun->lun_lock);
8065
8066	return (retval);
8067}
8068
8069static void
8070ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8071{
8072	int i;
8073
8074	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8075	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8076	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8077		   msg->pr.pr_info.sa_res_key,
8078		   sizeof(struct scsi_per_res_key)) != 0) {
8079		uint64_t sa_res_key;
8080		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8081
8082		if (sa_res_key == 0) {
8083			/* temporarily unregister this nexus */
8084			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8085
8086			/*
8087			 * Unregister everybody else and build UA for
8088			 * them
8089			 */
8090			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8091				if (lun->per_res[i].registered == 0)
8092					continue;
8093
8094				if (!persis_offset
8095				 && i < CTL_MAX_INITIATORS)
8096					lun->pending_sense[i].ua_pending |=
8097						CTL_UA_REG_PREEMPT;
8098				else if (persis_offset && i >= persis_offset)
8099					lun->pending_sense[i -
8100						persis_offset].ua_pending |=
8101						CTL_UA_REG_PREEMPT;
8102				lun->per_res[i].registered = 0;
8103				memset(&lun->per_res[i].res_key, 0,
8104				       sizeof(struct scsi_per_res_key));
8105			}
8106
8107			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8108			lun->pr_key_count = 1;
8109			lun->res_type = msg->pr.pr_info.res_type;
8110			if (lun->res_type != SPR_TYPE_WR_EX_AR
8111			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8112				lun->pr_res_idx = msg->pr.pr_info.residx;
8113		} else {
8114		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8115				if (memcmp(msg->pr.pr_info.sa_res_key,
8116		                   lun->per_res[i].res_key.key,
8117		                   sizeof(struct scsi_per_res_key)) != 0)
8118					continue;
8119
8120				lun->per_res[i].registered = 0;
8121				memset(&lun->per_res[i].res_key, 0,
8122				       sizeof(struct scsi_per_res_key));
8123				lun->pr_key_count--;
8124
8125				if (!persis_offset
8126				 && i < persis_offset)
8127					lun->pending_sense[i].ua_pending |=
8128						CTL_UA_REG_PREEMPT;
8129				else if (persis_offset
8130				      && i >= persis_offset)
8131					lun->pending_sense[i -
8132						persis_offset].ua_pending |=
8133						CTL_UA_REG_PREEMPT;
8134			}
8135		}
8136	} else {
8137		/*
8138		 * Temporarily unregister so it won't get removed
8139		 * or UA generated
8140		 */
8141		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8142		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8143			if (lun->per_res[i].registered == 0)
8144				continue;
8145
8146			if (memcmp(msg->pr.pr_info.sa_res_key,
8147	                   lun->per_res[i].res_key.key,
8148	                   sizeof(struct scsi_per_res_key)) == 0) {
8149				lun->per_res[i].registered = 0;
8150				memset(&lun->per_res[i].res_key, 0,
8151				       sizeof(struct scsi_per_res_key));
8152				lun->pr_key_count--;
8153				if (!persis_offset
8154				 && i < CTL_MAX_INITIATORS)
8155					lun->pending_sense[i].ua_pending |=
8156						CTL_UA_REG_PREEMPT;
8157				else if (persis_offset
8158				      && i >= persis_offset)
8159					lun->pending_sense[i -
8160						persis_offset].ua_pending |=
8161						CTL_UA_REG_PREEMPT;
8162			} else if (msg->pr.pr_info.res_type != lun->res_type
8163				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8164				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8165					if (!persis_offset
8166					 && i < persis_offset)
8167						lun->pending_sense[i
8168							].ua_pending |=
8169							CTL_UA_RES_RELEASE;
8170					else if (persis_offset
8171					      && i >= persis_offset)
8172					lun->pending_sense[i -
8173						persis_offset].ua_pending |=
8174						CTL_UA_RES_RELEASE;
8175			}
8176		}
8177		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8178		lun->res_type = msg->pr.pr_info.res_type;
8179		if (lun->res_type != SPR_TYPE_WR_EX_AR
8180		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8181			lun->pr_res_idx = msg->pr.pr_info.residx;
8182		else
8183			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8184	}
8185	lun->PRGeneration++;
8186
8187}
8188
8189
8190int
8191ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8192{
8193	int retval;
8194	int isc_retval;
8195	u_int32_t param_len;
8196	struct scsi_per_res_out *cdb;
8197	struct ctl_lun *lun;
8198	struct scsi_per_res_out_parms* param;
8199	struct ctl_softc *softc;
8200	uint32_t residx;
8201	uint64_t res_key, sa_res_key;
8202	uint8_t type;
8203	union ctl_ha_msg persis_io;
8204	int    i;
8205
8206	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8207
8208	retval = CTL_RETVAL_COMPLETE;
8209
8210	softc = control_softc;
8211
8212	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8213	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8214
8215	/*
8216	 * We only support whole-LUN scope.  The scope & type are ignored for
8217	 * register, register and ignore existing key and clear.
8218	 * We sometimes ignore scope and type on preempts too!!
8219	 * Verify reservation type here as well.
8220	 */
8221	type = cdb->scope_type & SPR_TYPE_MASK;
8222	if ((cdb->action == SPRO_RESERVE)
8223	 || (cdb->action == SPRO_RELEASE)) {
8224		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8225			ctl_set_invalid_field(/*ctsio*/ ctsio,
8226					      /*sks_valid*/ 1,
8227					      /*command*/ 1,
8228					      /*field*/ 2,
8229					      /*bit_valid*/ 1,
8230					      /*bit*/ 4);
8231			ctl_done((union ctl_io *)ctsio);
8232			return (CTL_RETVAL_COMPLETE);
8233		}
8234
8235		if (type>8 || type==2 || type==4 || type==0) {
8236			ctl_set_invalid_field(/*ctsio*/ ctsio,
8237					      /*sks_valid*/ 1,
8238					      /*command*/ 1,
8239					      /*field*/ 2,
8240					      /*bit_valid*/ 1,
8241					      /*bit*/ 0);
8242			ctl_done((union ctl_io *)ctsio);
8243			return (CTL_RETVAL_COMPLETE);
8244		}
8245	}
8246
8247	param_len = scsi_4btoul(cdb->length);
8248
8249	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8250		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8251		ctsio->kern_data_len = param_len;
8252		ctsio->kern_total_len = param_len;
8253		ctsio->kern_data_resid = 0;
8254		ctsio->kern_rel_offset = 0;
8255		ctsio->kern_sg_entries = 0;
8256		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8257		ctsio->be_move_done = ctl_config_move_done;
8258		ctl_datamove((union ctl_io *)ctsio);
8259
8260		return (CTL_RETVAL_COMPLETE);
8261	}
8262
8263	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8264
8265	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8266	res_key = scsi_8btou64(param->res_key.key);
8267	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8268
8269	/*
8270	 * Validate the reservation key here except for SPRO_REG_IGNO
8271	 * This must be done for all other service actions
8272	 */
8273	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8274		mtx_lock(&lun->lun_lock);
8275		if (lun->per_res[residx].registered) {
8276		    if (memcmp(param->res_key.key,
8277			       lun->per_res[residx].res_key.key,
8278			       ctl_min(sizeof(param->res_key),
8279			       sizeof(lun->per_res[residx].res_key))) != 0) {
8280				/*
8281				 * The current key passed in doesn't match
8282				 * the one the initiator previously
8283				 * registered.
8284				 */
8285				mtx_unlock(&lun->lun_lock);
8286				free(ctsio->kern_data_ptr, M_CTL);
8287				ctl_set_reservation_conflict(ctsio);
8288				ctl_done((union ctl_io *)ctsio);
8289				return (CTL_RETVAL_COMPLETE);
8290			}
8291		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8292			/*
8293			 * We are not registered
8294			 */
8295			mtx_unlock(&lun->lun_lock);
8296			free(ctsio->kern_data_ptr, M_CTL);
8297			ctl_set_reservation_conflict(ctsio);
8298			ctl_done((union ctl_io *)ctsio);
8299			return (CTL_RETVAL_COMPLETE);
8300		} else if (res_key != 0) {
8301			/*
8302			 * We are not registered and trying to register but
8303			 * the register key isn't zero.
8304			 */
8305			mtx_unlock(&lun->lun_lock);
8306			free(ctsio->kern_data_ptr, M_CTL);
8307			ctl_set_reservation_conflict(ctsio);
8308			ctl_done((union ctl_io *)ctsio);
8309			return (CTL_RETVAL_COMPLETE);
8310		}
8311		mtx_unlock(&lun->lun_lock);
8312	}
8313
8314	switch (cdb->action & SPRO_ACTION_MASK) {
8315	case SPRO_REGISTER:
8316	case SPRO_REG_IGNO: {
8317
8318#if 0
8319		printf("Registration received\n");
8320#endif
8321
8322		/*
8323		 * We don't support any of these options, as we report in
8324		 * the read capabilities request (see
8325		 * ctl_persistent_reserve_in(), above).
8326		 */
8327		if ((param->flags & SPR_SPEC_I_PT)
8328		 || (param->flags & SPR_ALL_TG_PT)
8329		 || (param->flags & SPR_APTPL)) {
8330			int bit_ptr;
8331
8332			if (param->flags & SPR_APTPL)
8333				bit_ptr = 0;
8334			else if (param->flags & SPR_ALL_TG_PT)
8335				bit_ptr = 2;
8336			else /* SPR_SPEC_I_PT */
8337				bit_ptr = 3;
8338
8339			free(ctsio->kern_data_ptr, M_CTL);
8340			ctl_set_invalid_field(ctsio,
8341					      /*sks_valid*/ 1,
8342					      /*command*/ 0,
8343					      /*field*/ 20,
8344					      /*bit_valid*/ 1,
8345					      /*bit*/ bit_ptr);
8346			ctl_done((union ctl_io *)ctsio);
8347			return (CTL_RETVAL_COMPLETE);
8348		}
8349
8350		mtx_lock(&lun->lun_lock);
8351
8352		/*
8353		 * The initiator wants to clear the
8354		 * key/unregister.
8355		 */
8356		if (sa_res_key == 0) {
8357			if ((res_key == 0
8358			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8359			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8360			  && !lun->per_res[residx].registered)) {
8361				mtx_unlock(&lun->lun_lock);
8362				goto done;
8363			}
8364
8365			lun->per_res[residx].registered = 0;
8366			memset(&lun->per_res[residx].res_key,
8367			       0, sizeof(lun->per_res[residx].res_key));
8368			lun->pr_key_count--;
8369
8370			if (residx == lun->pr_res_idx) {
8371				lun->flags &= ~CTL_LUN_PR_RESERVED;
8372				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8373
8374				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8375				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8376				 && lun->pr_key_count) {
8377					/*
8378					 * If the reservation is a registrants
8379					 * only type we need to generate a UA
8380					 * for other registered inits.  The
8381					 * sense code should be RESERVATIONS
8382					 * RELEASED
8383					 */
8384
8385					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8386						if (lun->per_res[
8387						    i+persis_offset].registered
8388						    == 0)
8389							continue;
8390						lun->pending_sense[i
8391							].ua_pending |=
8392							CTL_UA_RES_RELEASE;
8393					}
8394				}
8395				lun->res_type = 0;
8396			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8397				if (lun->pr_key_count==0) {
8398					lun->flags &= ~CTL_LUN_PR_RESERVED;
8399					lun->res_type = 0;
8400					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8401				}
8402			}
8403			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8404			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8405			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8406			persis_io.pr.pr_info.residx = residx;
8407			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8408			     &persis_io, sizeof(persis_io), 0 )) >
8409			     CTL_HA_STATUS_SUCCESS) {
8410				printf("CTL:Persis Out error returned from "
8411				       "ctl_ha_msg_send %d\n", isc_retval);
8412			}
8413		} else /* sa_res_key != 0 */ {
8414
8415			/*
8416			 * If we aren't registered currently then increment
8417			 * the key count and set the registered flag.
8418			 */
8419			if (!lun->per_res[residx].registered) {
8420				lun->pr_key_count++;
8421				lun->per_res[residx].registered = 1;
8422			}
8423
8424			memcpy(&lun->per_res[residx].res_key,
8425			       param->serv_act_res_key,
8426			       ctl_min(sizeof(param->serv_act_res_key),
8427			       sizeof(lun->per_res[residx].res_key)));
8428
8429			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8430			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8431			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8432			persis_io.pr.pr_info.residx = residx;
8433			memcpy(persis_io.pr.pr_info.sa_res_key,
8434			       param->serv_act_res_key,
8435			       sizeof(param->serv_act_res_key));
8436			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8437			     &persis_io, sizeof(persis_io), 0)) >
8438			     CTL_HA_STATUS_SUCCESS) {
8439				printf("CTL:Persis Out error returned from "
8440				       "ctl_ha_msg_send %d\n", isc_retval);
8441			}
8442		}
8443		lun->PRGeneration++;
8444		mtx_unlock(&lun->lun_lock);
8445
8446		break;
8447	}
8448	case SPRO_RESERVE:
8449#if 0
8450                printf("Reserve executed type %d\n", type);
8451#endif
8452		mtx_lock(&lun->lun_lock);
8453		if (lun->flags & CTL_LUN_PR_RESERVED) {
8454			/*
8455			 * if this isn't the reservation holder and it's
8456			 * not a "all registrants" type or if the type is
8457			 * different then we have a conflict
8458			 */
8459			if ((lun->pr_res_idx != residx
8460			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8461			 || lun->res_type != type) {
8462				mtx_unlock(&lun->lun_lock);
8463				free(ctsio->kern_data_ptr, M_CTL);
8464				ctl_set_reservation_conflict(ctsio);
8465				ctl_done((union ctl_io *)ctsio);
8466				return (CTL_RETVAL_COMPLETE);
8467			}
8468			mtx_unlock(&lun->lun_lock);
8469		} else /* create a reservation */ {
8470			/*
8471			 * If it's not an "all registrants" type record
8472			 * reservation holder
8473			 */
8474			if (type != SPR_TYPE_WR_EX_AR
8475			 && type != SPR_TYPE_EX_AC_AR)
8476				lun->pr_res_idx = residx; /* Res holder */
8477			else
8478				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8479
8480			lun->flags |= CTL_LUN_PR_RESERVED;
8481			lun->res_type = type;
8482
8483			mtx_unlock(&lun->lun_lock);
8484
8485			/* send msg to other side */
8486			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8487			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8488			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8489			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8490			persis_io.pr.pr_info.res_type = type;
8491			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8492			     &persis_io, sizeof(persis_io), 0)) >
8493			     CTL_HA_STATUS_SUCCESS) {
8494				printf("CTL:Persis Out error returned from "
8495				       "ctl_ha_msg_send %d\n", isc_retval);
8496			}
8497		}
8498		break;
8499
8500	case SPRO_RELEASE:
8501		mtx_lock(&lun->lun_lock);
8502		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8503			/* No reservation exists return good status */
8504			mtx_unlock(&lun->lun_lock);
8505			goto done;
8506		}
8507		/*
8508		 * Is this nexus a reservation holder?
8509		 */
8510		if (lun->pr_res_idx != residx
8511		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8512			/*
8513			 * not a res holder return good status but
8514			 * do nothing
8515			 */
8516			mtx_unlock(&lun->lun_lock);
8517			goto done;
8518		}
8519
8520		if (lun->res_type != type) {
8521			mtx_unlock(&lun->lun_lock);
8522			free(ctsio->kern_data_ptr, M_CTL);
8523			ctl_set_illegal_pr_release(ctsio);
8524			ctl_done((union ctl_io *)ctsio);
8525			return (CTL_RETVAL_COMPLETE);
8526		}
8527
8528		/* okay to release */
8529		lun->flags &= ~CTL_LUN_PR_RESERVED;
8530		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8531		lun->res_type = 0;
8532
8533		/*
8534		 * if this isn't an exclusive access
8535		 * res generate UA for all other
8536		 * registrants.
8537		 */
8538		if (type != SPR_TYPE_EX_AC
8539		 && type != SPR_TYPE_WR_EX) {
8540			/*
8541			 * temporarily unregister so we don't generate UA
8542			 */
8543			lun->per_res[residx].registered = 0;
8544
8545			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8546				if (lun->per_res[i+persis_offset].registered
8547				    == 0)
8548					continue;
8549				lun->pending_sense[i].ua_pending |=
8550					CTL_UA_RES_RELEASE;
8551			}
8552
8553			lun->per_res[residx].registered = 1;
8554		}
8555		mtx_unlock(&lun->lun_lock);
8556		/* Send msg to other side */
8557		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8558		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8559		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8560		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8561		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8562			printf("CTL:Persis Out error returned from "
8563			       "ctl_ha_msg_send %d\n", isc_retval);
8564		}
8565		break;
8566
8567	case SPRO_CLEAR:
8568		/* send msg to other side */
8569
8570		mtx_lock(&lun->lun_lock);
8571		lun->flags &= ~CTL_LUN_PR_RESERVED;
8572		lun->res_type = 0;
8573		lun->pr_key_count = 0;
8574		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8575
8576
8577		memset(&lun->per_res[residx].res_key,
8578		       0, sizeof(lun->per_res[residx].res_key));
8579		lun->per_res[residx].registered = 0;
8580
8581		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8582			if (lun->per_res[i].registered) {
8583				if (!persis_offset && i < CTL_MAX_INITIATORS)
8584					lun->pending_sense[i].ua_pending |=
8585						CTL_UA_RES_PREEMPT;
8586				else if (persis_offset && i >= persis_offset)
8587					lun->pending_sense[i-persis_offset
8588					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8589
8590				memset(&lun->per_res[i].res_key,
8591				       0, sizeof(struct scsi_per_res_key));
8592				lun->per_res[i].registered = 0;
8593			}
8594		lun->PRGeneration++;
8595		mtx_unlock(&lun->lun_lock);
8596		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8597		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8598		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8599		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8600		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8601			printf("CTL:Persis Out error returned from "
8602			       "ctl_ha_msg_send %d\n", isc_retval);
8603		}
8604		break;
8605
8606	case SPRO_PREEMPT: {
8607		int nretval;
8608
8609		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8610					  residx, ctsio, cdb, param);
8611		if (nretval != 0)
8612			return (CTL_RETVAL_COMPLETE);
8613		break;
8614	}
8615	default:
8616		panic("Invalid PR type %x", cdb->action);
8617	}
8618
8619done:
8620	free(ctsio->kern_data_ptr, M_CTL);
8621	ctl_set_success(ctsio);
8622	ctl_done((union ctl_io *)ctsio);
8623
8624	return (retval);
8625}
8626
8627/*
8628 * This routine is for handling a message from the other SC pertaining to
8629 * persistent reserve out. All the error checking will have been done
8630 * so only perorming the action need be done here to keep the two
8631 * in sync.
8632 */
8633static void
8634ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8635{
8636	struct ctl_lun *lun;
8637	struct ctl_softc *softc;
8638	int i;
8639	uint32_t targ_lun;
8640
8641	softc = control_softc;
8642
8643	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8644	lun = softc->ctl_luns[targ_lun];
8645	mtx_lock(&lun->lun_lock);
8646	switch(msg->pr.pr_info.action) {
8647	case CTL_PR_REG_KEY:
8648		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8649			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8650			lun->pr_key_count++;
8651		}
8652		lun->PRGeneration++;
8653		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8654		       msg->pr.pr_info.sa_res_key,
8655		       sizeof(struct scsi_per_res_key));
8656		break;
8657
8658	case CTL_PR_UNREG_KEY:
8659		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8660		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8661		       0, sizeof(struct scsi_per_res_key));
8662		lun->pr_key_count--;
8663
8664		/* XXX Need to see if the reservation has been released */
8665		/* if so do we need to generate UA? */
8666		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8667			lun->flags &= ~CTL_LUN_PR_RESERVED;
8668			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8669
8670			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8671			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8672			 && lun->pr_key_count) {
8673				/*
8674				 * If the reservation is a registrants
8675				 * only type we need to generate a UA
8676				 * for other registered inits.  The
8677				 * sense code should be RESERVATIONS
8678				 * RELEASED
8679				 */
8680
8681				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8682					if (lun->per_res[i+
8683					    persis_offset].registered == 0)
8684						continue;
8685
8686					lun->pending_sense[i
8687						].ua_pending |=
8688						CTL_UA_RES_RELEASE;
8689				}
8690			}
8691			lun->res_type = 0;
8692		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8693			if (lun->pr_key_count==0) {
8694				lun->flags &= ~CTL_LUN_PR_RESERVED;
8695				lun->res_type = 0;
8696				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8697			}
8698		}
8699		lun->PRGeneration++;
8700		break;
8701
8702	case CTL_PR_RESERVE:
8703		lun->flags |= CTL_LUN_PR_RESERVED;
8704		lun->res_type = msg->pr.pr_info.res_type;
8705		lun->pr_res_idx = msg->pr.pr_info.residx;
8706
8707		break;
8708
8709	case CTL_PR_RELEASE:
8710		/*
8711		 * if this isn't an exclusive access res generate UA for all
8712		 * other registrants.
8713		 */
8714		if (lun->res_type != SPR_TYPE_EX_AC
8715		 && lun->res_type != SPR_TYPE_WR_EX) {
8716			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8717				if (lun->per_res[i+persis_offset].registered)
8718					lun->pending_sense[i].ua_pending |=
8719						CTL_UA_RES_RELEASE;
8720		}
8721
8722		lun->flags &= ~CTL_LUN_PR_RESERVED;
8723		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8724		lun->res_type = 0;
8725		break;
8726
8727	case CTL_PR_PREEMPT:
8728		ctl_pro_preempt_other(lun, msg);
8729		break;
8730	case CTL_PR_CLEAR:
8731		lun->flags &= ~CTL_LUN_PR_RESERVED;
8732		lun->res_type = 0;
8733		lun->pr_key_count = 0;
8734		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8735
8736		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8737			if (lun->per_res[i].registered == 0)
8738				continue;
8739			if (!persis_offset
8740			 && i < CTL_MAX_INITIATORS)
8741				lun->pending_sense[i].ua_pending |=
8742					CTL_UA_RES_PREEMPT;
8743			else if (persis_offset
8744			      && i >= persis_offset)
8745   				lun->pending_sense[i-persis_offset].ua_pending|=
8746					CTL_UA_RES_PREEMPT;
8747			memset(&lun->per_res[i].res_key, 0,
8748			       sizeof(struct scsi_per_res_key));
8749			lun->per_res[i].registered = 0;
8750		}
8751		lun->PRGeneration++;
8752		break;
8753	}
8754
8755	mtx_unlock(&lun->lun_lock);
8756}
8757
8758int
8759ctl_read_write(struct ctl_scsiio *ctsio)
8760{
8761	struct ctl_lun *lun;
8762	struct ctl_lba_len_flags *lbalen;
8763	uint64_t lba;
8764	uint32_t num_blocks;
8765	int fua, dpo;
8766	int retval;
8767	int isread;
8768
8769	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8770
8771	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8772
8773	fua = 0;
8774	dpo = 0;
8775
8776	retval = CTL_RETVAL_COMPLETE;
8777
8778	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8779	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8780	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8781		uint32_t residx;
8782
8783		/*
8784		 * XXX KDM need a lock here.
8785		 */
8786		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8787		if ((lun->res_type == SPR_TYPE_EX_AC
8788		  && residx != lun->pr_res_idx)
8789		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8790		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8791		  && !lun->per_res[residx].registered)) {
8792			ctl_set_reservation_conflict(ctsio);
8793			ctl_done((union ctl_io *)ctsio);
8794			return (CTL_RETVAL_COMPLETE);
8795	        }
8796	}
8797
8798	switch (ctsio->cdb[0]) {
8799	case READ_6:
8800	case WRITE_6: {
8801		struct scsi_rw_6 *cdb;
8802
8803		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8804
8805		lba = scsi_3btoul(cdb->addr);
8806		/* only 5 bits are valid in the most significant address byte */
8807		lba &= 0x1fffff;
8808		num_blocks = cdb->length;
8809		/*
8810		 * This is correct according to SBC-2.
8811		 */
8812		if (num_blocks == 0)
8813			num_blocks = 256;
8814		break;
8815	}
8816	case READ_10:
8817	case WRITE_10: {
8818		struct scsi_rw_10 *cdb;
8819
8820		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8821
8822		if (cdb->byte2 & SRW10_FUA)
8823			fua = 1;
8824		if (cdb->byte2 & SRW10_DPO)
8825			dpo = 1;
8826
8827		lba = scsi_4btoul(cdb->addr);
8828		num_blocks = scsi_2btoul(cdb->length);
8829		break;
8830	}
8831	case WRITE_VERIFY_10: {
8832		struct scsi_write_verify_10 *cdb;
8833
8834		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8835
8836		/*
8837		 * XXX KDM we should do actual write verify support at some
8838		 * point.  This is obviously fake, we're just translating
8839		 * things to a write.  So we don't even bother checking the
8840		 * BYTCHK field, since we don't do any verification.  If
8841		 * the user asks for it, we'll just pretend we did it.
8842		 */
8843		if (cdb->byte2 & SWV_DPO)
8844			dpo = 1;
8845
8846		lba = scsi_4btoul(cdb->addr);
8847		num_blocks = scsi_2btoul(cdb->length);
8848		break;
8849	}
8850	case READ_12:
8851	case WRITE_12: {
8852		struct scsi_rw_12 *cdb;
8853
8854		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8855
8856		if (cdb->byte2 & SRW12_FUA)
8857			fua = 1;
8858		if (cdb->byte2 & SRW12_DPO)
8859			dpo = 1;
8860		lba = scsi_4btoul(cdb->addr);
8861		num_blocks = scsi_4btoul(cdb->length);
8862		break;
8863	}
8864	case WRITE_VERIFY_12: {
8865		struct scsi_write_verify_12 *cdb;
8866
8867		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8868
8869		if (cdb->byte2 & SWV_DPO)
8870			dpo = 1;
8871
8872		lba = scsi_4btoul(cdb->addr);
8873		num_blocks = scsi_4btoul(cdb->length);
8874
8875		break;
8876	}
8877	case READ_16:
8878	case WRITE_16: {
8879		struct scsi_rw_16 *cdb;
8880
8881		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8882
8883		if (cdb->byte2 & SRW12_FUA)
8884			fua = 1;
8885		if (cdb->byte2 & SRW12_DPO)
8886			dpo = 1;
8887
8888		lba = scsi_8btou64(cdb->addr);
8889		num_blocks = scsi_4btoul(cdb->length);
8890		break;
8891	}
8892	case WRITE_VERIFY_16: {
8893		struct scsi_write_verify_16 *cdb;
8894
8895		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8896
8897		if (cdb->byte2 & SWV_DPO)
8898			dpo = 1;
8899
8900		lba = scsi_8btou64(cdb->addr);
8901		num_blocks = scsi_4btoul(cdb->length);
8902		break;
8903	}
8904	default:
8905		/*
8906		 * We got a command we don't support.  This shouldn't
8907		 * happen, commands should be filtered out above us.
8908		 */
8909		ctl_set_invalid_opcode(ctsio);
8910		ctl_done((union ctl_io *)ctsio);
8911
8912		return (CTL_RETVAL_COMPLETE);
8913		break; /* NOTREACHED */
8914	}
8915
8916	/*
8917	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8918	 * interesting for us, but if RAIDCore is in write-back mode,
8919	 * getting it to do write-through for a particular transaction may
8920	 * not be possible.
8921	 */
8922
8923	/*
8924	 * The first check is to make sure we're in bounds, the second
8925	 * check is to catch wrap-around problems.  If the lba + num blocks
8926	 * is less than the lba, then we've wrapped around and the block
8927	 * range is invalid anyway.
8928	 */
8929	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8930	 || ((lba + num_blocks) < lba)) {
8931		ctl_set_lba_out_of_range(ctsio);
8932		ctl_done((union ctl_io *)ctsio);
8933		return (CTL_RETVAL_COMPLETE);
8934	}
8935
8936	/*
8937	 * According to SBC-3, a transfer length of 0 is not an error.
8938	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8939	 * translates to 256 blocks for those commands.
8940	 */
8941	if (num_blocks == 0) {
8942		ctl_set_success(ctsio);
8943		ctl_done((union ctl_io *)ctsio);
8944		return (CTL_RETVAL_COMPLETE);
8945	}
8946
8947	lbalen = (struct ctl_lba_len_flags *)
8948	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8949	lbalen->lba = lba;
8950	lbalen->len = num_blocks;
8951	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
8952
8953	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8954	ctsio->kern_rel_offset = 0;
8955
8956	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8957
8958	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8959
8960	return (retval);
8961}
8962
8963static int
8964ctl_cnw_cont(union ctl_io *io)
8965{
8966	struct ctl_scsiio *ctsio;
8967	struct ctl_lun *lun;
8968	struct ctl_lba_len_flags *lbalen;
8969	int retval;
8970
8971	ctsio = &io->scsiio;
8972	ctsio->io_hdr.status = CTL_STATUS_NONE;
8973	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8974	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8975	lbalen = (struct ctl_lba_len_flags *)
8976	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8977	lbalen->flags = CTL_LLF_WRITE;
8978
8979	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8980	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8981	return (retval);
8982}
8983
8984int
8985ctl_cnw(struct ctl_scsiio *ctsio)
8986{
8987	struct ctl_lun *lun;
8988	struct ctl_lba_len_flags *lbalen;
8989	uint64_t lba;
8990	uint32_t num_blocks;
8991	int fua, dpo;
8992	int retval;
8993
8994	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8995
8996	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8997
8998	fua = 0;
8999	dpo = 0;
9000
9001	retval = CTL_RETVAL_COMPLETE;
9002
9003	switch (ctsio->cdb[0]) {
9004	case COMPARE_AND_WRITE: {
9005		struct scsi_compare_and_write *cdb;
9006
9007		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9008
9009		if (cdb->byte2 & SRW10_FUA)
9010			fua = 1;
9011		if (cdb->byte2 & SRW10_DPO)
9012			dpo = 1;
9013		lba = scsi_8btou64(cdb->addr);
9014		num_blocks = cdb->length;
9015		break;
9016	}
9017	default:
9018		/*
9019		 * We got a command we don't support.  This shouldn't
9020		 * happen, commands should be filtered out above us.
9021		 */
9022		ctl_set_invalid_opcode(ctsio);
9023		ctl_done((union ctl_io *)ctsio);
9024
9025		return (CTL_RETVAL_COMPLETE);
9026		break; /* NOTREACHED */
9027	}
9028
9029	/*
9030	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9031	 * interesting for us, but if RAIDCore is in write-back mode,
9032	 * getting it to do write-through for a particular transaction may
9033	 * not be possible.
9034	 */
9035
9036	/*
9037	 * The first check is to make sure we're in bounds, the second
9038	 * check is to catch wrap-around problems.  If the lba + num blocks
9039	 * is less than the lba, then we've wrapped around and the block
9040	 * range is invalid anyway.
9041	 */
9042	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9043	 || ((lba + num_blocks) < lba)) {
9044		ctl_set_lba_out_of_range(ctsio);
9045		ctl_done((union ctl_io *)ctsio);
9046		return (CTL_RETVAL_COMPLETE);
9047	}
9048
9049	/*
9050	 * According to SBC-3, a transfer length of 0 is not an error.
9051	 */
9052	if (num_blocks == 0) {
9053		ctl_set_success(ctsio);
9054		ctl_done((union ctl_io *)ctsio);
9055		return (CTL_RETVAL_COMPLETE);
9056	}
9057
9058	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9059	ctsio->kern_rel_offset = 0;
9060
9061	/*
9062	 * Set the IO_CONT flag, so that if this I/O gets passed to
9063	 * ctl_data_submit_done(), it'll get passed back to
9064	 * ctl_ctl_cnw_cont() for further processing.
9065	 */
9066	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9067	ctsio->io_cont = ctl_cnw_cont;
9068
9069	lbalen = (struct ctl_lba_len_flags *)
9070	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9071	lbalen->lba = lba;
9072	lbalen->len = num_blocks;
9073	lbalen->flags = CTL_LLF_COMPARE;
9074
9075	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9076	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9077	return (retval);
9078}
9079
9080int
9081ctl_verify(struct ctl_scsiio *ctsio)
9082{
9083	struct ctl_lun *lun;
9084	struct ctl_lba_len_flags *lbalen;
9085	uint64_t lba;
9086	uint32_t num_blocks;
9087	int bytchk, dpo;
9088	int retval;
9089
9090	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9091
9092	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9093
9094	bytchk = 0;
9095	dpo = 0;
9096	retval = CTL_RETVAL_COMPLETE;
9097
9098	switch (ctsio->cdb[0]) {
9099	case VERIFY_10: {
9100		struct scsi_verify_10 *cdb;
9101
9102		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9103		if (cdb->byte2 & SVFY_BYTCHK)
9104			bytchk = 1;
9105		if (cdb->byte2 & SVFY_DPO)
9106			dpo = 1;
9107		lba = scsi_4btoul(cdb->addr);
9108		num_blocks = scsi_2btoul(cdb->length);
9109		break;
9110	}
9111	case VERIFY_12: {
9112		struct scsi_verify_12 *cdb;
9113
9114		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9115		if (cdb->byte2 & SVFY_BYTCHK)
9116			bytchk = 1;
9117		if (cdb->byte2 & SVFY_DPO)
9118			dpo = 1;
9119		lba = scsi_4btoul(cdb->addr);
9120		num_blocks = scsi_4btoul(cdb->length);
9121		break;
9122	}
9123	case VERIFY_16: {
9124		struct scsi_rw_16 *cdb;
9125
9126		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9127		if (cdb->byte2 & SVFY_BYTCHK)
9128			bytchk = 1;
9129		if (cdb->byte2 & SVFY_DPO)
9130			dpo = 1;
9131		lba = scsi_8btou64(cdb->addr);
9132		num_blocks = scsi_4btoul(cdb->length);
9133		break;
9134	}
9135	default:
9136		/*
9137		 * We got a command we don't support.  This shouldn't
9138		 * happen, commands should be filtered out above us.
9139		 */
9140		ctl_set_invalid_opcode(ctsio);
9141		ctl_done((union ctl_io *)ctsio);
9142		return (CTL_RETVAL_COMPLETE);
9143	}
9144
9145	/*
9146	 * The first check is to make sure we're in bounds, the second
9147	 * check is to catch wrap-around problems.  If the lba + num blocks
9148	 * is less than the lba, then we've wrapped around and the block
9149	 * range is invalid anyway.
9150	 */
9151	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9152	 || ((lba + num_blocks) < lba)) {
9153		ctl_set_lba_out_of_range(ctsio);
9154		ctl_done((union ctl_io *)ctsio);
9155		return (CTL_RETVAL_COMPLETE);
9156	}
9157
9158	/*
9159	 * According to SBC-3, a transfer length of 0 is not an error.
9160	 */
9161	if (num_blocks == 0) {
9162		ctl_set_success(ctsio);
9163		ctl_done((union ctl_io *)ctsio);
9164		return (CTL_RETVAL_COMPLETE);
9165	}
9166
9167	lbalen = (struct ctl_lba_len_flags *)
9168	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9169	lbalen->lba = lba;
9170	lbalen->len = num_blocks;
9171	if (bytchk) {
9172		lbalen->flags = CTL_LLF_COMPARE;
9173		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9174	} else {
9175		lbalen->flags = CTL_LLF_VERIFY;
9176		ctsio->kern_total_len = 0;
9177	}
9178	ctsio->kern_rel_offset = 0;
9179
9180	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9181	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9182	return (retval);
9183}
9184
9185int
9186ctl_report_luns(struct ctl_scsiio *ctsio)
9187{
9188	struct scsi_report_luns *cdb;
9189	struct scsi_report_luns_data *lun_data;
9190	struct ctl_lun *lun, *request_lun;
9191	int num_luns, retval;
9192	uint32_t alloc_len, lun_datalen;
9193	int num_filled, well_known;
9194	uint32_t initidx, targ_lun_id, lun_id;
9195
9196	retval = CTL_RETVAL_COMPLETE;
9197	well_known = 0;
9198
9199	cdb = (struct scsi_report_luns *)ctsio->cdb;
9200
9201	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9202
9203	mtx_lock(&control_softc->ctl_lock);
9204	num_luns = control_softc->num_luns;
9205	mtx_unlock(&control_softc->ctl_lock);
9206
9207	switch (cdb->select_report) {
9208	case RPL_REPORT_DEFAULT:
9209	case RPL_REPORT_ALL:
9210		break;
9211	case RPL_REPORT_WELLKNOWN:
9212		well_known = 1;
9213		num_luns = 0;
9214		break;
9215	default:
9216		ctl_set_invalid_field(ctsio,
9217				      /*sks_valid*/ 1,
9218				      /*command*/ 1,
9219				      /*field*/ 2,
9220				      /*bit_valid*/ 0,
9221				      /*bit*/ 0);
9222		ctl_done((union ctl_io *)ctsio);
9223		return (retval);
9224		break; /* NOTREACHED */
9225	}
9226
9227	alloc_len = scsi_4btoul(cdb->length);
9228	/*
9229	 * The initiator has to allocate at least 16 bytes for this request,
9230	 * so he can at least get the header and the first LUN.  Otherwise
9231	 * we reject the request (per SPC-3 rev 14, section 6.21).
9232	 */
9233	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9234	    sizeof(struct scsi_report_luns_lundata))) {
9235		ctl_set_invalid_field(ctsio,
9236				      /*sks_valid*/ 1,
9237				      /*command*/ 1,
9238				      /*field*/ 6,
9239				      /*bit_valid*/ 0,
9240				      /*bit*/ 0);
9241		ctl_done((union ctl_io *)ctsio);
9242		return (retval);
9243	}
9244
9245	request_lun = (struct ctl_lun *)
9246		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9247
9248	lun_datalen = sizeof(*lun_data) +
9249		(num_luns * sizeof(struct scsi_report_luns_lundata));
9250
9251	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9252	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9253	ctsio->kern_sg_entries = 0;
9254
9255	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9256
9257	mtx_lock(&control_softc->ctl_lock);
9258	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9259		lun_id = targ_lun_id;
9260		if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
9261			lun_id = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, lun_id);
9262		if (lun_id >= CTL_MAX_LUNS)
9263			continue;
9264		lun = control_softc->ctl_luns[lun_id];
9265		if (lun == NULL)
9266			continue;
9267
9268		if (targ_lun_id <= 0xff) {
9269			/*
9270			 * Peripheral addressing method, bus number 0.
9271			 */
9272			lun_data->luns[num_filled].lundata[0] =
9273				RPL_LUNDATA_ATYP_PERIPH;
9274			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9275			num_filled++;
9276		} else if (targ_lun_id <= 0x3fff) {
9277			/*
9278			 * Flat addressing method.
9279			 */
9280			lun_data->luns[num_filled].lundata[0] =
9281				RPL_LUNDATA_ATYP_FLAT |
9282				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9283#ifdef OLDCTLHEADERS
9284				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9285				(targ_lun_id & SRLD_BUS_LUN_MASK);
9286#endif
9287			lun_data->luns[num_filled].lundata[1] =
9288#ifdef OLDCTLHEADERS
9289				targ_lun_id >> SRLD_BUS_LUN_BITS;
9290#endif
9291				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9292			num_filled++;
9293		} else {
9294			printf("ctl_report_luns: bogus LUN number %jd, "
9295			       "skipping\n", (intmax_t)targ_lun_id);
9296		}
9297		/*
9298		 * According to SPC-3, rev 14 section 6.21:
9299		 *
9300		 * "The execution of a REPORT LUNS command to any valid and
9301		 * installed logical unit shall clear the REPORTED LUNS DATA
9302		 * HAS CHANGED unit attention condition for all logical
9303		 * units of that target with respect to the requesting
9304		 * initiator. A valid and installed logical unit is one
9305		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9306		 * INQUIRY data (see 6.4.2)."
9307		 *
9308		 * If request_lun is NULL, the LUN this report luns command
9309		 * was issued to is either disabled or doesn't exist. In that
9310		 * case, we shouldn't clear any pending lun change unit
9311		 * attention.
9312		 */
9313		if (request_lun != NULL) {
9314			mtx_lock(&lun->lun_lock);
9315			lun->pending_sense[initidx].ua_pending &=
9316				~CTL_UA_LUN_CHANGE;
9317			mtx_unlock(&lun->lun_lock);
9318		}
9319	}
9320	mtx_unlock(&control_softc->ctl_lock);
9321
9322	/*
9323	 * It's quite possible that we've returned fewer LUNs than we allocated
9324	 * space for.  Trim it.
9325	 */
9326	lun_datalen = sizeof(*lun_data) +
9327		(num_filled * sizeof(struct scsi_report_luns_lundata));
9328
9329	if (lun_datalen < alloc_len) {
9330		ctsio->residual = alloc_len - lun_datalen;
9331		ctsio->kern_data_len = lun_datalen;
9332		ctsio->kern_total_len = lun_datalen;
9333	} else {
9334		ctsio->residual = 0;
9335		ctsio->kern_data_len = alloc_len;
9336		ctsio->kern_total_len = alloc_len;
9337	}
9338	ctsio->kern_data_resid = 0;
9339	ctsio->kern_rel_offset = 0;
9340	ctsio->kern_sg_entries = 0;
9341
9342	/*
9343	 * We set this to the actual data length, regardless of how much
9344	 * space we actually have to return results.  If the user looks at
9345	 * this value, he'll know whether or not he allocated enough space
9346	 * and reissue the command if necessary.  We don't support well
9347	 * known logical units, so if the user asks for that, return none.
9348	 */
9349	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9350
9351	/*
9352	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9353	 * this request.
9354	 */
9355	ctsio->scsi_status = SCSI_STATUS_OK;
9356
9357	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9358	ctsio->be_move_done = ctl_config_move_done;
9359	ctl_datamove((union ctl_io *)ctsio);
9360
9361	return (retval);
9362}
9363
9364int
9365ctl_request_sense(struct ctl_scsiio *ctsio)
9366{
9367	struct scsi_request_sense *cdb;
9368	struct scsi_sense_data *sense_ptr;
9369	struct ctl_lun *lun;
9370	uint32_t initidx;
9371	int have_error;
9372	scsi_sense_data_type sense_format;
9373
9374	cdb = (struct scsi_request_sense *)ctsio->cdb;
9375
9376	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9377
9378	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9379
9380	/*
9381	 * Determine which sense format the user wants.
9382	 */
9383	if (cdb->byte2 & SRS_DESC)
9384		sense_format = SSD_TYPE_DESC;
9385	else
9386		sense_format = SSD_TYPE_FIXED;
9387
9388	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9389	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9390	ctsio->kern_sg_entries = 0;
9391
9392	/*
9393	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9394	 * larger than the largest allowed value for the length field in the
9395	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9396	 */
9397	ctsio->residual = 0;
9398	ctsio->kern_data_len = cdb->length;
9399	ctsio->kern_total_len = cdb->length;
9400
9401	ctsio->kern_data_resid = 0;
9402	ctsio->kern_rel_offset = 0;
9403	ctsio->kern_sg_entries = 0;
9404
9405	/*
9406	 * If we don't have a LUN, we don't have any pending sense.
9407	 */
9408	if (lun == NULL)
9409		goto no_sense;
9410
9411	have_error = 0;
9412	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9413	/*
9414	 * Check for pending sense, and then for pending unit attentions.
9415	 * Pending sense gets returned first, then pending unit attentions.
9416	 */
9417	mtx_lock(&lun->lun_lock);
9418	if (ctl_is_set(lun->have_ca, initidx)) {
9419		scsi_sense_data_type stored_format;
9420
9421		/*
9422		 * Check to see which sense format was used for the stored
9423		 * sense data.
9424		 */
9425		stored_format = scsi_sense_type(
9426		    &lun->pending_sense[initidx].sense);
9427
9428		/*
9429		 * If the user requested a different sense format than the
9430		 * one we stored, then we need to convert it to the other
9431		 * format.  If we're going from descriptor to fixed format
9432		 * sense data, we may lose things in translation, depending
9433		 * on what options were used.
9434		 *
9435		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9436		 * for some reason we'll just copy it out as-is.
9437		 */
9438		if ((stored_format == SSD_TYPE_FIXED)
9439		 && (sense_format == SSD_TYPE_DESC))
9440			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9441			    &lun->pending_sense[initidx].sense,
9442			    (struct scsi_sense_data_desc *)sense_ptr);
9443		else if ((stored_format == SSD_TYPE_DESC)
9444		      && (sense_format == SSD_TYPE_FIXED))
9445			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9446			    &lun->pending_sense[initidx].sense,
9447			    (struct scsi_sense_data_fixed *)sense_ptr);
9448		else
9449			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9450			       ctl_min(sizeof(*sense_ptr),
9451			       sizeof(lun->pending_sense[initidx].sense)));
9452
9453		ctl_clear_mask(lun->have_ca, initidx);
9454		have_error = 1;
9455	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9456		ctl_ua_type ua_type;
9457
9458		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9459				       sense_ptr, sense_format);
9460		if (ua_type != CTL_UA_NONE) {
9461			have_error = 1;
9462			/* We're reporting this UA, so clear it */
9463			lun->pending_sense[initidx].ua_pending &= ~ua_type;
9464		}
9465	}
9466	mtx_unlock(&lun->lun_lock);
9467
9468	/*
9469	 * We already have a pending error, return it.
9470	 */
9471	if (have_error != 0) {
9472		/*
9473		 * We report the SCSI status as OK, since the status of the
9474		 * request sense command itself is OK.
9475		 */
9476		ctsio->scsi_status = SCSI_STATUS_OK;
9477
9478		/*
9479		 * We report 0 for the sense length, because we aren't doing
9480		 * autosense in this case.  We're reporting sense as
9481		 * parameter data.
9482		 */
9483		ctsio->sense_len = 0;
9484		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9485		ctsio->be_move_done = ctl_config_move_done;
9486		ctl_datamove((union ctl_io *)ctsio);
9487
9488		return (CTL_RETVAL_COMPLETE);
9489	}
9490
9491no_sense:
9492
9493	/*
9494	 * No sense information to report, so we report that everything is
9495	 * okay.
9496	 */
9497	ctl_set_sense_data(sense_ptr,
9498			   lun,
9499			   sense_format,
9500			   /*current_error*/ 1,
9501			   /*sense_key*/ SSD_KEY_NO_SENSE,
9502			   /*asc*/ 0x00,
9503			   /*ascq*/ 0x00,
9504			   SSD_ELEM_NONE);
9505
9506	ctsio->scsi_status = SCSI_STATUS_OK;
9507
9508	/*
9509	 * We report 0 for the sense length, because we aren't doing
9510	 * autosense in this case.  We're reporting sense as parameter data.
9511	 */
9512	ctsio->sense_len = 0;
9513	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9514	ctsio->be_move_done = ctl_config_move_done;
9515	ctl_datamove((union ctl_io *)ctsio);
9516
9517	return (CTL_RETVAL_COMPLETE);
9518}
9519
9520int
9521ctl_tur(struct ctl_scsiio *ctsio)
9522{
9523	struct ctl_lun *lun;
9524
9525	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9526
9527	CTL_DEBUG_PRINT(("ctl_tur\n"));
9528
9529	if (lun == NULL)
9530		return (EINVAL);
9531
9532	ctsio->scsi_status = SCSI_STATUS_OK;
9533	ctsio->io_hdr.status = CTL_SUCCESS;
9534
9535	ctl_done((union ctl_io *)ctsio);
9536
9537	return (CTL_RETVAL_COMPLETE);
9538}
9539
9540#ifdef notyet
9541static int
9542ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9543{
9544
9545}
9546#endif
9547
9548static int
9549ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9550{
9551	struct scsi_vpd_supported_pages *pages;
9552	int sup_page_size;
9553	struct ctl_lun *lun;
9554
9555	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9556
9557	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9558	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9559	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9560	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9561	ctsio->kern_sg_entries = 0;
9562
9563	if (sup_page_size < alloc_len) {
9564		ctsio->residual = alloc_len - sup_page_size;
9565		ctsio->kern_data_len = sup_page_size;
9566		ctsio->kern_total_len = sup_page_size;
9567	} else {
9568		ctsio->residual = 0;
9569		ctsio->kern_data_len = alloc_len;
9570		ctsio->kern_total_len = alloc_len;
9571	}
9572	ctsio->kern_data_resid = 0;
9573	ctsio->kern_rel_offset = 0;
9574	ctsio->kern_sg_entries = 0;
9575
9576	/*
9577	 * The control device is always connected.  The disk device, on the
9578	 * other hand, may not be online all the time.  Need to change this
9579	 * to figure out whether the disk device is actually online or not.
9580	 */
9581	if (lun != NULL)
9582		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9583				lun->be_lun->lun_type;
9584	else
9585		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9586
9587	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9588	/* Supported VPD pages */
9589	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9590	/* Serial Number */
9591	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9592	/* Device Identification */
9593	pages->page_list[2] = SVPD_DEVICE_ID;
9594	/* Block limits */
9595	pages->page_list[3] = SVPD_BLOCK_LIMITS;
9596	/* Logical Block Provisioning */
9597	pages->page_list[4] = SVPD_LBP;
9598
9599	ctsio->scsi_status = SCSI_STATUS_OK;
9600
9601	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9602	ctsio->be_move_done = ctl_config_move_done;
9603	ctl_datamove((union ctl_io *)ctsio);
9604
9605	return (CTL_RETVAL_COMPLETE);
9606}
9607
9608static int
9609ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9610{
9611	struct scsi_vpd_unit_serial_number *sn_ptr;
9612	struct ctl_lun *lun;
9613
9614	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9615
9616	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9617	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9618	ctsio->kern_sg_entries = 0;
9619
9620	if (sizeof(*sn_ptr) < alloc_len) {
9621		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9622		ctsio->kern_data_len = sizeof(*sn_ptr);
9623		ctsio->kern_total_len = sizeof(*sn_ptr);
9624	} else {
9625		ctsio->residual = 0;
9626		ctsio->kern_data_len = alloc_len;
9627		ctsio->kern_total_len = alloc_len;
9628	}
9629	ctsio->kern_data_resid = 0;
9630	ctsio->kern_rel_offset = 0;
9631	ctsio->kern_sg_entries = 0;
9632
9633	/*
9634	 * The control device is always connected.  The disk device, on the
9635	 * other hand, may not be online all the time.  Need to change this
9636	 * to figure out whether the disk device is actually online or not.
9637	 */
9638	if (lun != NULL)
9639		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9640				  lun->be_lun->lun_type;
9641	else
9642		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9643
9644	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9645	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9646	/*
9647	 * If we don't have a LUN, we just leave the serial number as
9648	 * all spaces.
9649	 */
9650	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9651	if (lun != NULL) {
9652		strncpy((char *)sn_ptr->serial_num,
9653			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9654	}
9655	ctsio->scsi_status = SCSI_STATUS_OK;
9656
9657	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9658	ctsio->be_move_done = ctl_config_move_done;
9659	ctl_datamove((union ctl_io *)ctsio);
9660
9661	return (CTL_RETVAL_COMPLETE);
9662}
9663
9664
9665static int
9666ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9667{
9668	struct scsi_vpd_device_id *devid_ptr;
9669	struct scsi_vpd_id_descriptor *desc;
9670	struct ctl_softc *ctl_softc;
9671	struct ctl_lun *lun;
9672	struct ctl_port *port;
9673	int data_len;
9674	uint8_t proto;
9675
9676	ctl_softc = control_softc;
9677
9678	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9679	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9680
9681	data_len = sizeof(struct scsi_vpd_device_id) +
9682	    sizeof(struct scsi_vpd_id_descriptor) +
9683		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9684	    sizeof(struct scsi_vpd_id_descriptor) +
9685		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9686	if (lun && lun->lun_devid)
9687		data_len += lun->lun_devid->len;
9688	if (port->port_devid)
9689		data_len += port->port_devid->len;
9690	if (port->target_devid)
9691		data_len += port->target_devid->len;
9692
9693	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9694	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9695	ctsio->kern_sg_entries = 0;
9696
9697	if (data_len < alloc_len) {
9698		ctsio->residual = alloc_len - data_len;
9699		ctsio->kern_data_len = data_len;
9700		ctsio->kern_total_len = data_len;
9701	} else {
9702		ctsio->residual = 0;
9703		ctsio->kern_data_len = alloc_len;
9704		ctsio->kern_total_len = alloc_len;
9705	}
9706	ctsio->kern_data_resid = 0;
9707	ctsio->kern_rel_offset = 0;
9708	ctsio->kern_sg_entries = 0;
9709
9710	/*
9711	 * The control device is always connected.  The disk device, on the
9712	 * other hand, may not be online all the time.
9713	 */
9714	if (lun != NULL)
9715		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9716				     lun->be_lun->lun_type;
9717	else
9718		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9719	devid_ptr->page_code = SVPD_DEVICE_ID;
9720	scsi_ulto2b(data_len - 4, devid_ptr->length);
9721
9722	if (port->port_type == CTL_PORT_FC)
9723		proto = SCSI_PROTO_FC << 4;
9724	else if (port->port_type == CTL_PORT_ISCSI)
9725		proto = SCSI_PROTO_ISCSI << 4;
9726	else
9727		proto = SCSI_PROTO_SPI << 4;
9728	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9729
9730	/*
9731	 * We're using a LUN association here.  i.e., this device ID is a
9732	 * per-LUN identifier.
9733	 */
9734	if (lun && lun->lun_devid) {
9735		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9736		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9737		    lun->lun_devid->len);
9738	}
9739
9740	/*
9741	 * This is for the WWPN which is a port association.
9742	 */
9743	if (port->port_devid) {
9744		memcpy(desc, port->port_devid->data, port->port_devid->len);
9745		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9746		    port->port_devid->len);
9747	}
9748
9749	/*
9750	 * This is for the Relative Target Port(type 4h) identifier
9751	 */
9752	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9753	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9754	    SVPD_ID_TYPE_RELTARG;
9755	desc->length = 4;
9756	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9757	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9758	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9759
9760	/*
9761	 * This is for the Target Port Group(type 5h) identifier
9762	 */
9763	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9764	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9765	    SVPD_ID_TYPE_TPORTGRP;
9766	desc->length = 4;
9767	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS || ctl_is_single)
9768		scsi_ulto2b(1, &desc->identifier[2]);
9769	else
9770		scsi_ulto2b(2, &desc->identifier[2]);
9771	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9772	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9773
9774	/*
9775	 * This is for the Target identifier
9776	 */
9777	if (port->target_devid) {
9778		memcpy(desc, port->target_devid->data, port->target_devid->len);
9779	}
9780
9781	ctsio->scsi_status = SCSI_STATUS_OK;
9782	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9783	ctsio->be_move_done = ctl_config_move_done;
9784	ctl_datamove((union ctl_io *)ctsio);
9785
9786	return (CTL_RETVAL_COMPLETE);
9787}
9788
9789static int
9790ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9791{
9792	struct scsi_vpd_block_limits *bl_ptr;
9793	struct ctl_lun *lun;
9794	int bs;
9795
9796	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9797	bs = lun->be_lun->blocksize;
9798
9799	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9800	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9801	ctsio->kern_sg_entries = 0;
9802
9803	if (sizeof(*bl_ptr) < alloc_len) {
9804		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9805		ctsio->kern_data_len = sizeof(*bl_ptr);
9806		ctsio->kern_total_len = sizeof(*bl_ptr);
9807	} else {
9808		ctsio->residual = 0;
9809		ctsio->kern_data_len = alloc_len;
9810		ctsio->kern_total_len = alloc_len;
9811	}
9812	ctsio->kern_data_resid = 0;
9813	ctsio->kern_rel_offset = 0;
9814	ctsio->kern_sg_entries = 0;
9815
9816	/*
9817	 * The control device is always connected.  The disk device, on the
9818	 * other hand, may not be online all the time.  Need to change this
9819	 * to figure out whether the disk device is actually online or not.
9820	 */
9821	if (lun != NULL)
9822		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9823				  lun->be_lun->lun_type;
9824	else
9825		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9826
9827	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9828	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
9829	bl_ptr->max_cmp_write_len = 0xff;
9830	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9831	scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
9832	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9833		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9834		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9835	}
9836	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9837
9838	ctsio->scsi_status = SCSI_STATUS_OK;
9839	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9840	ctsio->be_move_done = ctl_config_move_done;
9841	ctl_datamove((union ctl_io *)ctsio);
9842
9843	return (CTL_RETVAL_COMPLETE);
9844}
9845
9846static int
9847ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9848{
9849	struct scsi_vpd_logical_block_prov *lbp_ptr;
9850	struct ctl_lun *lun;
9851	int bs;
9852
9853	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9854	bs = lun->be_lun->blocksize;
9855
9856	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9857	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9858	ctsio->kern_sg_entries = 0;
9859
9860	if (sizeof(*lbp_ptr) < alloc_len) {
9861		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9862		ctsio->kern_data_len = sizeof(*lbp_ptr);
9863		ctsio->kern_total_len = sizeof(*lbp_ptr);
9864	} else {
9865		ctsio->residual = 0;
9866		ctsio->kern_data_len = alloc_len;
9867		ctsio->kern_total_len = alloc_len;
9868	}
9869	ctsio->kern_data_resid = 0;
9870	ctsio->kern_rel_offset = 0;
9871	ctsio->kern_sg_entries = 0;
9872
9873	/*
9874	 * The control device is always connected.  The disk device, on the
9875	 * other hand, may not be online all the time.  Need to change this
9876	 * to figure out whether the disk device is actually online or not.
9877	 */
9878	if (lun != NULL)
9879		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9880				  lun->be_lun->lun_type;
9881	else
9882		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9883
9884	lbp_ptr->page_code = SVPD_LBP;
9885	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
9886		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
9887
9888	ctsio->scsi_status = SCSI_STATUS_OK;
9889	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9890	ctsio->be_move_done = ctl_config_move_done;
9891	ctl_datamove((union ctl_io *)ctsio);
9892
9893	return (CTL_RETVAL_COMPLETE);
9894}
9895
9896static int
9897ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9898{
9899	struct scsi_inquiry *cdb;
9900	struct ctl_lun *lun;
9901	int alloc_len, retval;
9902
9903	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9904	cdb = (struct scsi_inquiry *)ctsio->cdb;
9905
9906	retval = CTL_RETVAL_COMPLETE;
9907
9908	alloc_len = scsi_2btoul(cdb->length);
9909
9910	switch (cdb->page_code) {
9911	case SVPD_SUPPORTED_PAGES:
9912		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9913		break;
9914	case SVPD_UNIT_SERIAL_NUMBER:
9915		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9916		break;
9917	case SVPD_DEVICE_ID:
9918		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9919		break;
9920	case SVPD_BLOCK_LIMITS:
9921		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9922		break;
9923	case SVPD_LBP:
9924		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9925		break;
9926	default:
9927		ctl_set_invalid_field(ctsio,
9928				      /*sks_valid*/ 1,
9929				      /*command*/ 1,
9930				      /*field*/ 2,
9931				      /*bit_valid*/ 0,
9932				      /*bit*/ 0);
9933		ctl_done((union ctl_io *)ctsio);
9934		retval = CTL_RETVAL_COMPLETE;
9935		break;
9936	}
9937
9938	return (retval);
9939}
9940
9941static int
9942ctl_inquiry_std(struct ctl_scsiio *ctsio)
9943{
9944	struct scsi_inquiry_data *inq_ptr;
9945	struct scsi_inquiry *cdb;
9946	struct ctl_softc *ctl_softc;
9947	struct ctl_lun *lun;
9948	char *val;
9949	uint32_t alloc_len;
9950	int is_fc;
9951
9952	ctl_softc = control_softc;
9953
9954	/*
9955	 * Figure out whether we're talking to a Fibre Channel port or not.
9956	 * We treat the ioctl front end, and any SCSI adapters, as packetized
9957	 * SCSI front ends.
9958	 */
9959	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
9960	    CTL_PORT_FC)
9961		is_fc = 0;
9962	else
9963		is_fc = 1;
9964
9965	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9966	cdb = (struct scsi_inquiry *)ctsio->cdb;
9967	alloc_len = scsi_2btoul(cdb->length);
9968
9969	/*
9970	 * We malloc the full inquiry data size here and fill it
9971	 * in.  If the user only asks for less, we'll give him
9972	 * that much.
9973	 */
9974	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
9975	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9976	ctsio->kern_sg_entries = 0;
9977	ctsio->kern_data_resid = 0;
9978	ctsio->kern_rel_offset = 0;
9979
9980	if (sizeof(*inq_ptr) < alloc_len) {
9981		ctsio->residual = alloc_len - sizeof(*inq_ptr);
9982		ctsio->kern_data_len = sizeof(*inq_ptr);
9983		ctsio->kern_total_len = sizeof(*inq_ptr);
9984	} else {
9985		ctsio->residual = 0;
9986		ctsio->kern_data_len = alloc_len;
9987		ctsio->kern_total_len = alloc_len;
9988	}
9989
9990	/*
9991	 * If we have a LUN configured, report it as connected.  Otherwise,
9992	 * report that it is offline or no device is supported, depending
9993	 * on the value of inquiry_pq_no_lun.
9994	 *
9995	 * According to the spec (SPC-4 r34), the peripheral qualifier
9996	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9997	 *
9998	 * "A peripheral device having the specified peripheral device type
9999	 * is not connected to this logical unit. However, the device
10000	 * server is capable of supporting the specified peripheral device
10001	 * type on this logical unit."
10002	 *
10003	 * According to the same spec, the peripheral qualifier
10004	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10005	 *
10006	 * "The device server is not capable of supporting a peripheral
10007	 * device on this logical unit. For this peripheral qualifier the
10008	 * peripheral device type shall be set to 1Fh. All other peripheral
10009	 * device type values are reserved for this peripheral qualifier."
10010	 *
10011	 * Given the text, it would seem that we probably want to report that
10012	 * the LUN is offline here.  There is no LUN connected, but we can
10013	 * support a LUN at the given LUN number.
10014	 *
10015	 * In the real world, though, it sounds like things are a little
10016	 * different:
10017	 *
10018	 * - Linux, when presented with a LUN with the offline peripheral
10019	 *   qualifier, will create an sg driver instance for it.  So when
10020	 *   you attach it to CTL, you wind up with a ton of sg driver
10021	 *   instances.  (One for every LUN that Linux bothered to probe.)
10022	 *   Linux does this despite the fact that it issues a REPORT LUNs
10023	 *   to LUN 0 to get the inventory of supported LUNs.
10024	 *
10025	 * - There is other anecdotal evidence (from Emulex folks) about
10026	 *   arrays that use the offline peripheral qualifier for LUNs that
10027	 *   are on the "passive" path in an active/passive array.
10028	 *
10029	 * So the solution is provide a hopefully reasonable default
10030	 * (return bad/no LUN) and allow the user to change the behavior
10031	 * with a tunable/sysctl variable.
10032	 */
10033	if (lun != NULL)
10034		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10035				  lun->be_lun->lun_type;
10036	else if (ctl_softc->inquiry_pq_no_lun == 0)
10037		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10038	else
10039		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10040
10041	/* RMB in byte 2 is 0 */
10042	inq_ptr->version = SCSI_REV_SPC3;
10043
10044	/*
10045	 * According to SAM-3, even if a device only supports a single
10046	 * level of LUN addressing, it should still set the HISUP bit:
10047	 *
10048	 * 4.9.1 Logical unit numbers overview
10049	 *
10050	 * All logical unit number formats described in this standard are
10051	 * hierarchical in structure even when only a single level in that
10052	 * hierarchy is used. The HISUP bit shall be set to one in the
10053	 * standard INQUIRY data (see SPC-2) when any logical unit number
10054	 * format described in this standard is used.  Non-hierarchical
10055	 * formats are outside the scope of this standard.
10056	 *
10057	 * Therefore we set the HiSup bit here.
10058	 *
10059	 * The reponse format is 2, per SPC-3.
10060	 */
10061	inq_ptr->response_format = SID_HiSup | 2;
10062
10063	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10064	CTL_DEBUG_PRINT(("additional_length = %d\n",
10065			 inq_ptr->additional_length));
10066
10067	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
10068	/* 16 bit addressing */
10069	if (is_fc == 0)
10070		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10071	/* XXX set the SID_MultiP bit here if we're actually going to
10072	   respond on multiple ports */
10073	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10074
10075	/* 16 bit data bus, synchronous transfers */
10076	/* XXX these flags don't apply for FC */
10077	if (is_fc == 0)
10078		inq_ptr->flags = SID_WBus16 | SID_Sync;
10079	/*
10080	 * XXX KDM do we want to support tagged queueing on the control
10081	 * device at all?
10082	 */
10083	if ((lun == NULL)
10084	 || (lun->be_lun->lun_type != T_PROCESSOR))
10085		inq_ptr->flags |= SID_CmdQue;
10086	/*
10087	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10088	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10089	 * name and 4 bytes for the revision.
10090	 */
10091	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10092	    "vendor")) == NULL) {
10093		strcpy(inq_ptr->vendor, CTL_VENDOR);
10094	} else {
10095		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10096		strncpy(inq_ptr->vendor, val,
10097		    min(sizeof(inq_ptr->vendor), strlen(val)));
10098	}
10099	if (lun == NULL) {
10100		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10101	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10102		switch (lun->be_lun->lun_type) {
10103		case T_DIRECT:
10104			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10105			break;
10106		case T_PROCESSOR:
10107			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10108			break;
10109		default:
10110			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10111			break;
10112		}
10113	} else {
10114		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10115		strncpy(inq_ptr->product, val,
10116		    min(sizeof(inq_ptr->product), strlen(val)));
10117	}
10118
10119	/*
10120	 * XXX make this a macro somewhere so it automatically gets
10121	 * incremented when we make changes.
10122	 */
10123	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10124	    "revision")) == NULL) {
10125		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10126	} else {
10127		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10128		strncpy(inq_ptr->revision, val,
10129		    min(sizeof(inq_ptr->revision), strlen(val)));
10130	}
10131
10132	/*
10133	 * For parallel SCSI, we support double transition and single
10134	 * transition clocking.  We also support QAS (Quick Arbitration
10135	 * and Selection) and Information Unit transfers on both the
10136	 * control and array devices.
10137	 */
10138	if (is_fc == 0)
10139		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10140				    SID_SPI_IUS;
10141
10142	/* SAM-3 */
10143	scsi_ulto2b(0x0060, inq_ptr->version1);
10144	/* SPC-3 (no version claimed) XXX should we claim a version? */
10145	scsi_ulto2b(0x0300, inq_ptr->version2);
10146	if (is_fc) {
10147		/* FCP-2 ANSI INCITS.350:2003 */
10148		scsi_ulto2b(0x0917, inq_ptr->version3);
10149	} else {
10150		/* SPI-4 ANSI INCITS.362:200x */
10151		scsi_ulto2b(0x0B56, inq_ptr->version3);
10152	}
10153
10154	if (lun == NULL) {
10155		/* SBC-2 (no version claimed) XXX should we claim a version? */
10156		scsi_ulto2b(0x0320, inq_ptr->version4);
10157	} else {
10158		switch (lun->be_lun->lun_type) {
10159		case T_DIRECT:
10160			/*
10161			 * SBC-2 (no version claimed) XXX should we claim a
10162			 * version?
10163			 */
10164			scsi_ulto2b(0x0320, inq_ptr->version4);
10165			break;
10166		case T_PROCESSOR:
10167		default:
10168			break;
10169		}
10170	}
10171
10172	ctsio->scsi_status = SCSI_STATUS_OK;
10173	if (ctsio->kern_data_len > 0) {
10174		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10175		ctsio->be_move_done = ctl_config_move_done;
10176		ctl_datamove((union ctl_io *)ctsio);
10177	} else {
10178		ctsio->io_hdr.status = CTL_SUCCESS;
10179		ctl_done((union ctl_io *)ctsio);
10180	}
10181
10182	return (CTL_RETVAL_COMPLETE);
10183}
10184
10185int
10186ctl_inquiry(struct ctl_scsiio *ctsio)
10187{
10188	struct scsi_inquiry *cdb;
10189	int retval;
10190
10191	cdb = (struct scsi_inquiry *)ctsio->cdb;
10192
10193	retval = 0;
10194
10195	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10196
10197	/*
10198	 * Right now, we don't support the CmdDt inquiry information.
10199	 * This would be nice to support in the future.  When we do
10200	 * support it, we should change this test so that it checks to make
10201	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10202	 */
10203#ifdef notyet
10204	if (((cdb->byte2 & SI_EVPD)
10205	 && (cdb->byte2 & SI_CMDDT)))
10206#endif
10207	if (cdb->byte2 & SI_CMDDT) {
10208		/*
10209		 * Point to the SI_CMDDT bit.  We might change this
10210		 * when we support SI_CMDDT, but since both bits would be
10211		 * "wrong", this should probably just stay as-is then.
10212		 */
10213		ctl_set_invalid_field(ctsio,
10214				      /*sks_valid*/ 1,
10215				      /*command*/ 1,
10216				      /*field*/ 1,
10217				      /*bit_valid*/ 1,
10218				      /*bit*/ 1);
10219		ctl_done((union ctl_io *)ctsio);
10220		return (CTL_RETVAL_COMPLETE);
10221	}
10222	if (cdb->byte2 & SI_EVPD)
10223		retval = ctl_inquiry_evpd(ctsio);
10224#ifdef notyet
10225	else if (cdb->byte2 & SI_CMDDT)
10226		retval = ctl_inquiry_cmddt(ctsio);
10227#endif
10228	else
10229		retval = ctl_inquiry_std(ctsio);
10230
10231	return (retval);
10232}
10233
10234/*
10235 * For known CDB types, parse the LBA and length.
10236 */
10237static int
10238ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10239{
10240	if (io->io_hdr.io_type != CTL_IO_SCSI)
10241		return (1);
10242
10243	switch (io->scsiio.cdb[0]) {
10244	case COMPARE_AND_WRITE: {
10245		struct scsi_compare_and_write *cdb;
10246
10247		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10248
10249		*lba = scsi_8btou64(cdb->addr);
10250		*len = cdb->length;
10251		break;
10252	}
10253	case READ_6:
10254	case WRITE_6: {
10255		struct scsi_rw_6 *cdb;
10256
10257		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10258
10259		*lba = scsi_3btoul(cdb->addr);
10260		/* only 5 bits are valid in the most significant address byte */
10261		*lba &= 0x1fffff;
10262		*len = cdb->length;
10263		break;
10264	}
10265	case READ_10:
10266	case WRITE_10: {
10267		struct scsi_rw_10 *cdb;
10268
10269		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10270
10271		*lba = scsi_4btoul(cdb->addr);
10272		*len = scsi_2btoul(cdb->length);
10273		break;
10274	}
10275	case WRITE_VERIFY_10: {
10276		struct scsi_write_verify_10 *cdb;
10277
10278		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10279
10280		*lba = scsi_4btoul(cdb->addr);
10281		*len = scsi_2btoul(cdb->length);
10282		break;
10283	}
10284	case READ_12:
10285	case WRITE_12: {
10286		struct scsi_rw_12 *cdb;
10287
10288		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10289
10290		*lba = scsi_4btoul(cdb->addr);
10291		*len = scsi_4btoul(cdb->length);
10292		break;
10293	}
10294	case WRITE_VERIFY_12: {
10295		struct scsi_write_verify_12 *cdb;
10296
10297		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10298
10299		*lba = scsi_4btoul(cdb->addr);
10300		*len = scsi_4btoul(cdb->length);
10301		break;
10302	}
10303	case READ_16:
10304	case WRITE_16: {
10305		struct scsi_rw_16 *cdb;
10306
10307		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10308
10309		*lba = scsi_8btou64(cdb->addr);
10310		*len = scsi_4btoul(cdb->length);
10311		break;
10312	}
10313	case WRITE_VERIFY_16: {
10314		struct scsi_write_verify_16 *cdb;
10315
10316		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10317
10318
10319		*lba = scsi_8btou64(cdb->addr);
10320		*len = scsi_4btoul(cdb->length);
10321		break;
10322	}
10323	case WRITE_SAME_10: {
10324		struct scsi_write_same_10 *cdb;
10325
10326		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10327
10328		*lba = scsi_4btoul(cdb->addr);
10329		*len = scsi_2btoul(cdb->length);
10330		break;
10331	}
10332	case WRITE_SAME_16: {
10333		struct scsi_write_same_16 *cdb;
10334
10335		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10336
10337		*lba = scsi_8btou64(cdb->addr);
10338		*len = scsi_4btoul(cdb->length);
10339		break;
10340	}
10341	case VERIFY_10: {
10342		struct scsi_verify_10 *cdb;
10343
10344		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10345
10346		*lba = scsi_4btoul(cdb->addr);
10347		*len = scsi_2btoul(cdb->length);
10348		break;
10349	}
10350	case VERIFY_12: {
10351		struct scsi_verify_12 *cdb;
10352
10353		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10354
10355		*lba = scsi_4btoul(cdb->addr);
10356		*len = scsi_4btoul(cdb->length);
10357		break;
10358	}
10359	case VERIFY_16: {
10360		struct scsi_verify_16 *cdb;
10361
10362		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10363
10364		*lba = scsi_8btou64(cdb->addr);
10365		*len = scsi_4btoul(cdb->length);
10366		break;
10367	}
10368	default:
10369		return (1);
10370		break; /* NOTREACHED */
10371	}
10372
10373	return (0);
10374}
10375
10376static ctl_action
10377ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10378{
10379	uint64_t endlba1, endlba2;
10380
10381	endlba1 = lba1 + len1 - 1;
10382	endlba2 = lba2 + len2 - 1;
10383
10384	if ((endlba1 < lba2)
10385	 || (endlba2 < lba1))
10386		return (CTL_ACTION_PASS);
10387	else
10388		return (CTL_ACTION_BLOCK);
10389}
10390
10391static ctl_action
10392ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10393{
10394	uint64_t lba1, lba2;
10395	uint32_t len1, len2;
10396	int retval;
10397
10398	retval = ctl_get_lba_len(io1, &lba1, &len1);
10399	if (retval != 0)
10400		return (CTL_ACTION_ERROR);
10401
10402	retval = ctl_get_lba_len(io2, &lba2, &len2);
10403	if (retval != 0)
10404		return (CTL_ACTION_ERROR);
10405
10406	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10407}
10408
10409static ctl_action
10410ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10411{
10412	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10413	ctl_serialize_action *serialize_row;
10414
10415	/*
10416	 * The initiator attempted multiple untagged commands at the same
10417	 * time.  Can't do that.
10418	 */
10419	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10420	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10421	 && ((pending_io->io_hdr.nexus.targ_port ==
10422	      ooa_io->io_hdr.nexus.targ_port)
10423	  && (pending_io->io_hdr.nexus.initid.id ==
10424	      ooa_io->io_hdr.nexus.initid.id))
10425	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10426		return (CTL_ACTION_OVERLAP);
10427
10428	/*
10429	 * The initiator attempted to send multiple tagged commands with
10430	 * the same ID.  (It's fine if different initiators have the same
10431	 * tag ID.)
10432	 *
10433	 * Even if all of those conditions are true, we don't kill the I/O
10434	 * if the command ahead of us has been aborted.  We won't end up
10435	 * sending it to the FETD, and it's perfectly legal to resend a
10436	 * command with the same tag number as long as the previous
10437	 * instance of this tag number has been aborted somehow.
10438	 */
10439	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10440	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10441	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10442	 && ((pending_io->io_hdr.nexus.targ_port ==
10443	      ooa_io->io_hdr.nexus.targ_port)
10444	  && (pending_io->io_hdr.nexus.initid.id ==
10445	      ooa_io->io_hdr.nexus.initid.id))
10446	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10447		return (CTL_ACTION_OVERLAP_TAG);
10448
10449	/*
10450	 * If we get a head of queue tag, SAM-3 says that we should
10451	 * immediately execute it.
10452	 *
10453	 * What happens if this command would normally block for some other
10454	 * reason?  e.g. a request sense with a head of queue tag
10455	 * immediately after a write.  Normally that would block, but this
10456	 * will result in its getting executed immediately...
10457	 *
10458	 * We currently return "pass" instead of "skip", so we'll end up
10459	 * going through the rest of the queue to check for overlapped tags.
10460	 *
10461	 * XXX KDM check for other types of blockage first??
10462	 */
10463	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10464		return (CTL_ACTION_PASS);
10465
10466	/*
10467	 * Ordered tags have to block until all items ahead of them
10468	 * have completed.  If we get called with an ordered tag, we always
10469	 * block, if something else is ahead of us in the queue.
10470	 */
10471	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10472		return (CTL_ACTION_BLOCK);
10473
10474	/*
10475	 * Simple tags get blocked until all head of queue and ordered tags
10476	 * ahead of them have completed.  I'm lumping untagged commands in
10477	 * with simple tags here.  XXX KDM is that the right thing to do?
10478	 */
10479	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10480	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10481	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10482	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10483		return (CTL_ACTION_BLOCK);
10484
10485	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10486	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10487
10488	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10489
10490	switch (serialize_row[pending_entry->seridx]) {
10491	case CTL_SER_BLOCK:
10492		return (CTL_ACTION_BLOCK);
10493		break; /* NOTREACHED */
10494	case CTL_SER_EXTENT:
10495		return (ctl_extent_check(pending_io, ooa_io));
10496		break; /* NOTREACHED */
10497	case CTL_SER_PASS:
10498		return (CTL_ACTION_PASS);
10499		break; /* NOTREACHED */
10500	case CTL_SER_SKIP:
10501		return (CTL_ACTION_SKIP);
10502		break;
10503	default:
10504		panic("invalid serialization value %d",
10505		      serialize_row[pending_entry->seridx]);
10506		break; /* NOTREACHED */
10507	}
10508
10509	return (CTL_ACTION_ERROR);
10510}
10511
10512/*
10513 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10514 * Assumptions:
10515 * - pending_io is generally either incoming, or on the blocked queue
10516 * - starting I/O is the I/O we want to start the check with.
10517 */
10518static ctl_action
10519ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10520	      union ctl_io *starting_io)
10521{
10522	union ctl_io *ooa_io;
10523	ctl_action action;
10524
10525	mtx_assert(&lun->lun_lock, MA_OWNED);
10526
10527	/*
10528	 * Run back along the OOA queue, starting with the current
10529	 * blocked I/O and going through every I/O before it on the
10530	 * queue.  If starting_io is NULL, we'll just end up returning
10531	 * CTL_ACTION_PASS.
10532	 */
10533	for (ooa_io = starting_io; ooa_io != NULL;
10534	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10535	     ooa_links)){
10536
10537		/*
10538		 * This routine just checks to see whether
10539		 * cur_blocked is blocked by ooa_io, which is ahead
10540		 * of it in the queue.  It doesn't queue/dequeue
10541		 * cur_blocked.
10542		 */
10543		action = ctl_check_for_blockage(pending_io, ooa_io);
10544		switch (action) {
10545		case CTL_ACTION_BLOCK:
10546		case CTL_ACTION_OVERLAP:
10547		case CTL_ACTION_OVERLAP_TAG:
10548		case CTL_ACTION_SKIP:
10549		case CTL_ACTION_ERROR:
10550			return (action);
10551			break; /* NOTREACHED */
10552		case CTL_ACTION_PASS:
10553			break;
10554		default:
10555			panic("invalid action %d", action);
10556			break;  /* NOTREACHED */
10557		}
10558	}
10559
10560	return (CTL_ACTION_PASS);
10561}
10562
10563/*
10564 * Assumptions:
10565 * - An I/O has just completed, and has been removed from the per-LUN OOA
10566 *   queue, so some items on the blocked queue may now be unblocked.
10567 */
10568static int
10569ctl_check_blocked(struct ctl_lun *lun)
10570{
10571	union ctl_io *cur_blocked, *next_blocked;
10572
10573	mtx_assert(&lun->lun_lock, MA_OWNED);
10574
10575	/*
10576	 * Run forward from the head of the blocked queue, checking each
10577	 * entry against the I/Os prior to it on the OOA queue to see if
10578	 * there is still any blockage.
10579	 *
10580	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10581	 * with our removing a variable on it while it is traversing the
10582	 * list.
10583	 */
10584	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10585	     cur_blocked != NULL; cur_blocked = next_blocked) {
10586		union ctl_io *prev_ooa;
10587		ctl_action action;
10588
10589		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10590							  blocked_links);
10591
10592		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10593						      ctl_ooaq, ooa_links);
10594
10595		/*
10596		 * If cur_blocked happens to be the first item in the OOA
10597		 * queue now, prev_ooa will be NULL, and the action
10598		 * returned will just be CTL_ACTION_PASS.
10599		 */
10600		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10601
10602		switch (action) {
10603		case CTL_ACTION_BLOCK:
10604			/* Nothing to do here, still blocked */
10605			break;
10606		case CTL_ACTION_OVERLAP:
10607		case CTL_ACTION_OVERLAP_TAG:
10608			/*
10609			 * This shouldn't happen!  In theory we've already
10610			 * checked this command for overlap...
10611			 */
10612			break;
10613		case CTL_ACTION_PASS:
10614		case CTL_ACTION_SKIP: {
10615			struct ctl_softc *softc;
10616			const struct ctl_cmd_entry *entry;
10617			uint32_t initidx;
10618			int isc_retval;
10619
10620			/*
10621			 * The skip case shouldn't happen, this transaction
10622			 * should have never made it onto the blocked queue.
10623			 */
10624			/*
10625			 * This I/O is no longer blocked, we can remove it
10626			 * from the blocked queue.  Since this is a TAILQ
10627			 * (doubly linked list), we can do O(1) removals
10628			 * from any place on the list.
10629			 */
10630			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10631				     blocked_links);
10632			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10633
10634			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10635				/*
10636				 * Need to send IO back to original side to
10637				 * run
10638				 */
10639				union ctl_ha_msg msg_info;
10640
10641				msg_info.hdr.original_sc =
10642					cur_blocked->io_hdr.original_sc;
10643				msg_info.hdr.serializing_sc = cur_blocked;
10644				msg_info.hdr.msg_type = CTL_MSG_R2R;
10645				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10646				     &msg_info, sizeof(msg_info), 0)) >
10647				     CTL_HA_STATUS_SUCCESS) {
10648					printf("CTL:Check Blocked error from "
10649					       "ctl_ha_msg_send %d\n",
10650					       isc_retval);
10651				}
10652				break;
10653			}
10654			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10655			softc = control_softc;
10656
10657			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10658
10659			/*
10660			 * Check this I/O for LUN state changes that may
10661			 * have happened while this command was blocked.
10662			 * The LUN state may have been changed by a command
10663			 * ahead of us in the queue, so we need to re-check
10664			 * for any states that can be caused by SCSI
10665			 * commands.
10666			 */
10667			if (ctl_scsiio_lun_check(softc, lun, entry,
10668						 &cur_blocked->scsiio) == 0) {
10669				cur_blocked->io_hdr.flags |=
10670				                      CTL_FLAG_IS_WAS_ON_RTR;
10671				ctl_enqueue_rtr(cur_blocked);
10672			} else
10673				ctl_done(cur_blocked);
10674			break;
10675		}
10676		default:
10677			/*
10678			 * This probably shouldn't happen -- we shouldn't
10679			 * get CTL_ACTION_ERROR, or anything else.
10680			 */
10681			break;
10682		}
10683	}
10684
10685	return (CTL_RETVAL_COMPLETE);
10686}
10687
10688/*
10689 * This routine (with one exception) checks LUN flags that can be set by
10690 * commands ahead of us in the OOA queue.  These flags have to be checked
10691 * when a command initially comes in, and when we pull a command off the
10692 * blocked queue and are preparing to execute it.  The reason we have to
10693 * check these flags for commands on the blocked queue is that the LUN
10694 * state may have been changed by a command ahead of us while we're on the
10695 * blocked queue.
10696 *
10697 * Ordering is somewhat important with these checks, so please pay
10698 * careful attention to the placement of any new checks.
10699 */
10700static int
10701ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10702    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10703{
10704	int retval;
10705
10706	retval = 0;
10707
10708	mtx_assert(&lun->lun_lock, MA_OWNED);
10709
10710	/*
10711	 * If this shelf is a secondary shelf controller, we have to reject
10712	 * any media access commands.
10713	 */
10714#if 0
10715	/* No longer needed for HA */
10716	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10717	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10718		ctl_set_lun_standby(ctsio);
10719		retval = 1;
10720		goto bailout;
10721	}
10722#endif
10723
10724	/*
10725	 * Check for a reservation conflict.  If this command isn't allowed
10726	 * even on reserved LUNs, and if this initiator isn't the one who
10727	 * reserved us, reject the command with a reservation conflict.
10728	 */
10729	if ((lun->flags & CTL_LUN_RESERVED)
10730	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10731		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10732		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10733		 || (ctsio->io_hdr.nexus.targ_target.id !=
10734		     lun->rsv_nexus.targ_target.id)) {
10735			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10736			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10737			retval = 1;
10738			goto bailout;
10739		}
10740	}
10741
10742	if ( (lun->flags & CTL_LUN_PR_RESERVED)
10743	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10744		uint32_t residx;
10745
10746		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10747		/*
10748		 * if we aren't registered or it's a res holder type
10749		 * reservation and this isn't the res holder then set a
10750		 * conflict.
10751		 * NOTE: Commands which might be allowed on write exclusive
10752		 * type reservations are checked in the particular command
10753		 * for a conflict. Read and SSU are the only ones.
10754		 */
10755		if (!lun->per_res[residx].registered
10756		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10757			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10758			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10759			retval = 1;
10760			goto bailout;
10761		}
10762
10763	}
10764
10765	if ((lun->flags & CTL_LUN_OFFLINE)
10766	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10767		ctl_set_lun_not_ready(ctsio);
10768		retval = 1;
10769		goto bailout;
10770	}
10771
10772	/*
10773	 * If the LUN is stopped, see if this particular command is allowed
10774	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10775	 */
10776	if ((lun->flags & CTL_LUN_STOPPED)
10777	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10778		/* "Logical unit not ready, initializing cmd. required" */
10779		ctl_set_lun_stopped(ctsio);
10780		retval = 1;
10781		goto bailout;
10782	}
10783
10784	if ((lun->flags & CTL_LUN_INOPERABLE)
10785	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10786		/* "Medium format corrupted" */
10787		ctl_set_medium_format_corrupted(ctsio);
10788		retval = 1;
10789		goto bailout;
10790	}
10791
10792bailout:
10793	return (retval);
10794
10795}
10796
10797static void
10798ctl_failover_io(union ctl_io *io, int have_lock)
10799{
10800	ctl_set_busy(&io->scsiio);
10801	ctl_done(io);
10802}
10803
10804static void
10805ctl_failover(void)
10806{
10807	struct ctl_lun *lun;
10808	struct ctl_softc *ctl_softc;
10809	union ctl_io *next_io, *pending_io;
10810	union ctl_io *io;
10811	int lun_idx;
10812	int i;
10813
10814	ctl_softc = control_softc;
10815
10816	mtx_lock(&ctl_softc->ctl_lock);
10817	/*
10818	 * Remove any cmds from the other SC from the rtr queue.  These
10819	 * will obviously only be for LUNs for which we're the primary.
10820	 * We can't send status or get/send data for these commands.
10821	 * Since they haven't been executed yet, we can just remove them.
10822	 * We'll either abort them or delete them below, depending on
10823	 * which HA mode we're in.
10824	 */
10825#ifdef notyet
10826	mtx_lock(&ctl_softc->queue_lock);
10827	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10828	     io != NULL; io = next_io) {
10829		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10830		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10831			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10832				      ctl_io_hdr, links);
10833	}
10834	mtx_unlock(&ctl_softc->queue_lock);
10835#endif
10836
10837	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
10838		lun = ctl_softc->ctl_luns[lun_idx];
10839		if (lun==NULL)
10840			continue;
10841
10842		/*
10843		 * Processor LUNs are primary on both sides.
10844		 * XXX will this always be true?
10845		 */
10846		if (lun->be_lun->lun_type == T_PROCESSOR)
10847			continue;
10848
10849		if ((lun->flags & CTL_LUN_PRIMARY_SC)
10850		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10851			printf("FAILOVER: primary lun %d\n", lun_idx);
10852		        /*
10853			 * Remove all commands from the other SC. First from the
10854			 * blocked queue then from the ooa queue. Once we have
10855			 * removed them. Call ctl_check_blocked to see if there
10856			 * is anything that can run.
10857			 */
10858			for (io = (union ctl_io *)TAILQ_FIRST(
10859			     &lun->blocked_queue); io != NULL; io = next_io) {
10860
10861		        	next_io = (union ctl_io *)TAILQ_NEXT(
10862				    &io->io_hdr, blocked_links);
10863
10864				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10865					TAILQ_REMOVE(&lun->blocked_queue,
10866						     &io->io_hdr,blocked_links);
10867					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10868					TAILQ_REMOVE(&lun->ooa_queue,
10869						     &io->io_hdr, ooa_links);
10870
10871					ctl_free_io(io);
10872				}
10873			}
10874
10875			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10876	     		     io != NULL; io = next_io) {
10877
10878		        	next_io = (union ctl_io *)TAILQ_NEXT(
10879				    &io->io_hdr, ooa_links);
10880
10881				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10882
10883					TAILQ_REMOVE(&lun->ooa_queue,
10884						&io->io_hdr,
10885					     	ooa_links);
10886
10887					ctl_free_io(io);
10888				}
10889			}
10890			ctl_check_blocked(lun);
10891		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10892			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10893
10894			printf("FAILOVER: primary lun %d\n", lun_idx);
10895			/*
10896			 * Abort all commands from the other SC.  We can't
10897			 * send status back for them now.  These should get
10898			 * cleaned up when they are completed or come out
10899			 * for a datamove operation.
10900			 */
10901			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10902	     		     io != NULL; io = next_io) {
10903		        	next_io = (union ctl_io *)TAILQ_NEXT(
10904					&io->io_hdr, ooa_links);
10905
10906				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10907					io->io_hdr.flags |= CTL_FLAG_ABORT;
10908			}
10909		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10910			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10911
10912			printf("FAILOVER: secondary lun %d\n", lun_idx);
10913
10914			lun->flags |= CTL_LUN_PRIMARY_SC;
10915
10916			/*
10917			 * We send all I/O that was sent to this controller
10918			 * and redirected to the other side back with
10919			 * busy status, and have the initiator retry it.
10920			 * Figuring out how much data has been transferred,
10921			 * etc. and picking up where we left off would be
10922			 * very tricky.
10923			 *
10924			 * XXX KDM need to remove I/O from the blocked
10925			 * queue as well!
10926			 */
10927			for (pending_io = (union ctl_io *)TAILQ_FIRST(
10928			     &lun->ooa_queue); pending_io != NULL;
10929			     pending_io = next_io) {
10930
10931				next_io =  (union ctl_io *)TAILQ_NEXT(
10932					&pending_io->io_hdr, ooa_links);
10933
10934				pending_io->io_hdr.flags &=
10935					~CTL_FLAG_SENT_2OTHER_SC;
10936
10937				if (pending_io->io_hdr.flags &
10938				    CTL_FLAG_IO_ACTIVE) {
10939					pending_io->io_hdr.flags |=
10940						CTL_FLAG_FAILOVER;
10941				} else {
10942					ctl_set_busy(&pending_io->scsiio);
10943					ctl_done(pending_io);
10944				}
10945			}
10946
10947			/*
10948			 * Build Unit Attention
10949			 */
10950			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10951				lun->pending_sense[i].ua_pending |=
10952				                     CTL_UA_ASYM_ACC_CHANGE;
10953			}
10954		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10955			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10956			printf("FAILOVER: secondary lun %d\n", lun_idx);
10957			/*
10958			 * if the first io on the OOA is not on the RtR queue
10959			 * add it.
10960			 */
10961			lun->flags |= CTL_LUN_PRIMARY_SC;
10962
10963			pending_io = (union ctl_io *)TAILQ_FIRST(
10964			    &lun->ooa_queue);
10965			if (pending_io==NULL) {
10966				printf("Nothing on OOA queue\n");
10967				continue;
10968			}
10969
10970			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10971			if ((pending_io->io_hdr.flags &
10972			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
10973				pending_io->io_hdr.flags |=
10974				    CTL_FLAG_IS_WAS_ON_RTR;
10975				ctl_enqueue_rtr(pending_io);
10976			}
10977#if 0
10978			else
10979			{
10980				printf("Tag 0x%04x is running\n",
10981				      pending_io->scsiio.tag_num);
10982			}
10983#endif
10984
10985			next_io = (union ctl_io *)TAILQ_NEXT(
10986			    &pending_io->io_hdr, ooa_links);
10987			for (pending_io=next_io; pending_io != NULL;
10988			     pending_io = next_io) {
10989				pending_io->io_hdr.flags &=
10990				    ~CTL_FLAG_SENT_2OTHER_SC;
10991				next_io = (union ctl_io *)TAILQ_NEXT(
10992					&pending_io->io_hdr, ooa_links);
10993				if (pending_io->io_hdr.flags &
10994				    CTL_FLAG_IS_WAS_ON_RTR) {
10995#if 0
10996				        printf("Tag 0x%04x is running\n",
10997				      		pending_io->scsiio.tag_num);
10998#endif
10999					continue;
11000				}
11001
11002				switch (ctl_check_ooa(lun, pending_io,
11003			            (union ctl_io *)TAILQ_PREV(
11004				    &pending_io->io_hdr, ctl_ooaq,
11005				    ooa_links))) {
11006
11007				case CTL_ACTION_BLOCK:
11008					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11009							  &pending_io->io_hdr,
11010							  blocked_links);
11011					pending_io->io_hdr.flags |=
11012					    CTL_FLAG_BLOCKED;
11013					break;
11014				case CTL_ACTION_PASS:
11015				case CTL_ACTION_SKIP:
11016					pending_io->io_hdr.flags |=
11017					    CTL_FLAG_IS_WAS_ON_RTR;
11018					ctl_enqueue_rtr(pending_io);
11019					break;
11020				case CTL_ACTION_OVERLAP:
11021					ctl_set_overlapped_cmd(
11022					    (struct ctl_scsiio *)pending_io);
11023					ctl_done(pending_io);
11024					break;
11025				case CTL_ACTION_OVERLAP_TAG:
11026					ctl_set_overlapped_tag(
11027					    (struct ctl_scsiio *)pending_io,
11028					    pending_io->scsiio.tag_num & 0xff);
11029					ctl_done(pending_io);
11030					break;
11031				case CTL_ACTION_ERROR:
11032				default:
11033					ctl_set_internal_failure(
11034						(struct ctl_scsiio *)pending_io,
11035						0,  // sks_valid
11036						0); //retry count
11037					ctl_done(pending_io);
11038					break;
11039				}
11040			}
11041
11042			/*
11043			 * Build Unit Attention
11044			 */
11045			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11046				lun->pending_sense[i].ua_pending |=
11047				                     CTL_UA_ASYM_ACC_CHANGE;
11048			}
11049		} else {
11050			panic("Unhandled HA mode failover, LUN flags = %#x, "
11051			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11052		}
11053	}
11054	ctl_pause_rtr = 0;
11055	mtx_unlock(&ctl_softc->ctl_lock);
11056}
11057
11058static int
11059ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11060{
11061	struct ctl_lun *lun;
11062	const struct ctl_cmd_entry *entry;
11063	uint32_t initidx, targ_lun;
11064	int retval;
11065
11066	retval = 0;
11067
11068	lun = NULL;
11069
11070	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11071	if ((targ_lun < CTL_MAX_LUNS)
11072	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11073		lun = ctl_softc->ctl_luns[targ_lun];
11074		/*
11075		 * If the LUN is invalid, pretend that it doesn't exist.
11076		 * It will go away as soon as all pending I/O has been
11077		 * completed.
11078		 */
11079		if (lun->flags & CTL_LUN_DISABLED) {
11080			lun = NULL;
11081		} else {
11082			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11083			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11084				lun->be_lun;
11085			if (lun->be_lun->lun_type == T_PROCESSOR) {
11086				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11087			}
11088
11089			/*
11090			 * Every I/O goes into the OOA queue for a
11091			 * particular LUN, and stays there until completion.
11092			 */
11093			mtx_lock(&lun->lun_lock);
11094			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11095			    ooa_links);
11096		}
11097	} else {
11098		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11099		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11100	}
11101
11102	/* Get command entry and return error if it is unsuppotyed. */
11103	entry = ctl_validate_command(ctsio);
11104	if (entry == NULL) {
11105		if (lun)
11106			mtx_unlock(&lun->lun_lock);
11107		return (retval);
11108	}
11109
11110	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11111	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11112
11113	/*
11114	 * Check to see whether we can send this command to LUNs that don't
11115	 * exist.  This should pretty much only be the case for inquiry
11116	 * and request sense.  Further checks, below, really require having
11117	 * a LUN, so we can't really check the command anymore.  Just put
11118	 * it on the rtr queue.
11119	 */
11120	if (lun == NULL) {
11121		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11122			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11123			ctl_enqueue_rtr((union ctl_io *)ctsio);
11124			return (retval);
11125		}
11126
11127		ctl_set_unsupported_lun(ctsio);
11128		ctl_done((union ctl_io *)ctsio);
11129		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11130		return (retval);
11131	} else {
11132		/*
11133		 * Make sure we support this particular command on this LUN.
11134		 * e.g., we don't support writes to the control LUN.
11135		 */
11136		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11137			mtx_unlock(&lun->lun_lock);
11138			ctl_set_invalid_opcode(ctsio);
11139			ctl_done((union ctl_io *)ctsio);
11140			return (retval);
11141		}
11142	}
11143
11144	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11145
11146	/*
11147	 * If we've got a request sense, it'll clear the contingent
11148	 * allegiance condition.  Otherwise, if we have a CA condition for
11149	 * this initiator, clear it, because it sent down a command other
11150	 * than request sense.
11151	 */
11152	if ((ctsio->cdb[0] != REQUEST_SENSE)
11153	 && (ctl_is_set(lun->have_ca, initidx)))
11154		ctl_clear_mask(lun->have_ca, initidx);
11155
11156	/*
11157	 * If the command has this flag set, it handles its own unit
11158	 * attention reporting, we shouldn't do anything.  Otherwise we
11159	 * check for any pending unit attentions, and send them back to the
11160	 * initiator.  We only do this when a command initially comes in,
11161	 * not when we pull it off the blocked queue.
11162	 *
11163	 * According to SAM-3, section 5.3.2, the order that things get
11164	 * presented back to the host is basically unit attentions caused
11165	 * by some sort of reset event, busy status, reservation conflicts
11166	 * or task set full, and finally any other status.
11167	 *
11168	 * One issue here is that some of the unit attentions we report
11169	 * don't fall into the "reset" category (e.g. "reported luns data
11170	 * has changed").  So reporting it here, before the reservation
11171	 * check, may be technically wrong.  I guess the only thing to do
11172	 * would be to check for and report the reset events here, and then
11173	 * check for the other unit attention types after we check for a
11174	 * reservation conflict.
11175	 *
11176	 * XXX KDM need to fix this
11177	 */
11178	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11179		ctl_ua_type ua_type;
11180
11181		ua_type = lun->pending_sense[initidx].ua_pending;
11182		if (ua_type != CTL_UA_NONE) {
11183			scsi_sense_data_type sense_format;
11184
11185			if (lun != NULL)
11186				sense_format = (lun->flags &
11187				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11188				    SSD_TYPE_FIXED;
11189			else
11190				sense_format = SSD_TYPE_FIXED;
11191
11192			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11193					       sense_format);
11194			if (ua_type != CTL_UA_NONE) {
11195				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11196				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11197						       CTL_AUTOSENSE;
11198				ctsio->sense_len = SSD_FULL_SIZE;
11199				lun->pending_sense[initidx].ua_pending &=
11200					~ua_type;
11201				mtx_unlock(&lun->lun_lock);
11202				ctl_done((union ctl_io *)ctsio);
11203				return (retval);
11204			}
11205		}
11206	}
11207
11208
11209	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11210		mtx_unlock(&lun->lun_lock);
11211		ctl_done((union ctl_io *)ctsio);
11212		return (retval);
11213	}
11214
11215	/*
11216	 * XXX CHD this is where we want to send IO to other side if
11217	 * this LUN is secondary on this SC. We will need to make a copy
11218	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11219	 * the copy we send as FROM_OTHER.
11220	 * We also need to stuff the address of the original IO so we can
11221	 * find it easily. Something similar will need be done on the other
11222	 * side so when we are done we can find the copy.
11223	 */
11224	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11225		union ctl_ha_msg msg_info;
11226		int isc_retval;
11227
11228		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11229
11230		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11231		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11232#if 0
11233		printf("1. ctsio %p\n", ctsio);
11234#endif
11235		msg_info.hdr.serializing_sc = NULL;
11236		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11237		msg_info.scsi.tag_num = ctsio->tag_num;
11238		msg_info.scsi.tag_type = ctsio->tag_type;
11239		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11240
11241		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11242
11243		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11244		    (void *)&msg_info, sizeof(msg_info), 0)) >
11245		    CTL_HA_STATUS_SUCCESS) {
11246			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11247			       isc_retval);
11248			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11249		} else {
11250#if 0
11251			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11252#endif
11253		}
11254
11255		/*
11256		 * XXX KDM this I/O is off the incoming queue, but hasn't
11257		 * been inserted on any other queue.  We may need to come
11258		 * up with a holding queue while we wait for serialization
11259		 * so that we have an idea of what we're waiting for from
11260		 * the other side.
11261		 */
11262		mtx_unlock(&lun->lun_lock);
11263		return (retval);
11264	}
11265
11266	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11267			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11268			      ctl_ooaq, ooa_links))) {
11269	case CTL_ACTION_BLOCK:
11270		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11271		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11272				  blocked_links);
11273		mtx_unlock(&lun->lun_lock);
11274		return (retval);
11275	case CTL_ACTION_PASS:
11276	case CTL_ACTION_SKIP:
11277		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11278		mtx_unlock(&lun->lun_lock);
11279		ctl_enqueue_rtr((union ctl_io *)ctsio);
11280		break;
11281	case CTL_ACTION_OVERLAP:
11282		mtx_unlock(&lun->lun_lock);
11283		ctl_set_overlapped_cmd(ctsio);
11284		ctl_done((union ctl_io *)ctsio);
11285		break;
11286	case CTL_ACTION_OVERLAP_TAG:
11287		mtx_unlock(&lun->lun_lock);
11288		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11289		ctl_done((union ctl_io *)ctsio);
11290		break;
11291	case CTL_ACTION_ERROR:
11292	default:
11293		mtx_unlock(&lun->lun_lock);
11294		ctl_set_internal_failure(ctsio,
11295					 /*sks_valid*/ 0,
11296					 /*retry_count*/ 0);
11297		ctl_done((union ctl_io *)ctsio);
11298		break;
11299	}
11300	return (retval);
11301}
11302
11303const struct ctl_cmd_entry *
11304ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11305{
11306	const struct ctl_cmd_entry *entry;
11307	int service_action;
11308
11309	entry = &ctl_cmd_table[ctsio->cdb[0]];
11310	if (entry->flags & CTL_CMD_FLAG_SA5) {
11311		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11312		entry = &((const struct ctl_cmd_entry *)
11313		    entry->execute)[service_action];
11314	}
11315	return (entry);
11316}
11317
11318const struct ctl_cmd_entry *
11319ctl_validate_command(struct ctl_scsiio *ctsio)
11320{
11321	const struct ctl_cmd_entry *entry;
11322	int i;
11323	uint8_t diff;
11324
11325	entry = ctl_get_cmd_entry(ctsio);
11326	if (entry->execute == NULL) {
11327		ctl_set_invalid_opcode(ctsio);
11328		ctl_done((union ctl_io *)ctsio);
11329		return (NULL);
11330	}
11331	KASSERT(entry->length > 0,
11332	    ("Not defined length for command 0x%02x/0x%02x",
11333	     ctsio->cdb[0], ctsio->cdb[1]));
11334	for (i = 1; i < entry->length; i++) {
11335		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11336		if (diff == 0)
11337			continue;
11338		ctl_set_invalid_field(ctsio,
11339				      /*sks_valid*/ 1,
11340				      /*command*/ 1,
11341				      /*field*/ i,
11342				      /*bit_valid*/ 1,
11343				      /*bit*/ fls(diff) - 1);
11344		ctl_done((union ctl_io *)ctsio);
11345		return (NULL);
11346	}
11347	return (entry);
11348}
11349
11350static int
11351ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11352{
11353
11354	switch (lun_type) {
11355	case T_PROCESSOR:
11356		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11357		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11358			return (0);
11359		break;
11360	case T_DIRECT:
11361		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11362		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11363			return (0);
11364		break;
11365	default:
11366		return (0);
11367	}
11368	return (1);
11369}
11370
11371static int
11372ctl_scsiio(struct ctl_scsiio *ctsio)
11373{
11374	int retval;
11375	const struct ctl_cmd_entry *entry;
11376
11377	retval = CTL_RETVAL_COMPLETE;
11378
11379	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11380
11381	entry = ctl_get_cmd_entry(ctsio);
11382
11383	/*
11384	 * If this I/O has been aborted, just send it straight to
11385	 * ctl_done() without executing it.
11386	 */
11387	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11388		ctl_done((union ctl_io *)ctsio);
11389		goto bailout;
11390	}
11391
11392	/*
11393	 * All the checks should have been handled by ctl_scsiio_precheck().
11394	 * We should be clear now to just execute the I/O.
11395	 */
11396	retval = entry->execute(ctsio);
11397
11398bailout:
11399	return (retval);
11400}
11401
11402/*
11403 * Since we only implement one target right now, a bus reset simply resets
11404 * our single target.
11405 */
11406static int
11407ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11408{
11409	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11410}
11411
11412static int
11413ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11414		 ctl_ua_type ua_type)
11415{
11416	struct ctl_lun *lun;
11417	int retval;
11418
11419	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11420		union ctl_ha_msg msg_info;
11421
11422		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11423		msg_info.hdr.nexus = io->io_hdr.nexus;
11424		if (ua_type==CTL_UA_TARG_RESET)
11425			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11426		else
11427			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11428		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11429		msg_info.hdr.original_sc = NULL;
11430		msg_info.hdr.serializing_sc = NULL;
11431		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11432		    (void *)&msg_info, sizeof(msg_info), 0)) {
11433		}
11434	}
11435	retval = 0;
11436
11437	mtx_lock(&ctl_softc->ctl_lock);
11438	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11439		retval += ctl_lun_reset(lun, io, ua_type);
11440	mtx_unlock(&ctl_softc->ctl_lock);
11441
11442	return (retval);
11443}
11444
11445/*
11446 * The LUN should always be set.  The I/O is optional, and is used to
11447 * distinguish between I/Os sent by this initiator, and by other
11448 * initiators.  We set unit attention for initiators other than this one.
11449 * SAM-3 is vague on this point.  It does say that a unit attention should
11450 * be established for other initiators when a LUN is reset (see section
11451 * 5.7.3), but it doesn't specifically say that the unit attention should
11452 * be established for this particular initiator when a LUN is reset.  Here
11453 * is the relevant text, from SAM-3 rev 8:
11454 *
11455 * 5.7.2 When a SCSI initiator port aborts its own tasks
11456 *
11457 * When a SCSI initiator port causes its own task(s) to be aborted, no
11458 * notification that the task(s) have been aborted shall be returned to
11459 * the SCSI initiator port other than the completion response for the
11460 * command or task management function action that caused the task(s) to
11461 * be aborted and notification(s) associated with related effects of the
11462 * action (e.g., a reset unit attention condition).
11463 *
11464 * XXX KDM for now, we're setting unit attention for all initiators.
11465 */
11466static int
11467ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11468{
11469	union ctl_io *xio;
11470#if 0
11471	uint32_t initindex;
11472#endif
11473	int i;
11474
11475	mtx_lock(&lun->lun_lock);
11476	/*
11477	 * Run through the OOA queue and abort each I/O.
11478	 */
11479#if 0
11480	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11481#endif
11482	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11483	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11484		xio->io_hdr.flags |= CTL_FLAG_ABORT;
11485	}
11486
11487	/*
11488	 * This version sets unit attention for every
11489	 */
11490#if 0
11491	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11492	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11493		if (initindex == i)
11494			continue;
11495		lun->pending_sense[i].ua_pending |= ua_type;
11496	}
11497#endif
11498
11499	/*
11500	 * A reset (any kind, really) clears reservations established with
11501	 * RESERVE/RELEASE.  It does not clear reservations established
11502	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11503	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11504	 * reservations made with the RESERVE/RELEASE commands, because
11505	 * those commands are obsolete in SPC-3.
11506	 */
11507	lun->flags &= ~CTL_LUN_RESERVED;
11508
11509	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11510		ctl_clear_mask(lun->have_ca, i);
11511		lun->pending_sense[i].ua_pending |= ua_type;
11512	}
11513	mtx_lock(&lun->lun_lock);
11514
11515	return (0);
11516}
11517
11518static int
11519ctl_abort_task(union ctl_io *io)
11520{
11521	union ctl_io *xio;
11522	struct ctl_lun *lun;
11523	struct ctl_softc *ctl_softc;
11524#if 0
11525	struct sbuf sb;
11526	char printbuf[128];
11527#endif
11528	int found;
11529	uint32_t targ_lun;
11530
11531	ctl_softc = control_softc;
11532	found = 0;
11533
11534	/*
11535	 * Look up the LUN.
11536	 */
11537	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11538	mtx_lock(&ctl_softc->ctl_lock);
11539	if ((targ_lun < CTL_MAX_LUNS)
11540	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11541		lun = ctl_softc->ctl_luns[targ_lun];
11542	else {
11543		mtx_unlock(&ctl_softc->ctl_lock);
11544		goto bailout;
11545	}
11546
11547#if 0
11548	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11549	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11550#endif
11551
11552	mtx_lock(&lun->lun_lock);
11553	mtx_unlock(&ctl_softc->ctl_lock);
11554	/*
11555	 * Run through the OOA queue and attempt to find the given I/O.
11556	 * The target port, initiator ID, tag type and tag number have to
11557	 * match the values that we got from the initiator.  If we have an
11558	 * untagged command to abort, simply abort the first untagged command
11559	 * we come to.  We only allow one untagged command at a time of course.
11560	 */
11561#if 0
11562	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11563#endif
11564	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11565	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11566#if 0
11567		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11568
11569		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11570			    lun->lun, xio->scsiio.tag_num,
11571			    xio->scsiio.tag_type,
11572			    (xio->io_hdr.blocked_links.tqe_prev
11573			    == NULL) ? "" : " BLOCKED",
11574			    (xio->io_hdr.flags &
11575			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11576			    (xio->io_hdr.flags &
11577			    CTL_FLAG_ABORT) ? " ABORT" : "",
11578			    (xio->io_hdr.flags &
11579			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11580		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11581		sbuf_finish(&sb);
11582		printf("%s\n", sbuf_data(&sb));
11583#endif
11584
11585		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
11586		 && (xio->io_hdr.nexus.initid.id ==
11587		     io->io_hdr.nexus.initid.id)) {
11588			/*
11589			 * If the abort says that the task is untagged, the
11590			 * task in the queue must be untagged.  Otherwise,
11591			 * we just check to see whether the tag numbers
11592			 * match.  This is because the QLogic firmware
11593			 * doesn't pass back the tag type in an abort
11594			 * request.
11595			 */
11596#if 0
11597			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11598			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11599			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11600#endif
11601			/*
11602			 * XXX KDM we've got problems with FC, because it
11603			 * doesn't send down a tag type with aborts.  So we
11604			 * can only really go by the tag number...
11605			 * This may cause problems with parallel SCSI.
11606			 * Need to figure that out!!
11607			 */
11608			if (xio->scsiio.tag_num == io->taskio.tag_num) {
11609				xio->io_hdr.flags |= CTL_FLAG_ABORT;
11610				found = 1;
11611				if ((io->io_hdr.flags &
11612				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
11613				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11614					union ctl_ha_msg msg_info;
11615
11616					io->io_hdr.flags |=
11617					                CTL_FLAG_SENT_2OTHER_SC;
11618					msg_info.hdr.nexus = io->io_hdr.nexus;
11619					msg_info.task.task_action =
11620						CTL_TASK_ABORT_TASK;
11621					msg_info.task.tag_num =
11622						io->taskio.tag_num;
11623					msg_info.task.tag_type =
11624						io->taskio.tag_type;
11625					msg_info.hdr.msg_type =
11626						CTL_MSG_MANAGE_TASKS;
11627					msg_info.hdr.original_sc = NULL;
11628					msg_info.hdr.serializing_sc = NULL;
11629#if 0
11630					printf("Sent Abort to other side\n");
11631#endif
11632					if (CTL_HA_STATUS_SUCCESS !=
11633					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11634		    				(void *)&msg_info,
11635						sizeof(msg_info), 0)) {
11636					}
11637				}
11638#if 0
11639				printf("ctl_abort_task: found I/O to abort\n");
11640#endif
11641				break;
11642			}
11643		}
11644	}
11645	mtx_unlock(&lun->lun_lock);
11646
11647bailout:
11648
11649	if (found == 0) {
11650		/*
11651		 * This isn't really an error.  It's entirely possible for
11652		 * the abort and command completion to cross on the wire.
11653		 * This is more of an informative/diagnostic error.
11654		 */
11655#if 0
11656		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11657		       "%d:%d:%d:%d tag %d type %d\n",
11658		       io->io_hdr.nexus.initid.id,
11659		       io->io_hdr.nexus.targ_port,
11660		       io->io_hdr.nexus.targ_target.id,
11661		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11662		       io->taskio.tag_type);
11663#endif
11664		return (1);
11665	} else
11666		return (0);
11667}
11668
11669/*
11670 * This routine cannot block!  It must be callable from an interrupt
11671 * handler as well as from the work thread.
11672 */
11673static void
11674ctl_run_task(union ctl_io *io)
11675{
11676	struct ctl_softc *ctl_softc;
11677	int retval;
11678	const char *task_desc;
11679
11680	CTL_DEBUG_PRINT(("ctl_run_task\n"));
11681
11682	ctl_softc = control_softc;
11683	retval = 0;
11684
11685	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11686	    ("ctl_run_task: Unextected io_type %d\n",
11687	     io->io_hdr.io_type));
11688
11689	task_desc = ctl_scsi_task_string(&io->taskio);
11690	if (task_desc != NULL) {
11691#ifdef NEEDTOPORT
11692		csevent_log(CSC_CTL | CSC_SHELF_SW |
11693			    CTL_TASK_REPORT,
11694			    csevent_LogType_Trace,
11695			    csevent_Severity_Information,
11696			    csevent_AlertLevel_Green,
11697			    csevent_FRU_Firmware,
11698			    csevent_FRU_Unknown,
11699			    "CTL: received task: %s",task_desc);
11700#endif
11701	} else {
11702#ifdef NEEDTOPORT
11703		csevent_log(CSC_CTL | CSC_SHELF_SW |
11704			    CTL_TASK_REPORT,
11705			    csevent_LogType_Trace,
11706			    csevent_Severity_Information,
11707			    csevent_AlertLevel_Green,
11708			    csevent_FRU_Firmware,
11709			    csevent_FRU_Unknown,
11710			    "CTL: received unknown task "
11711			    "type: %d (%#x)",
11712			    io->taskio.task_action,
11713			    io->taskio.task_action);
11714#endif
11715	}
11716	switch (io->taskio.task_action) {
11717	case CTL_TASK_ABORT_TASK:
11718		retval = ctl_abort_task(io);
11719		break;
11720	case CTL_TASK_ABORT_TASK_SET:
11721		break;
11722	case CTL_TASK_CLEAR_ACA:
11723		break;
11724	case CTL_TASK_CLEAR_TASK_SET:
11725		break;
11726	case CTL_TASK_LUN_RESET: {
11727		struct ctl_lun *lun;
11728		uint32_t targ_lun;
11729		int retval;
11730
11731		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11732		mtx_lock(&ctl_softc->ctl_lock);
11733		if ((targ_lun < CTL_MAX_LUNS)
11734		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11735			lun = ctl_softc->ctl_luns[targ_lun];
11736		else {
11737			mtx_unlock(&ctl_softc->ctl_lock);
11738			retval = 1;
11739			break;
11740		}
11741
11742		if (!(io->io_hdr.flags &
11743		    CTL_FLAG_FROM_OTHER_SC)) {
11744			union ctl_ha_msg msg_info;
11745
11746			io->io_hdr.flags |=
11747				CTL_FLAG_SENT_2OTHER_SC;
11748			msg_info.hdr.msg_type =
11749				CTL_MSG_MANAGE_TASKS;
11750			msg_info.hdr.nexus = io->io_hdr.nexus;
11751			msg_info.task.task_action =
11752				CTL_TASK_LUN_RESET;
11753			msg_info.hdr.original_sc = NULL;
11754			msg_info.hdr.serializing_sc = NULL;
11755			if (CTL_HA_STATUS_SUCCESS !=
11756			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11757			    (void *)&msg_info,
11758			    sizeof(msg_info), 0)) {
11759			}
11760		}
11761
11762		retval = ctl_lun_reset(lun, io,
11763				       CTL_UA_LUN_RESET);
11764		mtx_unlock(&ctl_softc->ctl_lock);
11765		break;
11766	}
11767	case CTL_TASK_TARGET_RESET:
11768		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
11769		break;
11770	case CTL_TASK_BUS_RESET:
11771		retval = ctl_bus_reset(ctl_softc, io);
11772		break;
11773	case CTL_TASK_PORT_LOGIN:
11774		break;
11775	case CTL_TASK_PORT_LOGOUT:
11776		break;
11777	default:
11778		printf("ctl_run_task: got unknown task management event %d\n",
11779		       io->taskio.task_action);
11780		break;
11781	}
11782	if (retval == 0)
11783		io->io_hdr.status = CTL_SUCCESS;
11784	else
11785		io->io_hdr.status = CTL_ERROR;
11786
11787	/*
11788	 * This will queue this I/O to the done queue, but the
11789	 * work thread won't be able to process it until we
11790	 * return and the lock is released.
11791	 */
11792	ctl_done(io);
11793}
11794
11795/*
11796 * For HA operation.  Handle commands that come in from the other
11797 * controller.
11798 */
11799static void
11800ctl_handle_isc(union ctl_io *io)
11801{
11802	int free_io;
11803	struct ctl_lun *lun;
11804	struct ctl_softc *ctl_softc;
11805	uint32_t targ_lun;
11806
11807	ctl_softc = control_softc;
11808
11809	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11810	lun = ctl_softc->ctl_luns[targ_lun];
11811
11812	switch (io->io_hdr.msg_type) {
11813	case CTL_MSG_SERIALIZE:
11814		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11815		break;
11816	case CTL_MSG_R2R: {
11817		const struct ctl_cmd_entry *entry;
11818
11819		/*
11820		 * This is only used in SER_ONLY mode.
11821		 */
11822		free_io = 0;
11823		entry = ctl_get_cmd_entry(&io->scsiio);
11824		mtx_lock(&lun->lun_lock);
11825		if (ctl_scsiio_lun_check(ctl_softc, lun,
11826		    entry, (struct ctl_scsiio *)io) != 0) {
11827			mtx_unlock(&lun->lun_lock);
11828			ctl_done(io);
11829			break;
11830		}
11831		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11832		mtx_unlock(&lun->lun_lock);
11833		ctl_enqueue_rtr(io);
11834		break;
11835	}
11836	case CTL_MSG_FINISH_IO:
11837		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
11838			free_io = 0;
11839			ctl_done(io);
11840		} else {
11841			free_io = 1;
11842			mtx_lock(&lun->lun_lock);
11843			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11844				     ooa_links);
11845			ctl_check_blocked(lun);
11846			mtx_unlock(&lun->lun_lock);
11847		}
11848		break;
11849	case CTL_MSG_PERS_ACTION:
11850		ctl_hndl_per_res_out_on_other_sc(
11851			(union ctl_ha_msg *)&io->presio.pr_msg);
11852		free_io = 1;
11853		break;
11854	case CTL_MSG_BAD_JUJU:
11855		free_io = 0;
11856		ctl_done(io);
11857		break;
11858	case CTL_MSG_DATAMOVE:
11859		/* Only used in XFER mode */
11860		free_io = 0;
11861		ctl_datamove_remote(io);
11862		break;
11863	case CTL_MSG_DATAMOVE_DONE:
11864		/* Only used in XFER mode */
11865		free_io = 0;
11866		io->scsiio.be_move_done(io);
11867		break;
11868	default:
11869		free_io = 1;
11870		printf("%s: Invalid message type %d\n",
11871		       __func__, io->io_hdr.msg_type);
11872		break;
11873	}
11874	if (free_io)
11875		ctl_free_io(io);
11876
11877}
11878
11879
11880/*
11881 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11882 * there is no match.
11883 */
11884static ctl_lun_error_pattern
11885ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11886{
11887	const struct ctl_cmd_entry *entry;
11888	ctl_lun_error_pattern filtered_pattern, pattern;
11889
11890	pattern = desc->error_pattern;
11891
11892	/*
11893	 * XXX KDM we need more data passed into this function to match a
11894	 * custom pattern, and we actually need to implement custom pattern
11895	 * matching.
11896	 */
11897	if (pattern & CTL_LUN_PAT_CMD)
11898		return (CTL_LUN_PAT_CMD);
11899
11900	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11901		return (CTL_LUN_PAT_ANY);
11902
11903	entry = ctl_get_cmd_entry(ctsio);
11904
11905	filtered_pattern = entry->pattern & pattern;
11906
11907	/*
11908	 * If the user requested specific flags in the pattern (e.g.
11909	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11910	 * flags.
11911	 *
11912	 * If the user did not specify any flags, it doesn't matter whether
11913	 * or not the command supports the flags.
11914	 */
11915	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11916	     (pattern & ~CTL_LUN_PAT_MASK))
11917		return (CTL_LUN_PAT_NONE);
11918
11919	/*
11920	 * If the user asked for a range check, see if the requested LBA
11921	 * range overlaps with this command's LBA range.
11922	 */
11923	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
11924		uint64_t lba1;
11925		uint32_t len1;
11926		ctl_action action;
11927		int retval;
11928
11929		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
11930		if (retval != 0)
11931			return (CTL_LUN_PAT_NONE);
11932
11933		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
11934					      desc->lba_range.len);
11935		/*
11936		 * A "pass" means that the LBA ranges don't overlap, so
11937		 * this doesn't match the user's range criteria.
11938		 */
11939		if (action == CTL_ACTION_PASS)
11940			return (CTL_LUN_PAT_NONE);
11941	}
11942
11943	return (filtered_pattern);
11944}
11945
11946static void
11947ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
11948{
11949	struct ctl_error_desc *desc, *desc2;
11950
11951	mtx_assert(&lun->lun_lock, MA_OWNED);
11952
11953	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
11954		ctl_lun_error_pattern pattern;
11955		/*
11956		 * Check to see whether this particular command matches
11957		 * the pattern in the descriptor.
11958		 */
11959		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
11960		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
11961			continue;
11962
11963		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
11964		case CTL_LUN_INJ_ABORTED:
11965			ctl_set_aborted(&io->scsiio);
11966			break;
11967		case CTL_LUN_INJ_MEDIUM_ERR:
11968			ctl_set_medium_error(&io->scsiio);
11969			break;
11970		case CTL_LUN_INJ_UA:
11971			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
11972			 * OCCURRED */
11973			ctl_set_ua(&io->scsiio, 0x29, 0x00);
11974			break;
11975		case CTL_LUN_INJ_CUSTOM:
11976			/*
11977			 * We're assuming the user knows what he is doing.
11978			 * Just copy the sense information without doing
11979			 * checks.
11980			 */
11981			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
11982			      ctl_min(sizeof(desc->custom_sense),
11983				      sizeof(io->scsiio.sense_data)));
11984			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
11985			io->scsiio.sense_len = SSD_FULL_SIZE;
11986			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11987			break;
11988		case CTL_LUN_INJ_NONE:
11989		default:
11990			/*
11991			 * If this is an error injection type we don't know
11992			 * about, clear the continuous flag (if it is set)
11993			 * so it will get deleted below.
11994			 */
11995			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
11996			break;
11997		}
11998		/*
11999		 * By default, each error injection action is a one-shot
12000		 */
12001		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12002			continue;
12003
12004		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12005
12006		free(desc, M_CTL);
12007	}
12008}
12009
12010#ifdef CTL_IO_DELAY
12011static void
12012ctl_datamove_timer_wakeup(void *arg)
12013{
12014	union ctl_io *io;
12015
12016	io = (union ctl_io *)arg;
12017
12018	ctl_datamove(io);
12019}
12020#endif /* CTL_IO_DELAY */
12021
12022void
12023ctl_datamove(union ctl_io *io)
12024{
12025	void (*fe_datamove)(union ctl_io *io);
12026
12027	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12028
12029	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12030
12031#ifdef CTL_TIME_IO
12032	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12033		char str[256];
12034		char path_str[64];
12035		struct sbuf sb;
12036
12037		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12038		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12039
12040		sbuf_cat(&sb, path_str);
12041		switch (io->io_hdr.io_type) {
12042		case CTL_IO_SCSI:
12043			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12044			sbuf_printf(&sb, "\n");
12045			sbuf_cat(&sb, path_str);
12046			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12047				    io->scsiio.tag_num, io->scsiio.tag_type);
12048			break;
12049		case CTL_IO_TASK:
12050			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12051				    "Tag Type: %d\n", io->taskio.task_action,
12052				    io->taskio.tag_num, io->taskio.tag_type);
12053			break;
12054		default:
12055			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12056			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12057			break;
12058		}
12059		sbuf_cat(&sb, path_str);
12060		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12061			    (intmax_t)time_uptime - io->io_hdr.start_time);
12062		sbuf_finish(&sb);
12063		printf("%s", sbuf_data(&sb));
12064	}
12065#endif /* CTL_TIME_IO */
12066
12067#ifdef CTL_IO_DELAY
12068	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12069		struct ctl_lun *lun;
12070
12071		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12072
12073		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12074	} else {
12075		struct ctl_lun *lun;
12076
12077		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12078		if ((lun != NULL)
12079		 && (lun->delay_info.datamove_delay > 0)) {
12080			struct callout *callout;
12081
12082			callout = (struct callout *)&io->io_hdr.timer_bytes;
12083			callout_init(callout, /*mpsafe*/ 1);
12084			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12085			callout_reset(callout,
12086				      lun->delay_info.datamove_delay * hz,
12087				      ctl_datamove_timer_wakeup, io);
12088			if (lun->delay_info.datamove_type ==
12089			    CTL_DELAY_TYPE_ONESHOT)
12090				lun->delay_info.datamove_delay = 0;
12091			return;
12092		}
12093	}
12094#endif
12095
12096	/*
12097	 * This command has been aborted.  Set the port status, so we fail
12098	 * the data move.
12099	 */
12100	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12101		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12102		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12103		       io->io_hdr.nexus.targ_port,
12104		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12105		       io->io_hdr.nexus.targ_lun);
12106		io->io_hdr.status = CTL_CMD_ABORTED;
12107		io->io_hdr.port_status = 31337;
12108		/*
12109		 * Note that the backend, in this case, will get the
12110		 * callback in its context.  In other cases it may get
12111		 * called in the frontend's interrupt thread context.
12112		 */
12113		io->scsiio.be_move_done(io);
12114		return;
12115	}
12116
12117	/*
12118	 * If we're in XFER mode and this I/O is from the other shelf
12119	 * controller, we need to send the DMA to the other side to
12120	 * actually transfer the data to/from the host.  In serialize only
12121	 * mode the transfer happens below CTL and ctl_datamove() is only
12122	 * called on the machine that originally received the I/O.
12123	 */
12124	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12125	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12126		union ctl_ha_msg msg;
12127		uint32_t sg_entries_sent;
12128		int do_sg_copy;
12129		int i;
12130
12131		memset(&msg, 0, sizeof(msg));
12132		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12133		msg.hdr.original_sc = io->io_hdr.original_sc;
12134		msg.hdr.serializing_sc = io;
12135		msg.hdr.nexus = io->io_hdr.nexus;
12136		msg.dt.flags = io->io_hdr.flags;
12137		/*
12138		 * We convert everything into a S/G list here.  We can't
12139		 * pass by reference, only by value between controllers.
12140		 * So we can't pass a pointer to the S/G list, only as many
12141		 * S/G entries as we can fit in here.  If it's possible for
12142		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12143		 * then we need to break this up into multiple transfers.
12144		 */
12145		if (io->scsiio.kern_sg_entries == 0) {
12146			msg.dt.kern_sg_entries = 1;
12147			/*
12148			 * If this is in cached memory, flush the cache
12149			 * before we send the DMA request to the other
12150			 * controller.  We want to do this in either the
12151			 * read or the write case.  The read case is
12152			 * straightforward.  In the write case, we want to
12153			 * make sure nothing is in the local cache that
12154			 * could overwrite the DMAed data.
12155			 */
12156			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12157				/*
12158				 * XXX KDM use bus_dmamap_sync() here.
12159				 */
12160			}
12161
12162			/*
12163			 * Convert to a physical address if this is a
12164			 * virtual address.
12165			 */
12166			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12167				msg.dt.sg_list[0].addr =
12168					io->scsiio.kern_data_ptr;
12169			} else {
12170				/*
12171				 * XXX KDM use busdma here!
12172				 */
12173#if 0
12174				msg.dt.sg_list[0].addr = (void *)
12175					vtophys(io->scsiio.kern_data_ptr);
12176#endif
12177			}
12178
12179			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12180			do_sg_copy = 0;
12181		} else {
12182			struct ctl_sg_entry *sgl;
12183
12184			do_sg_copy = 1;
12185			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12186			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12187			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12188				/*
12189				 * XXX KDM use bus_dmamap_sync() here.
12190				 */
12191			}
12192		}
12193
12194		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12195		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12196		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12197		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12198		msg.dt.sg_sequence = 0;
12199
12200		/*
12201		 * Loop until we've sent all of the S/G entries.  On the
12202		 * other end, we'll recompose these S/G entries into one
12203		 * contiguous list before passing it to the
12204		 */
12205		for (sg_entries_sent = 0; sg_entries_sent <
12206		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12207			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12208				sizeof(msg.dt.sg_list[0])),
12209				msg.dt.kern_sg_entries - sg_entries_sent);
12210
12211			if (do_sg_copy != 0) {
12212				struct ctl_sg_entry *sgl;
12213				int j;
12214
12215				sgl = (struct ctl_sg_entry *)
12216					io->scsiio.kern_data_ptr;
12217				/*
12218				 * If this is in cached memory, flush the cache
12219				 * before we send the DMA request to the other
12220				 * controller.  We want to do this in either
12221				 * the * read or the write case.  The read
12222				 * case is straightforward.  In the write
12223				 * case, we want to make sure nothing is
12224				 * in the local cache that could overwrite
12225				 * the DMAed data.
12226				 */
12227
12228				for (i = sg_entries_sent, j = 0;
12229				     i < msg.dt.cur_sg_entries; i++, j++) {
12230					if ((io->io_hdr.flags &
12231					     CTL_FLAG_NO_DATASYNC) == 0) {
12232						/*
12233						 * XXX KDM use bus_dmamap_sync()
12234						 */
12235					}
12236					if ((io->io_hdr.flags &
12237					     CTL_FLAG_BUS_ADDR) == 0) {
12238						/*
12239						 * XXX KDM use busdma.
12240						 */
12241#if 0
12242						msg.dt.sg_list[j].addr =(void *)
12243						       vtophys(sgl[i].addr);
12244#endif
12245					} else {
12246						msg.dt.sg_list[j].addr =
12247							sgl[i].addr;
12248					}
12249					msg.dt.sg_list[j].len = sgl[i].len;
12250				}
12251			}
12252
12253			sg_entries_sent += msg.dt.cur_sg_entries;
12254			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12255				msg.dt.sg_last = 1;
12256			else
12257				msg.dt.sg_last = 0;
12258
12259			/*
12260			 * XXX KDM drop and reacquire the lock here?
12261			 */
12262			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12263			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12264				/*
12265				 * XXX do something here.
12266				 */
12267			}
12268
12269			msg.dt.sent_sg_entries = sg_entries_sent;
12270		}
12271		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12272		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12273			ctl_failover_io(io, /*have_lock*/ 0);
12274
12275	} else {
12276
12277		/*
12278		 * Lookup the fe_datamove() function for this particular
12279		 * front end.
12280		 */
12281		fe_datamove =
12282		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12283
12284		fe_datamove(io);
12285	}
12286}
12287
12288static void
12289ctl_send_datamove_done(union ctl_io *io, int have_lock)
12290{
12291	union ctl_ha_msg msg;
12292	int isc_status;
12293
12294	memset(&msg, 0, sizeof(msg));
12295
12296	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12297	msg.hdr.original_sc = io;
12298	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12299	msg.hdr.nexus = io->io_hdr.nexus;
12300	msg.hdr.status = io->io_hdr.status;
12301	msg.scsi.tag_num = io->scsiio.tag_num;
12302	msg.scsi.tag_type = io->scsiio.tag_type;
12303	msg.scsi.scsi_status = io->scsiio.scsi_status;
12304	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12305	       sizeof(io->scsiio.sense_data));
12306	msg.scsi.sense_len = io->scsiio.sense_len;
12307	msg.scsi.sense_residual = io->scsiio.sense_residual;
12308	msg.scsi.fetd_status = io->io_hdr.port_status;
12309	msg.scsi.residual = io->scsiio.residual;
12310	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12311
12312	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12313		ctl_failover_io(io, /*have_lock*/ have_lock);
12314		return;
12315	}
12316
12317	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12318	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12319		/* XXX do something if this fails */
12320	}
12321
12322}
12323
12324/*
12325 * The DMA to the remote side is done, now we need to tell the other side
12326 * we're done so it can continue with its data movement.
12327 */
12328static void
12329ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12330{
12331	union ctl_io *io;
12332
12333	io = rq->context;
12334
12335	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12336		printf("%s: ISC DMA write failed with error %d", __func__,
12337		       rq->ret);
12338		ctl_set_internal_failure(&io->scsiio,
12339					 /*sks_valid*/ 1,
12340					 /*retry_count*/ rq->ret);
12341	}
12342
12343	ctl_dt_req_free(rq);
12344
12345	/*
12346	 * In this case, we had to malloc the memory locally.  Free it.
12347	 */
12348	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12349		int i;
12350		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12351			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12352	}
12353	/*
12354	 * The data is in local and remote memory, so now we need to send
12355	 * status (good or back) back to the other side.
12356	 */
12357	ctl_send_datamove_done(io, /*have_lock*/ 0);
12358}
12359
12360/*
12361 * We've moved the data from the host/controller into local memory.  Now we
12362 * need to push it over to the remote controller's memory.
12363 */
12364static int
12365ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12366{
12367	int retval;
12368
12369	retval = 0;
12370
12371	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12372					  ctl_datamove_remote_write_cb);
12373
12374	return (retval);
12375}
12376
12377static void
12378ctl_datamove_remote_write(union ctl_io *io)
12379{
12380	int retval;
12381	void (*fe_datamove)(union ctl_io *io);
12382
12383	/*
12384	 * - Get the data from the host/HBA into local memory.
12385	 * - DMA memory from the local controller to the remote controller.
12386	 * - Send status back to the remote controller.
12387	 */
12388
12389	retval = ctl_datamove_remote_sgl_setup(io);
12390	if (retval != 0)
12391		return;
12392
12393	/* Switch the pointer over so the FETD knows what to do */
12394	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12395
12396	/*
12397	 * Use a custom move done callback, since we need to send completion
12398	 * back to the other controller, not to the backend on this side.
12399	 */
12400	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12401
12402	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12403
12404	fe_datamove(io);
12405
12406	return;
12407
12408}
12409
12410static int
12411ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12412{
12413#if 0
12414	char str[256];
12415	char path_str[64];
12416	struct sbuf sb;
12417#endif
12418
12419	/*
12420	 * In this case, we had to malloc the memory locally.  Free it.
12421	 */
12422	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12423		int i;
12424		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12425			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12426	}
12427
12428#if 0
12429	scsi_path_string(io, path_str, sizeof(path_str));
12430	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12431	sbuf_cat(&sb, path_str);
12432	scsi_command_string(&io->scsiio, NULL, &sb);
12433	sbuf_printf(&sb, "\n");
12434	sbuf_cat(&sb, path_str);
12435	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12436		    io->scsiio.tag_num, io->scsiio.tag_type);
12437	sbuf_cat(&sb, path_str);
12438	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12439		    io->io_hdr.flags, io->io_hdr.status);
12440	sbuf_finish(&sb);
12441	printk("%s", sbuf_data(&sb));
12442#endif
12443
12444
12445	/*
12446	 * The read is done, now we need to send status (good or bad) back
12447	 * to the other side.
12448	 */
12449	ctl_send_datamove_done(io, /*have_lock*/ 0);
12450
12451	return (0);
12452}
12453
12454static void
12455ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12456{
12457	union ctl_io *io;
12458	void (*fe_datamove)(union ctl_io *io);
12459
12460	io = rq->context;
12461
12462	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12463		printf("%s: ISC DMA read failed with error %d", __func__,
12464		       rq->ret);
12465		ctl_set_internal_failure(&io->scsiio,
12466					 /*sks_valid*/ 1,
12467					 /*retry_count*/ rq->ret);
12468	}
12469
12470	ctl_dt_req_free(rq);
12471
12472	/* Switch the pointer over so the FETD knows what to do */
12473	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12474
12475	/*
12476	 * Use a custom move done callback, since we need to send completion
12477	 * back to the other controller, not to the backend on this side.
12478	 */
12479	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12480
12481	/* XXX KDM add checks like the ones in ctl_datamove? */
12482
12483	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12484
12485	fe_datamove(io);
12486}
12487
12488static int
12489ctl_datamove_remote_sgl_setup(union ctl_io *io)
12490{
12491	struct ctl_sg_entry *local_sglist, *remote_sglist;
12492	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12493	struct ctl_softc *softc;
12494	int retval;
12495	int i;
12496
12497	retval = 0;
12498	softc = control_softc;
12499
12500	local_sglist = io->io_hdr.local_sglist;
12501	local_dma_sglist = io->io_hdr.local_dma_sglist;
12502	remote_sglist = io->io_hdr.remote_sglist;
12503	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12504
12505	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12506		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12507			local_sglist[i].len = remote_sglist[i].len;
12508
12509			/*
12510			 * XXX Detect the situation where the RS-level I/O
12511			 * redirector on the other side has already read the
12512			 * data off of the AOR RS on this side, and
12513			 * transferred it to remote (mirror) memory on the
12514			 * other side.  Since we already have the data in
12515			 * memory here, we just need to use it.
12516			 *
12517			 * XXX KDM this can probably be removed once we
12518			 * get the cache device code in and take the
12519			 * current AOR implementation out.
12520			 */
12521#ifdef NEEDTOPORT
12522			if ((remote_sglist[i].addr >=
12523			     (void *)vtophys(softc->mirr->addr))
12524			 && (remote_sglist[i].addr <
12525			     ((void *)vtophys(softc->mirr->addr) +
12526			     CacheMirrorOffset))) {
12527				local_sglist[i].addr = remote_sglist[i].addr -
12528					CacheMirrorOffset;
12529				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12530				     CTL_FLAG_DATA_IN)
12531					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12532			} else {
12533				local_sglist[i].addr = remote_sglist[i].addr +
12534					CacheMirrorOffset;
12535			}
12536#endif
12537#if 0
12538			printf("%s: local %p, remote %p, len %d\n",
12539			       __func__, local_sglist[i].addr,
12540			       remote_sglist[i].addr, local_sglist[i].len);
12541#endif
12542		}
12543	} else {
12544		uint32_t len_to_go;
12545
12546		/*
12547		 * In this case, we don't have automatically allocated
12548		 * memory for this I/O on this controller.  This typically
12549		 * happens with internal CTL I/O -- e.g. inquiry, mode
12550		 * sense, etc.  Anything coming from RAIDCore will have
12551		 * a mirror area available.
12552		 */
12553		len_to_go = io->scsiio.kern_data_len;
12554
12555		/*
12556		 * Clear the no datasync flag, we have to use malloced
12557		 * buffers.
12558		 */
12559		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12560
12561		/*
12562		 * The difficult thing here is that the size of the various
12563		 * S/G segments may be different than the size from the
12564		 * remote controller.  That'll make it harder when DMAing
12565		 * the data back to the other side.
12566		 */
12567		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12568		     sizeof(io->io_hdr.remote_sglist[0])) &&
12569		     (len_to_go > 0); i++) {
12570			local_sglist[i].len = ctl_min(len_to_go, 131072);
12571			CTL_SIZE_8B(local_dma_sglist[i].len,
12572				    local_sglist[i].len);
12573			local_sglist[i].addr =
12574				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12575
12576			local_dma_sglist[i].addr = local_sglist[i].addr;
12577
12578			if (local_sglist[i].addr == NULL) {
12579				int j;
12580
12581				printf("malloc failed for %zd bytes!",
12582				       local_dma_sglist[i].len);
12583				for (j = 0; j < i; j++) {
12584					free(local_sglist[j].addr, M_CTL);
12585				}
12586				ctl_set_internal_failure(&io->scsiio,
12587							 /*sks_valid*/ 1,
12588							 /*retry_count*/ 4857);
12589				retval = 1;
12590				goto bailout_error;
12591
12592			}
12593			/* XXX KDM do we need a sync here? */
12594
12595			len_to_go -= local_sglist[i].len;
12596		}
12597		/*
12598		 * Reset the number of S/G entries accordingly.  The
12599		 * original number of S/G entries is available in
12600		 * rem_sg_entries.
12601		 */
12602		io->scsiio.kern_sg_entries = i;
12603
12604#if 0
12605		printf("%s: kern_sg_entries = %d\n", __func__,
12606		       io->scsiio.kern_sg_entries);
12607		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12608			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12609			       local_sglist[i].addr, local_sglist[i].len,
12610			       local_dma_sglist[i].len);
12611#endif
12612	}
12613
12614
12615	return (retval);
12616
12617bailout_error:
12618
12619	ctl_send_datamove_done(io, /*have_lock*/ 0);
12620
12621	return (retval);
12622}
12623
12624static int
12625ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12626			 ctl_ha_dt_cb callback)
12627{
12628	struct ctl_ha_dt_req *rq;
12629	struct ctl_sg_entry *remote_sglist, *local_sglist;
12630	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12631	uint32_t local_used, remote_used, total_used;
12632	int retval;
12633	int i, j;
12634
12635	retval = 0;
12636
12637	rq = ctl_dt_req_alloc();
12638
12639	/*
12640	 * If we failed to allocate the request, and if the DMA didn't fail
12641	 * anyway, set busy status.  This is just a resource allocation
12642	 * failure.
12643	 */
12644	if ((rq == NULL)
12645	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12646		ctl_set_busy(&io->scsiio);
12647
12648	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12649
12650		if (rq != NULL)
12651			ctl_dt_req_free(rq);
12652
12653		/*
12654		 * The data move failed.  We need to return status back
12655		 * to the other controller.  No point in trying to DMA
12656		 * data to the remote controller.
12657		 */
12658
12659		ctl_send_datamove_done(io, /*have_lock*/ 0);
12660
12661		retval = 1;
12662
12663		goto bailout;
12664	}
12665
12666	local_sglist = io->io_hdr.local_sglist;
12667	local_dma_sglist = io->io_hdr.local_dma_sglist;
12668	remote_sglist = io->io_hdr.remote_sglist;
12669	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12670	local_used = 0;
12671	remote_used = 0;
12672	total_used = 0;
12673
12674	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12675		rq->ret = CTL_HA_STATUS_SUCCESS;
12676		rq->context = io;
12677		callback(rq);
12678		goto bailout;
12679	}
12680
12681	/*
12682	 * Pull/push the data over the wire from/to the other controller.
12683	 * This takes into account the possibility that the local and
12684	 * remote sglists may not be identical in terms of the size of
12685	 * the elements and the number of elements.
12686	 *
12687	 * One fundamental assumption here is that the length allocated for
12688	 * both the local and remote sglists is identical.  Otherwise, we've
12689	 * essentially got a coding error of some sort.
12690	 */
12691	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12692		int isc_ret;
12693		uint32_t cur_len, dma_length;
12694		uint8_t *tmp_ptr;
12695
12696		rq->id = CTL_HA_DATA_CTL;
12697		rq->command = command;
12698		rq->context = io;
12699
12700		/*
12701		 * Both pointers should be aligned.  But it is possible
12702		 * that the allocation length is not.  They should both
12703		 * also have enough slack left over at the end, though,
12704		 * to round up to the next 8 byte boundary.
12705		 */
12706		cur_len = ctl_min(local_sglist[i].len - local_used,
12707				  remote_sglist[j].len - remote_used);
12708
12709		/*
12710		 * In this case, we have a size issue and need to decrease
12711		 * the size, except in the case where we actually have less
12712		 * than 8 bytes left.  In that case, we need to increase
12713		 * the DMA length to get the last bit.
12714		 */
12715		if ((cur_len & 0x7) != 0) {
12716			if (cur_len > 0x7) {
12717				cur_len = cur_len - (cur_len & 0x7);
12718				dma_length = cur_len;
12719			} else {
12720				CTL_SIZE_8B(dma_length, cur_len);
12721			}
12722
12723		} else
12724			dma_length = cur_len;
12725
12726		/*
12727		 * If we had to allocate memory for this I/O, instead of using
12728		 * the non-cached mirror memory, we'll need to flush the cache
12729		 * before trying to DMA to the other controller.
12730		 *
12731		 * We could end up doing this multiple times for the same
12732		 * segment if we have a larger local segment than remote
12733		 * segment.  That shouldn't be an issue.
12734		 */
12735		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12736			/*
12737			 * XXX KDM use bus_dmamap_sync() here.
12738			 */
12739		}
12740
12741		rq->size = dma_length;
12742
12743		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12744		tmp_ptr += local_used;
12745
12746		/* Use physical addresses when talking to ISC hardware */
12747		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12748			/* XXX KDM use busdma */
12749#if 0
12750			rq->local = vtophys(tmp_ptr);
12751#endif
12752		} else
12753			rq->local = tmp_ptr;
12754
12755		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12756		tmp_ptr += remote_used;
12757		rq->remote = tmp_ptr;
12758
12759		rq->callback = NULL;
12760
12761		local_used += cur_len;
12762		if (local_used >= local_sglist[i].len) {
12763			i++;
12764			local_used = 0;
12765		}
12766
12767		remote_used += cur_len;
12768		if (remote_used >= remote_sglist[j].len) {
12769			j++;
12770			remote_used = 0;
12771		}
12772		total_used += cur_len;
12773
12774		if (total_used >= io->scsiio.kern_data_len)
12775			rq->callback = callback;
12776
12777		if ((rq->size & 0x7) != 0) {
12778			printf("%s: warning: size %d is not on 8b boundary\n",
12779			       __func__, rq->size);
12780		}
12781		if (((uintptr_t)rq->local & 0x7) != 0) {
12782			printf("%s: warning: local %p not on 8b boundary\n",
12783			       __func__, rq->local);
12784		}
12785		if (((uintptr_t)rq->remote & 0x7) != 0) {
12786			printf("%s: warning: remote %p not on 8b boundary\n",
12787			       __func__, rq->local);
12788		}
12789#if 0
12790		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12791		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12792		       rq->local, rq->remote, rq->size);
12793#endif
12794
12795		isc_ret = ctl_dt_single(rq);
12796		if (isc_ret == CTL_HA_STATUS_WAIT)
12797			continue;
12798
12799		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12800			rq->ret = CTL_HA_STATUS_SUCCESS;
12801		} else {
12802			rq->ret = isc_ret;
12803		}
12804		callback(rq);
12805		goto bailout;
12806	}
12807
12808bailout:
12809	return (retval);
12810
12811}
12812
12813static void
12814ctl_datamove_remote_read(union ctl_io *io)
12815{
12816	int retval;
12817	int i;
12818
12819	/*
12820	 * This will send an error to the other controller in the case of a
12821	 * failure.
12822	 */
12823	retval = ctl_datamove_remote_sgl_setup(io);
12824	if (retval != 0)
12825		return;
12826
12827	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12828					  ctl_datamove_remote_read_cb);
12829	if ((retval != 0)
12830	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12831		/*
12832		 * Make sure we free memory if there was an error..  The
12833		 * ctl_datamove_remote_xfer() function will send the
12834		 * datamove done message, or call the callback with an
12835		 * error if there is a problem.
12836		 */
12837		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12838			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12839	}
12840
12841	return;
12842}
12843
12844/*
12845 * Process a datamove request from the other controller.  This is used for
12846 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12847 * first.  Once that is complete, the data gets DMAed into the remote
12848 * controller's memory.  For reads, we DMA from the remote controller's
12849 * memory into our memory first, and then move it out to the FETD.
12850 */
12851static void
12852ctl_datamove_remote(union ctl_io *io)
12853{
12854	struct ctl_softc *softc;
12855
12856	softc = control_softc;
12857
12858	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
12859
12860	/*
12861	 * Note that we look for an aborted I/O here, but don't do some of
12862	 * the other checks that ctl_datamove() normally does.  We don't
12863	 * need to run the task queue, because this I/O is on the ISC
12864	 * queue, which is executed by the work thread after the task queue.
12865	 * We don't need to run the datamove delay code, since that should
12866	 * have been done if need be on the other controller.
12867	 */
12868	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12869
12870		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
12871		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
12872		       io->io_hdr.nexus.targ_port,
12873		       io->io_hdr.nexus.targ_target.id,
12874		       io->io_hdr.nexus.targ_lun);
12875		io->io_hdr.status = CTL_CMD_ABORTED;
12876		io->io_hdr.port_status = 31338;
12877
12878		ctl_send_datamove_done(io, /*have_lock*/ 0);
12879
12880		return;
12881	}
12882
12883	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
12884		ctl_datamove_remote_write(io);
12885	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
12886		ctl_datamove_remote_read(io);
12887	} else {
12888		union ctl_ha_msg msg;
12889		struct scsi_sense_data *sense;
12890		uint8_t sks[3];
12891		int retry_count;
12892
12893		memset(&msg, 0, sizeof(msg));
12894
12895		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
12896		msg.hdr.status = CTL_SCSI_ERROR;
12897		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
12898
12899		retry_count = 4243;
12900
12901		sense = &msg.scsi.sense_data;
12902		sks[0] = SSD_SCS_VALID;
12903		sks[1] = (retry_count >> 8) & 0xff;
12904		sks[2] = retry_count & 0xff;
12905
12906		/* "Internal target failure" */
12907		scsi_set_sense_data(sense,
12908				    /*sense_format*/ SSD_TYPE_NONE,
12909				    /*current_error*/ 1,
12910				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
12911				    /*asc*/ 0x44,
12912				    /*ascq*/ 0x00,
12913				    /*type*/ SSD_ELEM_SKS,
12914				    /*size*/ sizeof(sks),
12915				    /*data*/ sks,
12916				    SSD_ELEM_NONE);
12917
12918		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12919		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12920			ctl_failover_io(io, /*have_lock*/ 1);
12921			return;
12922		}
12923
12924		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
12925		    CTL_HA_STATUS_SUCCESS) {
12926			/* XXX KDM what to do if this fails? */
12927		}
12928		return;
12929	}
12930
12931}
12932
12933static int
12934ctl_process_done(union ctl_io *io)
12935{
12936	struct ctl_lun *lun;
12937	struct ctl_softc *ctl_softc;
12938	void (*fe_done)(union ctl_io *io);
12939	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
12940
12941	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12942
12943	fe_done =
12944	    control_softc->ctl_ports[targ_port]->fe_done;
12945
12946#ifdef CTL_TIME_IO
12947	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12948		char str[256];
12949		char path_str[64];
12950		struct sbuf sb;
12951
12952		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12953		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12954
12955		sbuf_cat(&sb, path_str);
12956		switch (io->io_hdr.io_type) {
12957		case CTL_IO_SCSI:
12958			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12959			sbuf_printf(&sb, "\n");
12960			sbuf_cat(&sb, path_str);
12961			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12962				    io->scsiio.tag_num, io->scsiio.tag_type);
12963			break;
12964		case CTL_IO_TASK:
12965			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12966				    "Tag Type: %d\n", io->taskio.task_action,
12967				    io->taskio.tag_num, io->taskio.tag_type);
12968			break;
12969		default:
12970			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12971			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12972			break;
12973		}
12974		sbuf_cat(&sb, path_str);
12975		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12976			    (intmax_t)time_uptime - io->io_hdr.start_time);
12977		sbuf_finish(&sb);
12978		printf("%s", sbuf_data(&sb));
12979	}
12980#endif /* CTL_TIME_IO */
12981
12982	switch (io->io_hdr.io_type) {
12983	case CTL_IO_SCSI:
12984		break;
12985	case CTL_IO_TASK:
12986		if (bootverbose || verbose > 0)
12987			ctl_io_error_print(io, NULL);
12988		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12989			ctl_free_io(io);
12990		else
12991			fe_done(io);
12992		return (CTL_RETVAL_COMPLETE);
12993		break;
12994	default:
12995		printf("ctl_process_done: invalid io type %d\n",
12996		       io->io_hdr.io_type);
12997		panic("ctl_process_done: invalid io type %d\n",
12998		      io->io_hdr.io_type);
12999		break; /* NOTREACHED */
13000	}
13001
13002	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13003	if (lun == NULL) {
13004		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13005				 io->io_hdr.nexus.targ_mapped_lun));
13006		fe_done(io);
13007		goto bailout;
13008	}
13009	ctl_softc = lun->ctl_softc;
13010
13011	mtx_lock(&lun->lun_lock);
13012
13013	/*
13014	 * Check to see if we have any errors to inject here.  We only
13015	 * inject errors for commands that don't already have errors set.
13016	 */
13017	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13018	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13019		ctl_inject_error(lun, io);
13020
13021	/*
13022	 * XXX KDM how do we treat commands that aren't completed
13023	 * successfully?
13024	 *
13025	 * XXX KDM should we also track I/O latency?
13026	 */
13027	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13028	    io->io_hdr.io_type == CTL_IO_SCSI) {
13029#ifdef CTL_TIME_IO
13030		struct bintime cur_bt;
13031#endif
13032		int type;
13033
13034		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13035		    CTL_FLAG_DATA_IN)
13036			type = CTL_STATS_READ;
13037		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13038		    CTL_FLAG_DATA_OUT)
13039			type = CTL_STATS_WRITE;
13040		else
13041			type = CTL_STATS_NO_IO;
13042
13043		lun->stats.ports[targ_port].bytes[type] +=
13044		    io->scsiio.kern_total_len;
13045		lun->stats.ports[targ_port].operations[type]++;
13046#ifdef CTL_TIME_IO
13047		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13048		   &io->io_hdr.dma_bt);
13049		lun->stats.ports[targ_port].num_dmas[type] +=
13050		    io->io_hdr.num_dmas;
13051		getbintime(&cur_bt);
13052		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13053		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13054#endif
13055	}
13056
13057	/*
13058	 * Remove this from the OOA queue.
13059	 */
13060	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13061
13062	/*
13063	 * Run through the blocked queue on this LUN and see if anything
13064	 * has become unblocked, now that this transaction is done.
13065	 */
13066	ctl_check_blocked(lun);
13067
13068	/*
13069	 * If the LUN has been invalidated, free it if there is nothing
13070	 * left on its OOA queue.
13071	 */
13072	if ((lun->flags & CTL_LUN_INVALID)
13073	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13074		mtx_unlock(&lun->lun_lock);
13075		mtx_lock(&ctl_softc->ctl_lock);
13076		ctl_free_lun(lun);
13077		mtx_unlock(&ctl_softc->ctl_lock);
13078	} else
13079		mtx_unlock(&lun->lun_lock);
13080
13081	/*
13082	 * If this command has been aborted, make sure we set the status
13083	 * properly.  The FETD is responsible for freeing the I/O and doing
13084	 * whatever it needs to do to clean up its state.
13085	 */
13086	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13087		io->io_hdr.status = CTL_CMD_ABORTED;
13088
13089	/*
13090	 * We print out status for every task management command.  For SCSI
13091	 * commands, we filter out any unit attention errors; they happen
13092	 * on every boot, and would clutter up the log.  Note:  task
13093	 * management commands aren't printed here, they are printed above,
13094	 * since they should never even make it down here.
13095	 */
13096	switch (io->io_hdr.io_type) {
13097	case CTL_IO_SCSI: {
13098		int error_code, sense_key, asc, ascq;
13099
13100		sense_key = 0;
13101
13102		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13103		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13104			/*
13105			 * Since this is just for printing, no need to
13106			 * show errors here.
13107			 */
13108			scsi_extract_sense_len(&io->scsiio.sense_data,
13109					       io->scsiio.sense_len,
13110					       &error_code,
13111					       &sense_key,
13112					       &asc,
13113					       &ascq,
13114					       /*show_errors*/ 0);
13115		}
13116
13117		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13118		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13119		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13120		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13121
13122			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13123				ctl_softc->skipped_prints++;
13124			} else {
13125				uint32_t skipped_prints;
13126
13127				skipped_prints = ctl_softc->skipped_prints;
13128
13129				ctl_softc->skipped_prints = 0;
13130				ctl_softc->last_print_jiffies = time_uptime;
13131
13132				if (skipped_prints > 0) {
13133#ifdef NEEDTOPORT
13134					csevent_log(CSC_CTL | CSC_SHELF_SW |
13135					    CTL_ERROR_REPORT,
13136					    csevent_LogType_Trace,
13137					    csevent_Severity_Information,
13138					    csevent_AlertLevel_Green,
13139					    csevent_FRU_Firmware,
13140					    csevent_FRU_Unknown,
13141					    "High CTL error volume, %d prints "
13142					    "skipped", skipped_prints);
13143#endif
13144				}
13145				if (bootverbose || verbose > 0)
13146					ctl_io_error_print(io, NULL);
13147			}
13148		}
13149		break;
13150	}
13151	case CTL_IO_TASK:
13152		if (bootverbose || verbose > 0)
13153			ctl_io_error_print(io, NULL);
13154		break;
13155	default:
13156		break;
13157	}
13158
13159	/*
13160	 * Tell the FETD or the other shelf controller we're done with this
13161	 * command.  Note that only SCSI commands get to this point.  Task
13162	 * management commands are completed above.
13163	 *
13164	 * We only send status to the other controller if we're in XFER
13165	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13166	 * received the I/O (from CTL's perspective), and so the status is
13167	 * generated there.
13168	 *
13169	 * XXX KDM if we hold the lock here, we could cause a deadlock
13170	 * if the frontend comes back in in this context to queue
13171	 * something.
13172	 */
13173	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13174	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13175		union ctl_ha_msg msg;
13176
13177		memset(&msg, 0, sizeof(msg));
13178		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13179		msg.hdr.original_sc = io->io_hdr.original_sc;
13180		msg.hdr.nexus = io->io_hdr.nexus;
13181		msg.hdr.status = io->io_hdr.status;
13182		msg.scsi.scsi_status = io->scsiio.scsi_status;
13183		msg.scsi.tag_num = io->scsiio.tag_num;
13184		msg.scsi.tag_type = io->scsiio.tag_type;
13185		msg.scsi.sense_len = io->scsiio.sense_len;
13186		msg.scsi.sense_residual = io->scsiio.sense_residual;
13187		msg.scsi.residual = io->scsiio.residual;
13188		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13189		       sizeof(io->scsiio.sense_data));
13190		/*
13191		 * We copy this whether or not this is an I/O-related
13192		 * command.  Otherwise, we'd have to go and check to see
13193		 * whether it's a read/write command, and it really isn't
13194		 * worth it.
13195		 */
13196		memcpy(&msg.scsi.lbalen,
13197		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13198		       sizeof(msg.scsi.lbalen));
13199
13200		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13201				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13202			/* XXX do something here */
13203		}
13204
13205		ctl_free_io(io);
13206	} else
13207		fe_done(io);
13208
13209bailout:
13210
13211	return (CTL_RETVAL_COMPLETE);
13212}
13213
13214/*
13215 * Front end should call this if it doesn't do autosense.  When the request
13216 * sense comes back in from the initiator, we'll dequeue this and send it.
13217 */
13218int
13219ctl_queue_sense(union ctl_io *io)
13220{
13221	struct ctl_lun *lun;
13222	struct ctl_softc *ctl_softc;
13223	uint32_t initidx, targ_lun;
13224
13225	ctl_softc = control_softc;
13226
13227	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13228
13229	/*
13230	 * LUN lookup will likely move to the ctl_work_thread() once we
13231	 * have our new queueing infrastructure (that doesn't put things on
13232	 * a per-LUN queue initially).  That is so that we can handle
13233	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13234	 * can't deal with that right now.
13235	 */
13236	mtx_lock(&ctl_softc->ctl_lock);
13237
13238	/*
13239	 * If we don't have a LUN for this, just toss the sense
13240	 * information.
13241	 */
13242	targ_lun = io->io_hdr.nexus.targ_lun;
13243	if (io->io_hdr.nexus.lun_map_fn != NULL)
13244		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
13245	if ((targ_lun < CTL_MAX_LUNS)
13246	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13247		lun = ctl_softc->ctl_luns[targ_lun];
13248	else
13249		goto bailout;
13250
13251	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13252
13253	mtx_lock(&lun->lun_lock);
13254	/*
13255	 * Already have CA set for this LUN...toss the sense information.
13256	 */
13257	if (ctl_is_set(lun->have_ca, initidx)) {
13258		mtx_unlock(&lun->lun_lock);
13259		goto bailout;
13260	}
13261
13262	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13263	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
13264	       sizeof(io->scsiio.sense_data)));
13265	ctl_set_mask(lun->have_ca, initidx);
13266	mtx_unlock(&lun->lun_lock);
13267
13268bailout:
13269	mtx_unlock(&ctl_softc->ctl_lock);
13270
13271	ctl_free_io(io);
13272
13273	return (CTL_RETVAL_COMPLETE);
13274}
13275
13276/*
13277 * Primary command inlet from frontend ports.  All SCSI and task I/O
13278 * requests must go through this function.
13279 */
13280int
13281ctl_queue(union ctl_io *io)
13282{
13283	struct ctl_softc *ctl_softc;
13284
13285	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13286
13287	ctl_softc = control_softc;
13288
13289#ifdef CTL_TIME_IO
13290	io->io_hdr.start_time = time_uptime;
13291	getbintime(&io->io_hdr.start_bt);
13292#endif /* CTL_TIME_IO */
13293
13294	/* Map FE-specific LUN ID into global one. */
13295	if (io->io_hdr.nexus.lun_map_fn != NULL)
13296		io->io_hdr.nexus.targ_mapped_lun = io->io_hdr.nexus.lun_map_fn(
13297		    io->io_hdr.nexus.lun_map_arg, io->io_hdr.nexus.targ_lun);
13298	else
13299		io->io_hdr.nexus.targ_mapped_lun = io->io_hdr.nexus.targ_lun;
13300
13301	switch (io->io_hdr.io_type) {
13302	case CTL_IO_SCSI:
13303		ctl_enqueue_incoming(io);
13304		break;
13305	case CTL_IO_TASK:
13306		ctl_run_task(io);
13307		break;
13308	default:
13309		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13310		return (EINVAL);
13311	}
13312
13313	return (CTL_RETVAL_COMPLETE);
13314}
13315
13316#ifdef CTL_IO_DELAY
13317static void
13318ctl_done_timer_wakeup(void *arg)
13319{
13320	union ctl_io *io;
13321
13322	io = (union ctl_io *)arg;
13323	ctl_done(io);
13324}
13325#endif /* CTL_IO_DELAY */
13326
13327void
13328ctl_done(union ctl_io *io)
13329{
13330	struct ctl_softc *ctl_softc;
13331
13332	ctl_softc = control_softc;
13333
13334	/*
13335	 * Enable this to catch duplicate completion issues.
13336	 */
13337#if 0
13338	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13339		printf("%s: type %d msg %d cdb %x iptl: "
13340		       "%d:%d:%d:%d tag 0x%04x "
13341		       "flag %#x status %x\n",
13342			__func__,
13343			io->io_hdr.io_type,
13344			io->io_hdr.msg_type,
13345			io->scsiio.cdb[0],
13346			io->io_hdr.nexus.initid.id,
13347			io->io_hdr.nexus.targ_port,
13348			io->io_hdr.nexus.targ_target.id,
13349			io->io_hdr.nexus.targ_lun,
13350			(io->io_hdr.io_type ==
13351			CTL_IO_TASK) ?
13352			io->taskio.tag_num :
13353			io->scsiio.tag_num,
13354		        io->io_hdr.flags,
13355			io->io_hdr.status);
13356	} else
13357		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13358#endif
13359
13360	/*
13361	 * This is an internal copy of an I/O, and should not go through
13362	 * the normal done processing logic.
13363	 */
13364	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13365		return;
13366
13367	/*
13368	 * We need to send a msg to the serializing shelf to finish the IO
13369	 * as well.  We don't send a finish message to the other shelf if
13370	 * this is a task management command.  Task management commands
13371	 * aren't serialized in the OOA queue, but rather just executed on
13372	 * both shelf controllers for commands that originated on that
13373	 * controller.
13374	 */
13375	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13376	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13377		union ctl_ha_msg msg_io;
13378
13379		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13380		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13381		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13382		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13383		}
13384		/* continue on to finish IO */
13385	}
13386#ifdef CTL_IO_DELAY
13387	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13388		struct ctl_lun *lun;
13389
13390		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13391
13392		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13393	} else {
13394		struct ctl_lun *lun;
13395
13396		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13397
13398		if ((lun != NULL)
13399		 && (lun->delay_info.done_delay > 0)) {
13400			struct callout *callout;
13401
13402			callout = (struct callout *)&io->io_hdr.timer_bytes;
13403			callout_init(callout, /*mpsafe*/ 1);
13404			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13405			callout_reset(callout,
13406				      lun->delay_info.done_delay * hz,
13407				      ctl_done_timer_wakeup, io);
13408			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13409				lun->delay_info.done_delay = 0;
13410			return;
13411		}
13412	}
13413#endif /* CTL_IO_DELAY */
13414
13415	ctl_enqueue_done(io);
13416}
13417
13418int
13419ctl_isc(struct ctl_scsiio *ctsio)
13420{
13421	struct ctl_lun *lun;
13422	int retval;
13423
13424	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13425
13426	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13427
13428	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13429
13430	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13431
13432	return (retval);
13433}
13434
13435
13436static void
13437ctl_work_thread(void *arg)
13438{
13439	struct ctl_thread *thr = (struct ctl_thread *)arg;
13440	struct ctl_softc *softc = thr->ctl_softc;
13441	union ctl_io *io;
13442	int retval;
13443
13444	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13445
13446	for (;;) {
13447		retval = 0;
13448
13449		/*
13450		 * We handle the queues in this order:
13451		 * - ISC
13452		 * - done queue (to free up resources, unblock other commands)
13453		 * - RtR queue
13454		 * - incoming queue
13455		 *
13456		 * If those queues are empty, we break out of the loop and
13457		 * go to sleep.
13458		 */
13459		mtx_lock(&thr->queue_lock);
13460		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13461		if (io != NULL) {
13462			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13463			mtx_unlock(&thr->queue_lock);
13464			ctl_handle_isc(io);
13465			continue;
13466		}
13467		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13468		if (io != NULL) {
13469			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13470			/* clear any blocked commands, call fe_done */
13471			mtx_unlock(&thr->queue_lock);
13472			retval = ctl_process_done(io);
13473			continue;
13474		}
13475		if (!ctl_pause_rtr) {
13476			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13477			if (io != NULL) {
13478				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13479				mtx_unlock(&thr->queue_lock);
13480				retval = ctl_scsiio(&io->scsiio);
13481				if (retval != CTL_RETVAL_COMPLETE)
13482					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13483				continue;
13484			}
13485		}
13486		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13487		if (io != NULL) {
13488			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13489			mtx_unlock(&thr->queue_lock);
13490			ctl_scsiio_precheck(softc, &io->scsiio);
13491			continue;
13492		}
13493
13494		/* Sleep until we have something to do. */
13495		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13496	}
13497}
13498
13499static void
13500ctl_lun_thread(void *arg)
13501{
13502	struct ctl_softc *softc = (struct ctl_softc *)arg;
13503	struct ctl_be_lun *be_lun;
13504	int retval;
13505
13506	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13507
13508	for (;;) {
13509		retval = 0;
13510		mtx_lock(&softc->ctl_lock);
13511		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13512		if (be_lun != NULL) {
13513			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13514			mtx_unlock(&softc->ctl_lock);
13515			ctl_create_lun(be_lun);
13516			continue;
13517		}
13518
13519		/* Sleep until we have something to do. */
13520		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13521		    PDROP | PRIBIO, "-", 0);
13522	}
13523}
13524
13525static void
13526ctl_enqueue_incoming(union ctl_io *io)
13527{
13528	struct ctl_softc *softc = control_softc;
13529	struct ctl_thread *thr;
13530
13531	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13532	mtx_lock(&thr->queue_lock);
13533	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13534	mtx_unlock(&thr->queue_lock);
13535	wakeup(thr);
13536}
13537
13538static void
13539ctl_enqueue_rtr(union ctl_io *io)
13540{
13541	struct ctl_softc *softc = control_softc;
13542	struct ctl_thread *thr;
13543
13544	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13545	mtx_lock(&thr->queue_lock);
13546	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13547	mtx_unlock(&thr->queue_lock);
13548	wakeup(thr);
13549}
13550
13551static void
13552ctl_enqueue_done(union ctl_io *io)
13553{
13554	struct ctl_softc *softc = control_softc;
13555	struct ctl_thread *thr;
13556
13557	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13558	mtx_lock(&thr->queue_lock);
13559	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13560	mtx_unlock(&thr->queue_lock);
13561	wakeup(thr);
13562}
13563
13564static void
13565ctl_enqueue_isc(union ctl_io *io)
13566{
13567	struct ctl_softc *softc = control_softc;
13568	struct ctl_thread *thr;
13569
13570	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13571	mtx_lock(&thr->queue_lock);
13572	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13573	mtx_unlock(&thr->queue_lock);
13574	wakeup(thr);
13575}
13576
13577/* Initialization and failover */
13578
13579void
13580ctl_init_isc_msg(void)
13581{
13582	printf("CTL: Still calling this thing\n");
13583}
13584
13585/*
13586 * Init component
13587 * 	Initializes component into configuration defined by bootMode
13588 *	(see hasc-sv.c)
13589 *  	returns hasc_Status:
13590 * 		OK
13591 *		ERROR - fatal error
13592 */
13593static ctl_ha_comp_status
13594ctl_isc_init(struct ctl_ha_component *c)
13595{
13596	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13597
13598	c->status = ret;
13599	return ret;
13600}
13601
13602/* Start component
13603 * 	Starts component in state requested. If component starts successfully,
13604 *	it must set its own state to the requestrd state
13605 *	When requested state is HASC_STATE_HA, the component may refine it
13606 * 	by adding _SLAVE or _MASTER flags.
13607 *	Currently allowed state transitions are:
13608 *	UNKNOWN->HA		- initial startup
13609 *	UNKNOWN->SINGLE - initial startup when no parter detected
13610 *	HA->SINGLE		- failover
13611 * returns ctl_ha_comp_status:
13612 * 		OK	- component successfully started in requested state
13613 *		FAILED  - could not start the requested state, failover may
13614 * 			  be possible
13615 *		ERROR	- fatal error detected, no future startup possible
13616 */
13617static ctl_ha_comp_status
13618ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13619{
13620	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13621
13622	printf("%s: go\n", __func__);
13623
13624	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13625	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13626		ctl_is_single = 0;
13627		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13628		    != CTL_HA_STATUS_SUCCESS) {
13629			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13630			ret = CTL_HA_COMP_STATUS_ERROR;
13631		}
13632	} else if (CTL_HA_STATE_IS_HA(c->state)
13633		&& CTL_HA_STATE_IS_SINGLE(state)){
13634		// HA->SINGLE transition
13635	        ctl_failover();
13636		ctl_is_single = 1;
13637	} else {
13638		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13639		       c->state, state);
13640		ret = CTL_HA_COMP_STATUS_ERROR;
13641	}
13642	if (CTL_HA_STATE_IS_SINGLE(state))
13643		ctl_is_single = 1;
13644
13645	c->state = state;
13646	c->status = ret;
13647	return ret;
13648}
13649
13650/*
13651 * Quiesce component
13652 * The component must clear any error conditions (set status to OK) and
13653 * prepare itself to another Start call
13654 * returns ctl_ha_comp_status:
13655 * 	OK
13656 *	ERROR
13657 */
13658static ctl_ha_comp_status
13659ctl_isc_quiesce(struct ctl_ha_component *c)
13660{
13661	int ret = CTL_HA_COMP_STATUS_OK;
13662
13663	ctl_pause_rtr = 1;
13664	c->status = ret;
13665	return ret;
13666}
13667
13668struct ctl_ha_component ctl_ha_component_ctlisc =
13669{
13670	.name = "CTL ISC",
13671	.state = CTL_HA_STATE_UNKNOWN,
13672	.init = ctl_isc_init,
13673	.start = ctl_isc_start,
13674	.quiesce = ctl_isc_quiesce
13675};
13676
13677/*
13678 *  vim: ts=8
13679 */
13680