ctl.c revision 269149
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 269149 2014-07-27 06:49:55Z 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	/*flags4*/SCP_TAS,
286	/*aen_holdoff_period*/{0, 0},
287	/*busy_timeout_period*/{0, 0},
288	/*extended_selftest_completion_time*/{0, 0}
289};
290
291static struct scsi_control_page control_page_changeable = {
292	/*page_code*/SMS_CONTROL_MODE_PAGE,
293	/*page_length*/sizeof(struct scsi_control_page) - 2,
294	/*rlec*/SCP_DSENSE,
295	/*queue_flags*/0,
296	/*eca_and_aen*/0,
297	/*flags4*/0,
298	/*aen_holdoff_period*/{0, 0},
299	/*busy_timeout_period*/{0, 0},
300	/*extended_selftest_completion_time*/{0, 0}
301};
302
303
304/*
305 * XXX KDM move these into the softc.
306 */
307static int rcv_sync_msg;
308static int persis_offset;
309static uint8_t ctl_pause_rtr;
310static int     ctl_is_single = 1;
311static int     index_to_aps_page;
312
313SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314static int worker_threads = -1;
315SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316    &worker_threads, 1, "Number of worker threads");
317static int verbose = 0;
318SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319    &verbose, 0, "Show SCSI errors returned to initiator");
320
321/*
322 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0) and
324 * Logical Block Provisioning (0xB2)
325 */
326#define SCSI_EVPD_NUM_SUPPORTED_PAGES	7
327
328static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
329				  int param);
330static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
331static int ctl_init(void);
332void ctl_shutdown(void);
333static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
334static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
335static void ctl_ioctl_online(void *arg);
336static void ctl_ioctl_offline(void *arg);
337static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
338static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
339static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
340static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
341static int ctl_ioctl_submit_wait(union ctl_io *io);
342static void ctl_ioctl_datamove(union ctl_io *io);
343static void ctl_ioctl_done(union ctl_io *io);
344static void ctl_ioctl_hard_startstop_callback(void *arg,
345					      struct cfi_metatask *metatask);
346static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
347static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
348			      struct ctl_ooa *ooa_hdr,
349			      struct ctl_ooa_entry *kern_entries);
350static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
351		     struct thread *td);
352static uint32_t ctl_map_lun(int port_num, uint32_t lun);
353static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
354#ifdef unused
355static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
356				   uint32_t targ_target, uint32_t targ_lun,
357				   int can_wait);
358static void ctl_kfree_io(union ctl_io *io);
359#endif /* unused */
360static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
361			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
362static int ctl_free_lun(struct ctl_lun *lun);
363static void ctl_create_lun(struct ctl_be_lun *be_lun);
364/**
365static void ctl_failover_change_pages(struct ctl_softc *softc,
366				      struct ctl_scsiio *ctsio, int master);
367**/
368
369static int ctl_do_mode_select(union ctl_io *io);
370static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
371			   uint64_t res_key, uint64_t sa_res_key,
372			   uint8_t type, uint32_t residx,
373			   struct ctl_scsiio *ctsio,
374			   struct scsi_per_res_out *cdb,
375			   struct scsi_per_res_out_parms* param);
376static void ctl_pro_preempt_other(struct ctl_lun *lun,
377				  union ctl_ha_msg *msg);
378static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
379static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
380static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
381static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
382static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
383					 int alloc_len);
384static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
385					 int alloc_len);
386static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
387static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
388static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
389static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
390static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
391static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
392					 union ctl_io *ooa_io);
393static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
394				union ctl_io *starting_io);
395static int ctl_check_blocked(struct ctl_lun *lun);
396static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
397				struct ctl_lun *lun,
398				const struct ctl_cmd_entry *entry,
399				struct ctl_scsiio *ctsio);
400//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
401static void ctl_failover(void);
402static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
403			       struct ctl_scsiio *ctsio);
404static int ctl_scsiio(struct ctl_scsiio *ctsio);
405
406static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
407static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
408			    ctl_ua_type ua_type);
409static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
410			 ctl_ua_type ua_type);
411static int ctl_abort_task(union ctl_io *io);
412static int ctl_abort_task_set(union ctl_io *io);
413static int ctl_i_t_nexus_reset(union ctl_io *io);
414static void ctl_run_task(union ctl_io *io);
415#ifdef CTL_IO_DELAY
416static void ctl_datamove_timer_wakeup(void *arg);
417static void ctl_done_timer_wakeup(void *arg);
418#endif /* CTL_IO_DELAY */
419
420static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
421static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
422static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
423static void ctl_datamove_remote_write(union ctl_io *io);
424static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
425static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
426static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
427static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
428				    ctl_ha_dt_cb callback);
429static void ctl_datamove_remote_read(union ctl_io *io);
430static void ctl_datamove_remote(union ctl_io *io);
431static int ctl_process_done(union ctl_io *io);
432static void ctl_lun_thread(void *arg);
433static void ctl_work_thread(void *arg);
434static void ctl_enqueue_incoming(union ctl_io *io);
435static void ctl_enqueue_rtr(union ctl_io *io);
436static void ctl_enqueue_done(union ctl_io *io);
437static void ctl_enqueue_isc(union ctl_io *io);
438static const struct ctl_cmd_entry *
439    ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
440static const struct ctl_cmd_entry *
441    ctl_validate_command(struct ctl_scsiio *ctsio);
442static int ctl_cmd_applicable(uint8_t lun_type,
443    const struct ctl_cmd_entry *entry);
444
445/*
446 * Load the serialization table.  This isn't very pretty, but is probably
447 * the easiest way to do it.
448 */
449#include "ctl_ser_table.c"
450
451/*
452 * We only need to define open, close and ioctl routines for this driver.
453 */
454static struct cdevsw ctl_cdevsw = {
455	.d_version =	D_VERSION,
456	.d_flags =	0,
457	.d_open =	ctl_open,
458	.d_close =	ctl_close,
459	.d_ioctl =	ctl_ioctl,
460	.d_name =	"ctl",
461};
462
463
464MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
465MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
466
467static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
468
469static moduledata_t ctl_moduledata = {
470	"ctl",
471	ctl_module_event_handler,
472	NULL
473};
474
475DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
476MODULE_VERSION(ctl, 1);
477
478static struct ctl_frontend ioctl_frontend =
479{
480	.name = "ioctl",
481};
482
483static void
484ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
485			    union ctl_ha_msg *msg_info)
486{
487	struct ctl_scsiio *ctsio;
488
489	if (msg_info->hdr.original_sc == NULL) {
490		printf("%s: original_sc == NULL!\n", __func__);
491		/* XXX KDM now what? */
492		return;
493	}
494
495	ctsio = &msg_info->hdr.original_sc->scsiio;
496	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
497	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
498	ctsio->io_hdr.status = msg_info->hdr.status;
499	ctsio->scsi_status = msg_info->scsi.scsi_status;
500	ctsio->sense_len = msg_info->scsi.sense_len;
501	ctsio->sense_residual = msg_info->scsi.sense_residual;
502	ctsio->residual = msg_info->scsi.residual;
503	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
504	       sizeof(ctsio->sense_data));
505	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
506	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
507	ctl_enqueue_isc((union ctl_io *)ctsio);
508}
509
510static void
511ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
512				union ctl_ha_msg *msg_info)
513{
514	struct ctl_scsiio *ctsio;
515
516	if (msg_info->hdr.serializing_sc == NULL) {
517		printf("%s: serializing_sc == NULL!\n", __func__);
518		/* XXX KDM now what? */
519		return;
520	}
521
522	ctsio = &msg_info->hdr.serializing_sc->scsiio;
523#if 0
524	/*
525	 * Attempt to catch the situation where an I/O has
526	 * been freed, and we're using it again.
527	 */
528	if (ctsio->io_hdr.io_type == 0xff) {
529		union ctl_io *tmp_io;
530		tmp_io = (union ctl_io *)ctsio;
531		printf("%s: %p use after free!\n", __func__,
532		       ctsio);
533		printf("%s: type %d msg %d cdb %x iptl: "
534		       "%d:%d:%d:%d tag 0x%04x "
535		       "flag %#x status %x\n",
536			__func__,
537			tmp_io->io_hdr.io_type,
538			tmp_io->io_hdr.msg_type,
539			tmp_io->scsiio.cdb[0],
540			tmp_io->io_hdr.nexus.initid.id,
541			tmp_io->io_hdr.nexus.targ_port,
542			tmp_io->io_hdr.nexus.targ_target.id,
543			tmp_io->io_hdr.nexus.targ_lun,
544			(tmp_io->io_hdr.io_type ==
545			CTL_IO_TASK) ?
546			tmp_io->taskio.tag_num :
547			tmp_io->scsiio.tag_num,
548		        tmp_io->io_hdr.flags,
549			tmp_io->io_hdr.status);
550	}
551#endif
552	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
553	ctl_enqueue_isc((union ctl_io *)ctsio);
554}
555
556/*
557 * ISC (Inter Shelf Communication) event handler.  Events from the HA
558 * subsystem come in here.
559 */
560static void
561ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
562{
563	struct ctl_softc *ctl_softc;
564	union ctl_io *io;
565	struct ctl_prio *presio;
566	ctl_ha_status isc_status;
567
568	ctl_softc = control_softc;
569	io = NULL;
570
571
572#if 0
573	printf("CTL: Isc Msg event %d\n", event);
574#endif
575	if (event == CTL_HA_EVT_MSG_RECV) {
576		union ctl_ha_msg msg_info;
577
578		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
579					     sizeof(msg_info), /*wait*/ 0);
580#if 0
581		printf("CTL: msg_type %d\n", msg_info.msg_type);
582#endif
583		if (isc_status != 0) {
584			printf("Error receiving message, status = %d\n",
585			       isc_status);
586			return;
587		}
588
589		switch (msg_info.hdr.msg_type) {
590		case CTL_MSG_SERIALIZE:
591#if 0
592			printf("Serialize\n");
593#endif
594			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
595			if (io == NULL) {
596				printf("ctl_isc_event_handler: can't allocate "
597				       "ctl_io!\n");
598				/* Bad Juju */
599				/* Need to set busy and send msg back */
600				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
601				msg_info.hdr.status = CTL_SCSI_ERROR;
602				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
603				msg_info.scsi.sense_len = 0;
604			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
605				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
606				}
607				goto bailout;
608			}
609			ctl_zero_io(io);
610			// populate ctsio from msg_info
611			io->io_hdr.io_type = CTL_IO_SCSI;
612			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
613			io->io_hdr.original_sc = msg_info.hdr.original_sc;
614#if 0
615			printf("pOrig %x\n", (int)msg_info.original_sc);
616#endif
617			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
618					    CTL_FLAG_IO_ACTIVE;
619			/*
620			 * If we're in serialization-only mode, we don't
621			 * want to go through full done processing.  Thus
622			 * the COPY flag.
623			 *
624			 * XXX KDM add another flag that is more specific.
625			 */
626			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
627				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
628			io->io_hdr.nexus = msg_info.hdr.nexus;
629#if 0
630			printf("targ %d, port %d, iid %d, lun %d\n",
631			       io->io_hdr.nexus.targ_target.id,
632			       io->io_hdr.nexus.targ_port,
633			       io->io_hdr.nexus.initid.id,
634			       io->io_hdr.nexus.targ_lun);
635#endif
636			io->scsiio.tag_num = msg_info.scsi.tag_num;
637			io->scsiio.tag_type = msg_info.scsi.tag_type;
638			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
639			       CTL_MAX_CDBLEN);
640			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
641				const struct ctl_cmd_entry *entry;
642
643				entry = ctl_get_cmd_entry(&io->scsiio);
644				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
645				io->io_hdr.flags |=
646					entry->flags & CTL_FLAG_DATA_MASK;
647			}
648			ctl_enqueue_isc(io);
649			break;
650
651		/* Performed on the Originating SC, XFER mode only */
652		case CTL_MSG_DATAMOVE: {
653			struct ctl_sg_entry *sgl;
654			int i, j;
655
656			io = msg_info.hdr.original_sc;
657			if (io == NULL) {
658				printf("%s: original_sc == NULL!\n", __func__);
659				/* XXX KDM do something here */
660				break;
661			}
662			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
663			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
664			/*
665			 * Keep track of this, we need to send it back over
666			 * when the datamove is complete.
667			 */
668			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
669
670			if (msg_info.dt.sg_sequence == 0) {
671				/*
672				 * XXX KDM we use the preallocated S/G list
673				 * here, but we'll need to change this to
674				 * dynamic allocation if we need larger S/G
675				 * lists.
676				 */
677				if (msg_info.dt.kern_sg_entries >
678				    sizeof(io->io_hdr.remote_sglist) /
679				    sizeof(io->io_hdr.remote_sglist[0])) {
680					printf("%s: number of S/G entries "
681					    "needed %u > allocated num %zd\n",
682					    __func__,
683					    msg_info.dt.kern_sg_entries,
684					    sizeof(io->io_hdr.remote_sglist)/
685					    sizeof(io->io_hdr.remote_sglist[0]));
686
687					/*
688					 * XXX KDM send a message back to
689					 * the other side to shut down the
690					 * DMA.  The error will come back
691					 * through via the normal channel.
692					 */
693					break;
694				}
695				sgl = io->io_hdr.remote_sglist;
696				memset(sgl, 0,
697				       sizeof(io->io_hdr.remote_sglist));
698
699				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
700
701				io->scsiio.kern_sg_entries =
702					msg_info.dt.kern_sg_entries;
703				io->scsiio.rem_sg_entries =
704					msg_info.dt.kern_sg_entries;
705				io->scsiio.kern_data_len =
706					msg_info.dt.kern_data_len;
707				io->scsiio.kern_total_len =
708					msg_info.dt.kern_total_len;
709				io->scsiio.kern_data_resid =
710					msg_info.dt.kern_data_resid;
711				io->scsiio.kern_rel_offset =
712					msg_info.dt.kern_rel_offset;
713				/*
714				 * Clear out per-DMA flags.
715				 */
716				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
717				/*
718				 * Add per-DMA flags that are set for this
719				 * particular DMA request.
720				 */
721				io->io_hdr.flags |= msg_info.dt.flags &
722						    CTL_FLAG_RDMA_MASK;
723			} else
724				sgl = (struct ctl_sg_entry *)
725					io->scsiio.kern_data_ptr;
726
727			for (i = msg_info.dt.sent_sg_entries, j = 0;
728			     i < (msg_info.dt.sent_sg_entries +
729			     msg_info.dt.cur_sg_entries); i++, j++) {
730				sgl[i].addr = msg_info.dt.sg_list[j].addr;
731				sgl[i].len = msg_info.dt.sg_list[j].len;
732
733#if 0
734				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
735				       __func__,
736				       msg_info.dt.sg_list[j].addr,
737				       msg_info.dt.sg_list[j].len,
738				       sgl[i].addr, sgl[i].len, j, i);
739#endif
740			}
741#if 0
742			memcpy(&sgl[msg_info.dt.sent_sg_entries],
743			       msg_info.dt.sg_list,
744			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
745#endif
746
747			/*
748			 * If this is the last piece of the I/O, we've got
749			 * the full S/G list.  Queue processing in the thread.
750			 * Otherwise wait for the next piece.
751			 */
752			if (msg_info.dt.sg_last != 0)
753				ctl_enqueue_isc(io);
754			break;
755		}
756		/* Performed on the Serializing (primary) SC, XFER mode only */
757		case CTL_MSG_DATAMOVE_DONE: {
758			if (msg_info.hdr.serializing_sc == NULL) {
759				printf("%s: serializing_sc == NULL!\n",
760				       __func__);
761				/* XXX KDM now what? */
762				break;
763			}
764			/*
765			 * We grab the sense information here in case
766			 * there was a failure, so we can return status
767			 * back to the initiator.
768			 */
769			io = msg_info.hdr.serializing_sc;
770			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
771			io->io_hdr.status = msg_info.hdr.status;
772			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
773			io->scsiio.sense_len = msg_info.scsi.sense_len;
774			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
775			io->io_hdr.port_status = msg_info.scsi.fetd_status;
776			io->scsiio.residual = msg_info.scsi.residual;
777			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
778			       sizeof(io->scsiio.sense_data));
779			ctl_enqueue_isc(io);
780			break;
781		}
782
783		/* Preformed on Originating SC, SER_ONLY mode */
784		case CTL_MSG_R2R:
785			io = msg_info.hdr.original_sc;
786			if (io == NULL) {
787				printf("%s: Major Bummer\n", __func__);
788				return;
789			} else {
790#if 0
791				printf("pOrig %x\n",(int) ctsio);
792#endif
793			}
794			io->io_hdr.msg_type = CTL_MSG_R2R;
795			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
796			ctl_enqueue_isc(io);
797			break;
798
799		/*
800		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
801		 * mode.
802		 * Performed on the Originating (i.e. secondary) SC in XFER
803		 * mode
804		 */
805		case CTL_MSG_FINISH_IO:
806			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
807				ctl_isc_handler_finish_xfer(ctl_softc,
808							    &msg_info);
809			else
810				ctl_isc_handler_finish_ser_only(ctl_softc,
811								&msg_info);
812			break;
813
814		/* Preformed on Originating SC */
815		case CTL_MSG_BAD_JUJU:
816			io = msg_info.hdr.original_sc;
817			if (io == NULL) {
818				printf("%s: Bad JUJU!, original_sc is NULL!\n",
819				       __func__);
820				break;
821			}
822			ctl_copy_sense_data(&msg_info, io);
823			/*
824			 * IO should have already been cleaned up on other
825			 * SC so clear this flag so we won't send a message
826			 * back to finish the IO there.
827			 */
828			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
829			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
830
831			/* io = msg_info.hdr.serializing_sc; */
832			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
833			ctl_enqueue_isc(io);
834			break;
835
836		/* Handle resets sent from the other side */
837		case CTL_MSG_MANAGE_TASKS: {
838			struct ctl_taskio *taskio;
839			taskio = (struct ctl_taskio *)ctl_alloc_io(
840				(void *)ctl_softc->othersc_pool);
841			if (taskio == NULL) {
842				printf("ctl_isc_event_handler: can't allocate "
843				       "ctl_io!\n");
844				/* Bad Juju */
845				/* should I just call the proper reset func
846				   here??? */
847				goto bailout;
848			}
849			ctl_zero_io((union ctl_io *)taskio);
850			taskio->io_hdr.io_type = CTL_IO_TASK;
851			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
852			taskio->io_hdr.nexus = msg_info.hdr.nexus;
853			taskio->task_action = msg_info.task.task_action;
854			taskio->tag_num = msg_info.task.tag_num;
855			taskio->tag_type = msg_info.task.tag_type;
856#ifdef CTL_TIME_IO
857			taskio->io_hdr.start_time = time_uptime;
858			getbintime(&taskio->io_hdr.start_bt);
859#if 0
860			cs_prof_gettime(&taskio->io_hdr.start_ticks);
861#endif
862#endif /* CTL_TIME_IO */
863			ctl_run_task((union ctl_io *)taskio);
864			break;
865		}
866		/* Persistent Reserve action which needs attention */
867		case CTL_MSG_PERS_ACTION:
868			presio = (struct ctl_prio *)ctl_alloc_io(
869				(void *)ctl_softc->othersc_pool);
870			if (presio == NULL) {
871				printf("ctl_isc_event_handler: can't allocate "
872				       "ctl_io!\n");
873				/* Bad Juju */
874				/* Need to set busy and send msg back */
875				goto bailout;
876			}
877			ctl_zero_io((union ctl_io *)presio);
878			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
879			presio->pr_msg = msg_info.pr;
880			ctl_enqueue_isc((union ctl_io *)presio);
881			break;
882		case CTL_MSG_SYNC_FE:
883			rcv_sync_msg = 1;
884			break;
885		case CTL_MSG_APS_LOCK: {
886			// It's quicker to execute this then to
887			// queue it.
888			struct ctl_lun *lun;
889			struct ctl_page_index *page_index;
890			struct copan_aps_subpage *current_sp;
891			uint32_t targ_lun;
892
893			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
894			lun = ctl_softc->ctl_luns[targ_lun];
895			mtx_lock(&lun->lun_lock);
896			page_index = &lun->mode_pages.index[index_to_aps_page];
897			current_sp = (struct copan_aps_subpage *)
898				     (page_index->page_data +
899				     (page_index->page_len * CTL_PAGE_CURRENT));
900
901			current_sp->lock_active = msg_info.aps.lock_flag;
902			mtx_unlock(&lun->lun_lock);
903		        break;
904		}
905		default:
906		        printf("How did I get here?\n");
907		}
908	} else if (event == CTL_HA_EVT_MSG_SENT) {
909		if (param != CTL_HA_STATUS_SUCCESS) {
910			printf("Bad status from ctl_ha_msg_send status %d\n",
911			       param);
912		}
913		return;
914	} else if (event == CTL_HA_EVT_DISCONNECT) {
915		printf("CTL: Got a disconnect from Isc\n");
916		return;
917	} else {
918		printf("ctl_isc_event_handler: Unknown event %d\n", event);
919		return;
920	}
921
922bailout:
923	return;
924}
925
926static void
927ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
928{
929	struct scsi_sense_data *sense;
930
931	sense = &dest->scsiio.sense_data;
932	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
933	dest->scsiio.scsi_status = src->scsi.scsi_status;
934	dest->scsiio.sense_len = src->scsi.sense_len;
935	dest->io_hdr.status = src->hdr.status;
936}
937
938static int
939ctl_init(void)
940{
941	struct ctl_softc *softc;
942	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
943	struct ctl_port *port;
944        uint8_t sc_id =0;
945	int i, error, retval;
946	//int isc_retval;
947
948	retval = 0;
949	ctl_pause_rtr = 0;
950        rcv_sync_msg = 0;
951
952	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
953			       M_WAITOK | M_ZERO);
954	softc = control_softc;
955
956	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
957			      "cam/ctl");
958
959	softc->dev->si_drv1 = softc;
960
961	/*
962	 * By default, return a "bad LUN" peripheral qualifier for unknown
963	 * LUNs.  The user can override this default using the tunable or
964	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
965	 */
966	softc->inquiry_pq_no_lun = 1;
967	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
968			  &softc->inquiry_pq_no_lun);
969	sysctl_ctx_init(&softc->sysctl_ctx);
970	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
971		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
972		CTLFLAG_RD, 0, "CAM Target Layer");
973
974	if (softc->sysctl_tree == NULL) {
975		printf("%s: unable to allocate sysctl tree\n", __func__);
976		destroy_dev(softc->dev);
977		free(control_softc, M_DEVBUF);
978		control_softc = NULL;
979		return (ENOMEM);
980	}
981
982	SYSCTL_ADD_INT(&softc->sysctl_ctx,
983		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
984		       "inquiry_pq_no_lun", CTLFLAG_RW,
985		       &softc->inquiry_pq_no_lun, 0,
986		       "Report no lun possible for invalid LUNs");
987
988	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
989	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
990	softc->open_count = 0;
991
992	/*
993	 * Default to actually sending a SYNCHRONIZE CACHE command down to
994	 * the drive.
995	 */
996	softc->flags = CTL_FLAG_REAL_SYNC;
997
998	/*
999	 * In Copan's HA scheme, the "master" and "slave" roles are
1000	 * figured out through the slot the controller is in.  Although it
1001	 * is an active/active system, someone has to be in charge.
1002 	 */
1003#ifdef NEEDTOPORT
1004        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1005#endif
1006
1007        if (sc_id == 0) {
1008		softc->flags |= CTL_FLAG_MASTER_SHELF;
1009		persis_offset = 0;
1010	} else
1011		persis_offset = CTL_MAX_INITIATORS;
1012
1013	/*
1014	 * XXX KDM need to figure out where we want to get our target ID
1015	 * and WWID.  Is it different on each port?
1016	 */
1017	softc->target.id = 0;
1018	softc->target.wwid[0] = 0x12345678;
1019	softc->target.wwid[1] = 0x87654321;
1020	STAILQ_INIT(&softc->lun_list);
1021	STAILQ_INIT(&softc->pending_lun_queue);
1022	STAILQ_INIT(&softc->fe_list);
1023	STAILQ_INIT(&softc->port_list);
1024	STAILQ_INIT(&softc->be_list);
1025	STAILQ_INIT(&softc->io_pools);
1026
1027	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1028			    &internal_pool)!= 0){
1029		printf("ctl: can't allocate %d entry internal pool, "
1030		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1031		return (ENOMEM);
1032	}
1033
1034	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1035			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1036		printf("ctl: can't allocate %d entry emergency pool, "
1037		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1038		ctl_pool_free(internal_pool);
1039		return (ENOMEM);
1040	}
1041
1042	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1043	                    &other_pool) != 0)
1044	{
1045		printf("ctl: can't allocate %d entry other SC pool, "
1046		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1047		ctl_pool_free(internal_pool);
1048		ctl_pool_free(emergency_pool);
1049		return (ENOMEM);
1050	}
1051
1052	softc->internal_pool = internal_pool;
1053	softc->emergency_pool = emergency_pool;
1054	softc->othersc_pool = other_pool;
1055
1056	if (worker_threads <= 0)
1057		worker_threads = max(1, mp_ncpus / 4);
1058	if (worker_threads > CTL_MAX_THREADS)
1059		worker_threads = CTL_MAX_THREADS;
1060
1061	for (i = 0; i < worker_threads; i++) {
1062		struct ctl_thread *thr = &softc->threads[i];
1063
1064		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1065		thr->ctl_softc = softc;
1066		STAILQ_INIT(&thr->incoming_queue);
1067		STAILQ_INIT(&thr->rtr_queue);
1068		STAILQ_INIT(&thr->done_queue);
1069		STAILQ_INIT(&thr->isc_queue);
1070
1071		error = kproc_kthread_add(ctl_work_thread, thr,
1072		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1073		if (error != 0) {
1074			printf("error creating CTL work thread!\n");
1075			ctl_pool_free(internal_pool);
1076			ctl_pool_free(emergency_pool);
1077			ctl_pool_free(other_pool);
1078			return (error);
1079		}
1080	}
1081	error = kproc_kthread_add(ctl_lun_thread, softc,
1082	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1083	if (error != 0) {
1084		printf("error creating CTL lun thread!\n");
1085		ctl_pool_free(internal_pool);
1086		ctl_pool_free(emergency_pool);
1087		ctl_pool_free(other_pool);
1088		return (error);
1089	}
1090	if (bootverbose)
1091		printf("ctl: CAM Target Layer loaded\n");
1092
1093	/*
1094	 * Initialize the ioctl front end.
1095	 */
1096	ctl_frontend_register(&ioctl_frontend);
1097	port = &softc->ioctl_info.port;
1098	port->frontend = &ioctl_frontend;
1099	sprintf(softc->ioctl_info.port_name, "ioctl");
1100	port->port_type = CTL_PORT_IOCTL;
1101	port->num_requested_ctl_io = 100;
1102	port->port_name = softc->ioctl_info.port_name;
1103	port->port_online = ctl_ioctl_online;
1104	port->port_offline = ctl_ioctl_offline;
1105	port->onoff_arg = &softc->ioctl_info;
1106	port->lun_enable = ctl_ioctl_lun_enable;
1107	port->lun_disable = ctl_ioctl_lun_disable;
1108	port->targ_lun_arg = &softc->ioctl_info;
1109	port->fe_datamove = ctl_ioctl_datamove;
1110	port->fe_done = ctl_ioctl_done;
1111	port->max_targets = 15;
1112	port->max_target_id = 15;
1113
1114	if (ctl_port_register(&softc->ioctl_info.port,
1115	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1116		printf("ctl: ioctl front end registration failed, will "
1117		       "continue anyway\n");
1118	}
1119
1120#ifdef CTL_IO_DELAY
1121	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1122		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1123		       sizeof(struct callout), CTL_TIMER_BYTES);
1124		return (EINVAL);
1125	}
1126#endif /* CTL_IO_DELAY */
1127
1128	return (0);
1129}
1130
1131void
1132ctl_shutdown(void)
1133{
1134	struct ctl_softc *softc;
1135	struct ctl_lun *lun, *next_lun;
1136	struct ctl_io_pool *pool;
1137
1138	softc = (struct ctl_softc *)control_softc;
1139
1140	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1141		printf("ctl: ioctl front end deregistration failed\n");
1142
1143	mtx_lock(&softc->ctl_lock);
1144
1145	/*
1146	 * Free up each LUN.
1147	 */
1148	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1149		next_lun = STAILQ_NEXT(lun, links);
1150		ctl_free_lun(lun);
1151	}
1152
1153	mtx_unlock(&softc->ctl_lock);
1154
1155	ctl_frontend_deregister(&ioctl_frontend);
1156
1157	/*
1158	 * This will rip the rug out from under any FETDs or anyone else
1159	 * that has a pool allocated.  Since we increment our module
1160	 * refcount any time someone outside the main CTL module allocates
1161	 * a pool, we shouldn't have any problems here.  The user won't be
1162	 * able to unload the CTL module until client modules have
1163	 * successfully unloaded.
1164	 */
1165	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1166		ctl_pool_free(pool);
1167
1168#if 0
1169	ctl_shutdown_thread(softc->work_thread);
1170	mtx_destroy(&softc->queue_lock);
1171#endif
1172
1173	mtx_destroy(&softc->pool_lock);
1174	mtx_destroy(&softc->ctl_lock);
1175
1176	destroy_dev(softc->dev);
1177
1178	sysctl_ctx_free(&softc->sysctl_ctx);
1179
1180	free(control_softc, M_DEVBUF);
1181	control_softc = NULL;
1182
1183	if (bootverbose)
1184		printf("ctl: CAM Target Layer unloaded\n");
1185}
1186
1187static int
1188ctl_module_event_handler(module_t mod, int what, void *arg)
1189{
1190
1191	switch (what) {
1192	case MOD_LOAD:
1193		return (ctl_init());
1194	case MOD_UNLOAD:
1195		return (EBUSY);
1196	default:
1197		return (EOPNOTSUPP);
1198	}
1199}
1200
1201/*
1202 * XXX KDM should we do some access checks here?  Bump a reference count to
1203 * prevent a CTL module from being unloaded while someone has it open?
1204 */
1205static int
1206ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1207{
1208	return (0);
1209}
1210
1211static int
1212ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1213{
1214	return (0);
1215}
1216
1217int
1218ctl_port_enable(ctl_port_type port_type)
1219{
1220	struct ctl_softc *softc;
1221	struct ctl_port *port;
1222
1223	if (ctl_is_single == 0) {
1224		union ctl_ha_msg msg_info;
1225		int isc_retval;
1226
1227#if 0
1228		printf("%s: HA mode, synchronizing frontend enable\n",
1229		        __func__);
1230#endif
1231		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1232	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1233		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1234			printf("Sync msg send error retval %d\n", isc_retval);
1235		}
1236		if (!rcv_sync_msg) {
1237			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1238			        sizeof(msg_info), 1);
1239		}
1240#if 0
1241        	printf("CTL:Frontend Enable\n");
1242	} else {
1243		printf("%s: single mode, skipping frontend synchronization\n",
1244		        __func__);
1245#endif
1246	}
1247
1248	softc = control_softc;
1249
1250	STAILQ_FOREACH(port, &softc->port_list, links) {
1251		if (port_type & port->port_type)
1252		{
1253#if 0
1254			printf("port %d\n", port->targ_port);
1255#endif
1256			ctl_port_online(port);
1257		}
1258	}
1259
1260	return (0);
1261}
1262
1263int
1264ctl_port_disable(ctl_port_type port_type)
1265{
1266	struct ctl_softc *softc;
1267	struct ctl_port *port;
1268
1269	softc = control_softc;
1270
1271	STAILQ_FOREACH(port, &softc->port_list, links) {
1272		if (port_type & port->port_type)
1273			ctl_port_offline(port);
1274	}
1275
1276	return (0);
1277}
1278
1279/*
1280 * Returns 0 for success, 1 for failure.
1281 * Currently the only failure mode is if there aren't enough entries
1282 * allocated.  So, in case of a failure, look at num_entries_dropped,
1283 * reallocate and try again.
1284 */
1285int
1286ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1287	      int *num_entries_filled, int *num_entries_dropped,
1288	      ctl_port_type port_type, int no_virtual)
1289{
1290	struct ctl_softc *softc;
1291	struct ctl_port *port;
1292	int entries_dropped, entries_filled;
1293	int retval;
1294	int i;
1295
1296	softc = control_softc;
1297
1298	retval = 0;
1299	entries_filled = 0;
1300	entries_dropped = 0;
1301
1302	i = 0;
1303	mtx_lock(&softc->ctl_lock);
1304	STAILQ_FOREACH(port, &softc->port_list, links) {
1305		struct ctl_port_entry *entry;
1306
1307		if ((port->port_type & port_type) == 0)
1308			continue;
1309
1310		if ((no_virtual != 0)
1311		 && (port->virtual_port != 0))
1312			continue;
1313
1314		if (entries_filled >= num_entries_alloced) {
1315			entries_dropped++;
1316			continue;
1317		}
1318		entry = &entries[i];
1319
1320		entry->port_type = port->port_type;
1321		strlcpy(entry->port_name, port->port_name,
1322			sizeof(entry->port_name));
1323		entry->physical_port = port->physical_port;
1324		entry->virtual_port = port->virtual_port;
1325		entry->wwnn = port->wwnn;
1326		entry->wwpn = port->wwpn;
1327
1328		i++;
1329		entries_filled++;
1330	}
1331
1332	mtx_unlock(&softc->ctl_lock);
1333
1334	if (entries_dropped > 0)
1335		retval = 1;
1336
1337	*num_entries_dropped = entries_dropped;
1338	*num_entries_filled = entries_filled;
1339
1340	return (retval);
1341}
1342
1343static void
1344ctl_ioctl_online(void *arg)
1345{
1346	struct ctl_ioctl_info *ioctl_info;
1347
1348	ioctl_info = (struct ctl_ioctl_info *)arg;
1349
1350	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1351}
1352
1353static void
1354ctl_ioctl_offline(void *arg)
1355{
1356	struct ctl_ioctl_info *ioctl_info;
1357
1358	ioctl_info = (struct ctl_ioctl_info *)arg;
1359
1360	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1361}
1362
1363/*
1364 * Remove an initiator by port number and initiator ID.
1365 * Returns 0 for success, -1 for failure.
1366 */
1367int
1368ctl_remove_initiator(struct ctl_port *port, int iid)
1369{
1370	struct ctl_softc *softc = control_softc;
1371
1372	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1373
1374	if (iid > CTL_MAX_INIT_PER_PORT) {
1375		printf("%s: initiator ID %u > maximun %u!\n",
1376		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1377		return (-1);
1378	}
1379
1380	mtx_lock(&softc->ctl_lock);
1381	port->wwpn_iid[iid].in_use--;
1382	port->wwpn_iid[iid].last_use = time_uptime;
1383	mtx_unlock(&softc->ctl_lock);
1384
1385	return (0);
1386}
1387
1388/*
1389 * Add an initiator to the initiator map.
1390 * Returns iid for success, < 0 for failure.
1391 */
1392int
1393ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1394{
1395	struct ctl_softc *softc = control_softc;
1396	time_t best_time;
1397	int i, best;
1398
1399	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1400
1401	if (iid >= CTL_MAX_INIT_PER_PORT) {
1402		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1403		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1404		free(name, M_CTL);
1405		return (-1);
1406	}
1407
1408	mtx_lock(&softc->ctl_lock);
1409
1410	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1411		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1412			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1413				iid = i;
1414				break;
1415			}
1416			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1417			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1418				iid = i;
1419				break;
1420			}
1421		}
1422	}
1423
1424	if (iid < 0) {
1425		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1426			if (port->wwpn_iid[i].in_use == 0 &&
1427			    port->wwpn_iid[i].wwpn == 0 &&
1428			    port->wwpn_iid[i].name == NULL) {
1429				iid = i;
1430				break;
1431			}
1432		}
1433	}
1434
1435	if (iid < 0) {
1436		best = -1;
1437		best_time = INT32_MAX;
1438		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1439			if (port->wwpn_iid[i].in_use == 0) {
1440				if (port->wwpn_iid[i].last_use < best_time) {
1441					best = i;
1442					best_time = port->wwpn_iid[i].last_use;
1443				}
1444			}
1445		}
1446		iid = best;
1447	}
1448
1449	if (iid < 0) {
1450		mtx_unlock(&softc->ctl_lock);
1451		free(name, M_CTL);
1452		return (-2);
1453	}
1454
1455	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1456		/*
1457		 * This is not an error yet.
1458		 */
1459		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1460#if 0
1461			printf("%s: port %d iid %u WWPN %#jx arrived"
1462			    " again\n", __func__, port->targ_port,
1463			    iid, (uintmax_t)wwpn);
1464#endif
1465			goto take;
1466		}
1467		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1468		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1469#if 0
1470			printf("%s: port %d iid %u name '%s' arrived"
1471			    " again\n", __func__, port->targ_port,
1472			    iid, name);
1473#endif
1474			goto take;
1475		}
1476
1477		/*
1478		 * This is an error, but what do we do about it?  The
1479		 * driver is telling us we have a new WWPN for this
1480		 * initiator ID, so we pretty much need to use it.
1481		 */
1482		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1483		    " but WWPN %#jx '%s' is still at that address\n",
1484		    __func__, port->targ_port, iid, wwpn, name,
1485		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1486		    port->wwpn_iid[iid].name);
1487
1488		/*
1489		 * XXX KDM clear have_ca and ua_pending on each LUN for
1490		 * this initiator.
1491		 */
1492	}
1493take:
1494	free(port->wwpn_iid[iid].name, M_CTL);
1495	port->wwpn_iid[iid].name = name;
1496	port->wwpn_iid[iid].wwpn = wwpn;
1497	port->wwpn_iid[iid].in_use++;
1498	mtx_unlock(&softc->ctl_lock);
1499
1500	return (iid);
1501}
1502
1503static int
1504ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1505{
1506	int len;
1507
1508	switch (port->port_type) {
1509	case CTL_PORT_FC:
1510	{
1511		struct scsi_transportid_fcp *id =
1512		    (struct scsi_transportid_fcp *)buf;
1513		if (port->wwpn_iid[iid].wwpn == 0)
1514			return (0);
1515		memset(id, 0, sizeof(*id));
1516		id->format_protocol = SCSI_PROTO_FC;
1517		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1518		return (sizeof(*id));
1519	}
1520	case CTL_PORT_ISCSI:
1521	{
1522		struct scsi_transportid_iscsi_port *id =
1523		    (struct scsi_transportid_iscsi_port *)buf;
1524		if (port->wwpn_iid[iid].name == NULL)
1525			return (0);
1526		memset(id, 0, 256);
1527		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1528		    SCSI_PROTO_ISCSI;
1529		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1530		len = roundup2(min(len, 252), 4);
1531		scsi_ulto2b(len, id->additional_length);
1532		return (sizeof(*id) + len);
1533	}
1534	case CTL_PORT_SAS:
1535	{
1536		struct scsi_transportid_sas *id =
1537		    (struct scsi_transportid_sas *)buf;
1538		if (port->wwpn_iid[iid].wwpn == 0)
1539			return (0);
1540		memset(id, 0, sizeof(*id));
1541		id->format_protocol = SCSI_PROTO_SAS;
1542		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1543		return (sizeof(*id));
1544	}
1545	default:
1546	{
1547		struct scsi_transportid_spi *id =
1548		    (struct scsi_transportid_spi *)buf;
1549		memset(id, 0, sizeof(*id));
1550		id->format_protocol = SCSI_PROTO_SPI;
1551		scsi_ulto2b(iid, id->scsi_addr);
1552		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1553		return (sizeof(*id));
1554	}
1555	}
1556}
1557
1558static int
1559ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1560{
1561	return (0);
1562}
1563
1564static int
1565ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1566{
1567	return (0);
1568}
1569
1570/*
1571 * Data movement routine for the CTL ioctl frontend port.
1572 */
1573static int
1574ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1575{
1576	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1577	struct ctl_sg_entry ext_entry, kern_entry;
1578	int ext_sglen, ext_sg_entries, kern_sg_entries;
1579	int ext_sg_start, ext_offset;
1580	int len_to_copy, len_copied;
1581	int kern_watermark, ext_watermark;
1582	int ext_sglist_malloced;
1583	int i, j;
1584
1585	ext_sglist_malloced = 0;
1586	ext_sg_start = 0;
1587	ext_offset = 0;
1588
1589	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1590
1591	/*
1592	 * If this flag is set, fake the data transfer.
1593	 */
1594	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1595		ctsio->ext_data_filled = ctsio->ext_data_len;
1596		goto bailout;
1597	}
1598
1599	/*
1600	 * To simplify things here, if we have a single buffer, stick it in
1601	 * a S/G entry and just make it a single entry S/G list.
1602	 */
1603	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1604		int len_seen;
1605
1606		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1607
1608		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1609							   M_WAITOK);
1610		ext_sglist_malloced = 1;
1611		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1612				   ext_sglen) != 0) {
1613			ctl_set_internal_failure(ctsio,
1614						 /*sks_valid*/ 0,
1615						 /*retry_count*/ 0);
1616			goto bailout;
1617		}
1618		ext_sg_entries = ctsio->ext_sg_entries;
1619		len_seen = 0;
1620		for (i = 0; i < ext_sg_entries; i++) {
1621			if ((len_seen + ext_sglist[i].len) >=
1622			     ctsio->ext_data_filled) {
1623				ext_sg_start = i;
1624				ext_offset = ctsio->ext_data_filled - len_seen;
1625				break;
1626			}
1627			len_seen += ext_sglist[i].len;
1628		}
1629	} else {
1630		ext_sglist = &ext_entry;
1631		ext_sglist->addr = ctsio->ext_data_ptr;
1632		ext_sglist->len = ctsio->ext_data_len;
1633		ext_sg_entries = 1;
1634		ext_sg_start = 0;
1635		ext_offset = ctsio->ext_data_filled;
1636	}
1637
1638	if (ctsio->kern_sg_entries > 0) {
1639		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1640		kern_sg_entries = ctsio->kern_sg_entries;
1641	} else {
1642		kern_sglist = &kern_entry;
1643		kern_sglist->addr = ctsio->kern_data_ptr;
1644		kern_sglist->len = ctsio->kern_data_len;
1645		kern_sg_entries = 1;
1646	}
1647
1648
1649	kern_watermark = 0;
1650	ext_watermark = ext_offset;
1651	len_copied = 0;
1652	for (i = ext_sg_start, j = 0;
1653	     i < ext_sg_entries && j < kern_sg_entries;) {
1654		uint8_t *ext_ptr, *kern_ptr;
1655
1656		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1657				      kern_sglist[j].len - kern_watermark);
1658
1659		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1660		ext_ptr = ext_ptr + ext_watermark;
1661		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1662			/*
1663			 * XXX KDM fix this!
1664			 */
1665			panic("need to implement bus address support");
1666#if 0
1667			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1668#endif
1669		} else
1670			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1671		kern_ptr = kern_ptr + kern_watermark;
1672
1673		kern_watermark += len_to_copy;
1674		ext_watermark += len_to_copy;
1675
1676		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1677		     CTL_FLAG_DATA_IN) {
1678			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1679					 "bytes to user\n", len_to_copy));
1680			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1681					 "to %p\n", kern_ptr, ext_ptr));
1682			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1683				ctl_set_internal_failure(ctsio,
1684							 /*sks_valid*/ 0,
1685							 /*retry_count*/ 0);
1686				goto bailout;
1687			}
1688		} else {
1689			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1690					 "bytes from user\n", len_to_copy));
1691			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1692					 "to %p\n", ext_ptr, kern_ptr));
1693			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1694				ctl_set_internal_failure(ctsio,
1695							 /*sks_valid*/ 0,
1696							 /*retry_count*/0);
1697				goto bailout;
1698			}
1699		}
1700
1701		len_copied += len_to_copy;
1702
1703		if (ext_sglist[i].len == ext_watermark) {
1704			i++;
1705			ext_watermark = 0;
1706		}
1707
1708		if (kern_sglist[j].len == kern_watermark) {
1709			j++;
1710			kern_watermark = 0;
1711		}
1712	}
1713
1714	ctsio->ext_data_filled += len_copied;
1715
1716	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1717			 "kern_sg_entries: %d\n", ext_sg_entries,
1718			 kern_sg_entries));
1719	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1720			 "kern_data_len = %d\n", ctsio->ext_data_len,
1721			 ctsio->kern_data_len));
1722
1723
1724	/* XXX KDM set residual?? */
1725bailout:
1726
1727	if (ext_sglist_malloced != 0)
1728		free(ext_sglist, M_CTL);
1729
1730	return (CTL_RETVAL_COMPLETE);
1731}
1732
1733/*
1734 * Serialize a command that went down the "wrong" side, and so was sent to
1735 * this controller for execution.  The logic is a little different than the
1736 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1737 * sent back to the other side, but in the success case, we execute the
1738 * command on this side (XFER mode) or tell the other side to execute it
1739 * (SER_ONLY mode).
1740 */
1741static int
1742ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1743{
1744	struct ctl_softc *ctl_softc;
1745	union ctl_ha_msg msg_info;
1746	struct ctl_lun *lun;
1747	int retval = 0;
1748	uint32_t targ_lun;
1749
1750	ctl_softc = control_softc;
1751
1752	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1753	lun = ctl_softc->ctl_luns[targ_lun];
1754	if (lun==NULL)
1755	{
1756		/*
1757		 * Why isn't LUN defined? The other side wouldn't
1758		 * send a cmd if the LUN is undefined.
1759		 */
1760		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1761
1762		/* "Logical unit not supported" */
1763		ctl_set_sense_data(&msg_info.scsi.sense_data,
1764				   lun,
1765				   /*sense_format*/SSD_TYPE_NONE,
1766				   /*current_error*/ 1,
1767				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1768				   /*asc*/ 0x25,
1769				   /*ascq*/ 0x00,
1770				   SSD_ELEM_NONE);
1771
1772		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1773		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1774		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1775		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1776		msg_info.hdr.serializing_sc = NULL;
1777		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1778	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1779				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1780		}
1781		return(1);
1782
1783	}
1784
1785	mtx_lock(&lun->lun_lock);
1786    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1787
1788	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1789		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1790		 ooa_links))) {
1791	case CTL_ACTION_BLOCK:
1792		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1793		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1794				  blocked_links);
1795		break;
1796	case CTL_ACTION_PASS:
1797	case CTL_ACTION_SKIP:
1798		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1799			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1800			ctl_enqueue_rtr((union ctl_io *)ctsio);
1801		} else {
1802
1803			/* send msg back to other side */
1804			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1805			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1806			msg_info.hdr.msg_type = CTL_MSG_R2R;
1807#if 0
1808			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1809#endif
1810		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1811			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1812			}
1813		}
1814		break;
1815	case CTL_ACTION_OVERLAP:
1816		/* OVERLAPPED COMMANDS ATTEMPTED */
1817		ctl_set_sense_data(&msg_info.scsi.sense_data,
1818				   lun,
1819				   /*sense_format*/SSD_TYPE_NONE,
1820				   /*current_error*/ 1,
1821				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1822				   /*asc*/ 0x4E,
1823				   /*ascq*/ 0x00,
1824				   SSD_ELEM_NONE);
1825
1826		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1827		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1828		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1829		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1830		msg_info.hdr.serializing_sc = NULL;
1831		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1832#if 0
1833		printf("BAD JUJU:Major Bummer Overlap\n");
1834#endif
1835		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1836		retval = 1;
1837		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1838		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1839		}
1840		break;
1841	case CTL_ACTION_OVERLAP_TAG:
1842		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1843		ctl_set_sense_data(&msg_info.scsi.sense_data,
1844				   lun,
1845				   /*sense_format*/SSD_TYPE_NONE,
1846				   /*current_error*/ 1,
1847				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1848				   /*asc*/ 0x4D,
1849				   /*ascq*/ ctsio->tag_num & 0xff,
1850				   SSD_ELEM_NONE);
1851
1852		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1853		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1854		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1855		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1856		msg_info.hdr.serializing_sc = NULL;
1857		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1858#if 0
1859		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1860#endif
1861		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1862		retval = 1;
1863		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1864		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1865		}
1866		break;
1867	case CTL_ACTION_ERROR:
1868	default:
1869		/* "Internal target failure" */
1870		ctl_set_sense_data(&msg_info.scsi.sense_data,
1871				   lun,
1872				   /*sense_format*/SSD_TYPE_NONE,
1873				   /*current_error*/ 1,
1874				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1875				   /*asc*/ 0x44,
1876				   /*ascq*/ 0x00,
1877				   SSD_ELEM_NONE);
1878
1879		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1880		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1881		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1882		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1883		msg_info.hdr.serializing_sc = NULL;
1884		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1885#if 0
1886		printf("BAD JUJU:Major Bummer HW Error\n");
1887#endif
1888		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1889		retval = 1;
1890		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1891		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1892		}
1893		break;
1894	}
1895	mtx_unlock(&lun->lun_lock);
1896	return (retval);
1897}
1898
1899static int
1900ctl_ioctl_submit_wait(union ctl_io *io)
1901{
1902	struct ctl_fe_ioctl_params params;
1903	ctl_fe_ioctl_state last_state;
1904	int done, retval;
1905
1906	retval = 0;
1907
1908	bzero(&params, sizeof(params));
1909
1910	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1911	cv_init(&params.sem, "ctlioccv");
1912	params.state = CTL_IOCTL_INPROG;
1913	last_state = params.state;
1914
1915	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1916
1917	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1918
1919	/* This shouldn't happen */
1920	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1921		return (retval);
1922
1923	done = 0;
1924
1925	do {
1926		mtx_lock(&params.ioctl_mtx);
1927		/*
1928		 * Check the state here, and don't sleep if the state has
1929		 * already changed (i.e. wakeup has already occured, but we
1930		 * weren't waiting yet).
1931		 */
1932		if (params.state == last_state) {
1933			/* XXX KDM cv_wait_sig instead? */
1934			cv_wait(&params.sem, &params.ioctl_mtx);
1935		}
1936		last_state = params.state;
1937
1938		switch (params.state) {
1939		case CTL_IOCTL_INPROG:
1940			/* Why did we wake up? */
1941			/* XXX KDM error here? */
1942			mtx_unlock(&params.ioctl_mtx);
1943			break;
1944		case CTL_IOCTL_DATAMOVE:
1945			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1946
1947			/*
1948			 * change last_state back to INPROG to avoid
1949			 * deadlock on subsequent data moves.
1950			 */
1951			params.state = last_state = CTL_IOCTL_INPROG;
1952
1953			mtx_unlock(&params.ioctl_mtx);
1954			ctl_ioctl_do_datamove(&io->scsiio);
1955			/*
1956			 * Note that in some cases, most notably writes,
1957			 * this will queue the I/O and call us back later.
1958			 * In other cases, generally reads, this routine
1959			 * will immediately call back and wake us up,
1960			 * probably using our own context.
1961			 */
1962			io->scsiio.be_move_done(io);
1963			break;
1964		case CTL_IOCTL_DONE:
1965			mtx_unlock(&params.ioctl_mtx);
1966			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1967			done = 1;
1968			break;
1969		default:
1970			mtx_unlock(&params.ioctl_mtx);
1971			/* XXX KDM error here? */
1972			break;
1973		}
1974	} while (done == 0);
1975
1976	mtx_destroy(&params.ioctl_mtx);
1977	cv_destroy(&params.sem);
1978
1979	return (CTL_RETVAL_COMPLETE);
1980}
1981
1982static void
1983ctl_ioctl_datamove(union ctl_io *io)
1984{
1985	struct ctl_fe_ioctl_params *params;
1986
1987	params = (struct ctl_fe_ioctl_params *)
1988		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1989
1990	mtx_lock(&params->ioctl_mtx);
1991	params->state = CTL_IOCTL_DATAMOVE;
1992	cv_broadcast(&params->sem);
1993	mtx_unlock(&params->ioctl_mtx);
1994}
1995
1996static void
1997ctl_ioctl_done(union ctl_io *io)
1998{
1999	struct ctl_fe_ioctl_params *params;
2000
2001	params = (struct ctl_fe_ioctl_params *)
2002		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2003
2004	mtx_lock(&params->ioctl_mtx);
2005	params->state = CTL_IOCTL_DONE;
2006	cv_broadcast(&params->sem);
2007	mtx_unlock(&params->ioctl_mtx);
2008}
2009
2010static void
2011ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2012{
2013	struct ctl_fe_ioctl_startstop_info *sd_info;
2014
2015	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2016
2017	sd_info->hs_info.status = metatask->status;
2018	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2019	sd_info->hs_info.luns_complete =
2020		metatask->taskinfo.startstop.luns_complete;
2021	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2022
2023	cv_broadcast(&sd_info->sem);
2024}
2025
2026static void
2027ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2028{
2029	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2030
2031	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2032
2033	mtx_lock(fe_bbr_info->lock);
2034	fe_bbr_info->bbr_info->status = metatask->status;
2035	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2036	fe_bbr_info->wakeup_done = 1;
2037	mtx_unlock(fe_bbr_info->lock);
2038
2039	cv_broadcast(&fe_bbr_info->sem);
2040}
2041
2042/*
2043 * Returns 0 for success, errno for failure.
2044 */
2045static int
2046ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2047		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2048{
2049	union ctl_io *io;
2050	int retval;
2051
2052	retval = 0;
2053
2054	mtx_lock(&lun->lun_lock);
2055	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2056	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2057	     ooa_links)) {
2058		struct ctl_ooa_entry *entry;
2059
2060		/*
2061		 * If we've got more than we can fit, just count the
2062		 * remaining entries.
2063		 */
2064		if (*cur_fill_num >= ooa_hdr->alloc_num)
2065			continue;
2066
2067		entry = &kern_entries[*cur_fill_num];
2068
2069		entry->tag_num = io->scsiio.tag_num;
2070		entry->lun_num = lun->lun;
2071#ifdef CTL_TIME_IO
2072		entry->start_bt = io->io_hdr.start_bt;
2073#endif
2074		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2075		entry->cdb_len = io->scsiio.cdb_len;
2076		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2077			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2078
2079		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2080			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2081
2082		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2083			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2084
2085		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2086			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2087
2088		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2089			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2090	}
2091	mtx_unlock(&lun->lun_lock);
2092
2093	return (retval);
2094}
2095
2096static void *
2097ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2098		 size_t error_str_len)
2099{
2100	void *kptr;
2101
2102	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2103
2104	if (copyin(user_addr, kptr, len) != 0) {
2105		snprintf(error_str, error_str_len, "Error copying %d bytes "
2106			 "from user address %p to kernel address %p", len,
2107			 user_addr, kptr);
2108		free(kptr, M_CTL);
2109		return (NULL);
2110	}
2111
2112	return (kptr);
2113}
2114
2115static void
2116ctl_free_args(int num_args, struct ctl_be_arg *args)
2117{
2118	int i;
2119
2120	if (args == NULL)
2121		return;
2122
2123	for (i = 0; i < num_args; i++) {
2124		free(args[i].kname, M_CTL);
2125		free(args[i].kvalue, M_CTL);
2126	}
2127
2128	free(args, M_CTL);
2129}
2130
2131static struct ctl_be_arg *
2132ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2133		char *error_str, size_t error_str_len)
2134{
2135	struct ctl_be_arg *args;
2136	int i;
2137
2138	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2139				error_str, error_str_len);
2140
2141	if (args == NULL)
2142		goto bailout;
2143
2144	for (i = 0; i < num_args; i++) {
2145		args[i].kname = NULL;
2146		args[i].kvalue = NULL;
2147	}
2148
2149	for (i = 0; i < num_args; i++) {
2150		uint8_t *tmpptr;
2151
2152		args[i].kname = ctl_copyin_alloc(args[i].name,
2153			args[i].namelen, error_str, error_str_len);
2154		if (args[i].kname == NULL)
2155			goto bailout;
2156
2157		if (args[i].kname[args[i].namelen - 1] != '\0') {
2158			snprintf(error_str, error_str_len, "Argument %d "
2159				 "name is not NUL-terminated", i);
2160			goto bailout;
2161		}
2162
2163		if (args[i].flags & CTL_BEARG_RD) {
2164			tmpptr = ctl_copyin_alloc(args[i].value,
2165				args[i].vallen, error_str, error_str_len);
2166			if (tmpptr == NULL)
2167				goto bailout;
2168			if ((args[i].flags & CTL_BEARG_ASCII)
2169			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2170				snprintf(error_str, error_str_len, "Argument "
2171				    "%d value is not NUL-terminated", i);
2172				goto bailout;
2173			}
2174			args[i].kvalue = tmpptr;
2175		} else {
2176			args[i].kvalue = malloc(args[i].vallen,
2177			    M_CTL, M_WAITOK | M_ZERO);
2178		}
2179	}
2180
2181	return (args);
2182bailout:
2183
2184	ctl_free_args(num_args, args);
2185
2186	return (NULL);
2187}
2188
2189static void
2190ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2191{
2192	int i;
2193
2194	for (i = 0; i < num_args; i++) {
2195		if (args[i].flags & CTL_BEARG_WR)
2196			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2197	}
2198}
2199
2200/*
2201 * Escape characters that are illegal or not recommended in XML.
2202 */
2203int
2204ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2205{
2206	int retval;
2207
2208	retval = 0;
2209
2210	for (; *str; str++) {
2211		switch (*str) {
2212		case '&':
2213			retval = sbuf_printf(sb, "&amp;");
2214			break;
2215		case '>':
2216			retval = sbuf_printf(sb, "&gt;");
2217			break;
2218		case '<':
2219			retval = sbuf_printf(sb, "&lt;");
2220			break;
2221		default:
2222			retval = sbuf_putc(sb, *str);
2223			break;
2224		}
2225
2226		if (retval != 0)
2227			break;
2228
2229	}
2230
2231	return (retval);
2232}
2233
2234static int
2235ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2236	  struct thread *td)
2237{
2238	struct ctl_softc *softc;
2239	int retval;
2240
2241	softc = control_softc;
2242
2243	retval = 0;
2244
2245	switch (cmd) {
2246	case CTL_IO: {
2247		union ctl_io *io;
2248		void *pool_tmp;
2249
2250		/*
2251		 * If we haven't been "enabled", don't allow any SCSI I/O
2252		 * to this FETD.
2253		 */
2254		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2255			retval = EPERM;
2256			break;
2257		}
2258
2259		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2260		if (io == NULL) {
2261			printf("ctl_ioctl: can't allocate ctl_io!\n");
2262			retval = ENOSPC;
2263			break;
2264		}
2265
2266		/*
2267		 * Need to save the pool reference so it doesn't get
2268		 * spammed by the user's ctl_io.
2269		 */
2270		pool_tmp = io->io_hdr.pool;
2271
2272		memcpy(io, (void *)addr, sizeof(*io));
2273
2274		io->io_hdr.pool = pool_tmp;
2275		/*
2276		 * No status yet, so make sure the status is set properly.
2277		 */
2278		io->io_hdr.status = CTL_STATUS_NONE;
2279
2280		/*
2281		 * The user sets the initiator ID, target and LUN IDs.
2282		 */
2283		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2284		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2285		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2286		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2287			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2288
2289		retval = ctl_ioctl_submit_wait(io);
2290
2291		if (retval != 0) {
2292			ctl_free_io(io);
2293			break;
2294		}
2295
2296		memcpy((void *)addr, io, sizeof(*io));
2297
2298		/* return this to our pool */
2299		ctl_free_io(io);
2300
2301		break;
2302	}
2303	case CTL_ENABLE_PORT:
2304	case CTL_DISABLE_PORT:
2305	case CTL_SET_PORT_WWNS: {
2306		struct ctl_port *port;
2307		struct ctl_port_entry *entry;
2308
2309		entry = (struct ctl_port_entry *)addr;
2310
2311		mtx_lock(&softc->ctl_lock);
2312		STAILQ_FOREACH(port, &softc->port_list, links) {
2313			int action, done;
2314
2315			action = 0;
2316			done = 0;
2317
2318			if ((entry->port_type == CTL_PORT_NONE)
2319			 && (entry->targ_port == port->targ_port)) {
2320				/*
2321				 * If the user only wants to enable or
2322				 * disable or set WWNs on a specific port,
2323				 * do the operation and we're done.
2324				 */
2325				action = 1;
2326				done = 1;
2327			} else if (entry->port_type & port->port_type) {
2328				/*
2329				 * Compare the user's type mask with the
2330				 * particular frontend type to see if we
2331				 * have a match.
2332				 */
2333				action = 1;
2334				done = 0;
2335
2336				/*
2337				 * Make sure the user isn't trying to set
2338				 * WWNs on multiple ports at the same time.
2339				 */
2340				if (cmd == CTL_SET_PORT_WWNS) {
2341					printf("%s: Can't set WWNs on "
2342					       "multiple ports\n", __func__);
2343					retval = EINVAL;
2344					break;
2345				}
2346			}
2347			if (action != 0) {
2348				/*
2349				 * XXX KDM we have to drop the lock here,
2350				 * because the online/offline operations
2351				 * can potentially block.  We need to
2352				 * reference count the frontends so they
2353				 * can't go away,
2354				 */
2355				mtx_unlock(&softc->ctl_lock);
2356
2357				if (cmd == CTL_ENABLE_PORT) {
2358					struct ctl_lun *lun;
2359
2360					STAILQ_FOREACH(lun, &softc->lun_list,
2361						       links) {
2362						port->lun_enable(port->targ_lun_arg,
2363						    lun->target,
2364						    lun->lun);
2365					}
2366
2367					ctl_port_online(port);
2368				} else if (cmd == CTL_DISABLE_PORT) {
2369					struct ctl_lun *lun;
2370
2371					ctl_port_offline(port);
2372
2373					STAILQ_FOREACH(lun, &softc->lun_list,
2374						       links) {
2375						port->lun_disable(
2376						    port->targ_lun_arg,
2377						    lun->target,
2378						    lun->lun);
2379					}
2380				}
2381
2382				mtx_lock(&softc->ctl_lock);
2383
2384				if (cmd == CTL_SET_PORT_WWNS)
2385					ctl_port_set_wwns(port,
2386					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2387					    1 : 0, entry->wwnn,
2388					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2389					    1 : 0, entry->wwpn);
2390			}
2391			if (done != 0)
2392				break;
2393		}
2394		mtx_unlock(&softc->ctl_lock);
2395		break;
2396	}
2397	case CTL_GET_PORT_LIST: {
2398		struct ctl_port *port;
2399		struct ctl_port_list *list;
2400		int i;
2401
2402		list = (struct ctl_port_list *)addr;
2403
2404		if (list->alloc_len != (list->alloc_num *
2405		    sizeof(struct ctl_port_entry))) {
2406			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2407			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2408			       "%zu\n", __func__, list->alloc_len,
2409			       list->alloc_num, sizeof(struct ctl_port_entry));
2410			retval = EINVAL;
2411			break;
2412		}
2413		list->fill_len = 0;
2414		list->fill_num = 0;
2415		list->dropped_num = 0;
2416		i = 0;
2417		mtx_lock(&softc->ctl_lock);
2418		STAILQ_FOREACH(port, &softc->port_list, links) {
2419			struct ctl_port_entry entry, *list_entry;
2420
2421			if (list->fill_num >= list->alloc_num) {
2422				list->dropped_num++;
2423				continue;
2424			}
2425
2426			entry.port_type = port->port_type;
2427			strlcpy(entry.port_name, port->port_name,
2428				sizeof(entry.port_name));
2429			entry.targ_port = port->targ_port;
2430			entry.physical_port = port->physical_port;
2431			entry.virtual_port = port->virtual_port;
2432			entry.wwnn = port->wwnn;
2433			entry.wwpn = port->wwpn;
2434			if (port->status & CTL_PORT_STATUS_ONLINE)
2435				entry.online = 1;
2436			else
2437				entry.online = 0;
2438
2439			list_entry = &list->entries[i];
2440
2441			retval = copyout(&entry, list_entry, sizeof(entry));
2442			if (retval != 0) {
2443				printf("%s: CTL_GET_PORT_LIST: copyout "
2444				       "returned %d\n", __func__, retval);
2445				break;
2446			}
2447			i++;
2448			list->fill_num++;
2449			list->fill_len += sizeof(entry);
2450		}
2451		mtx_unlock(&softc->ctl_lock);
2452
2453		/*
2454		 * If this is non-zero, we had a copyout fault, so there's
2455		 * probably no point in attempting to set the status inside
2456		 * the structure.
2457		 */
2458		if (retval != 0)
2459			break;
2460
2461		if (list->dropped_num > 0)
2462			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2463		else
2464			list->status = CTL_PORT_LIST_OK;
2465		break;
2466	}
2467	case CTL_DUMP_OOA: {
2468		struct ctl_lun *lun;
2469		union ctl_io *io;
2470		char printbuf[128];
2471		struct sbuf sb;
2472
2473		mtx_lock(&softc->ctl_lock);
2474		printf("Dumping OOA queues:\n");
2475		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2476			mtx_lock(&lun->lun_lock);
2477			for (io = (union ctl_io *)TAILQ_FIRST(
2478			     &lun->ooa_queue); io != NULL;
2479			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2480			     ooa_links)) {
2481				sbuf_new(&sb, printbuf, sizeof(printbuf),
2482					 SBUF_FIXEDLEN);
2483				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2484					    (intmax_t)lun->lun,
2485					    io->scsiio.tag_num,
2486					    (io->io_hdr.flags &
2487					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2488					    (io->io_hdr.flags &
2489					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2490					    (io->io_hdr.flags &
2491					    CTL_FLAG_ABORT) ? " ABORT" : "",
2492			                    (io->io_hdr.flags &
2493		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2494				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2495				sbuf_finish(&sb);
2496				printf("%s\n", sbuf_data(&sb));
2497			}
2498			mtx_unlock(&lun->lun_lock);
2499		}
2500		printf("OOA queues dump done\n");
2501		mtx_unlock(&softc->ctl_lock);
2502		break;
2503	}
2504	case CTL_GET_OOA: {
2505		struct ctl_lun *lun;
2506		struct ctl_ooa *ooa_hdr;
2507		struct ctl_ooa_entry *entries;
2508		uint32_t cur_fill_num;
2509
2510		ooa_hdr = (struct ctl_ooa *)addr;
2511
2512		if ((ooa_hdr->alloc_len == 0)
2513		 || (ooa_hdr->alloc_num == 0)) {
2514			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2515			       "must be non-zero\n", __func__,
2516			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2517			retval = EINVAL;
2518			break;
2519		}
2520
2521		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2522		    sizeof(struct ctl_ooa_entry))) {
2523			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2524			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2525			       __func__, ooa_hdr->alloc_len,
2526			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2527			retval = EINVAL;
2528			break;
2529		}
2530
2531		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2532		if (entries == NULL) {
2533			printf("%s: could not allocate %d bytes for OOA "
2534			       "dump\n", __func__, ooa_hdr->alloc_len);
2535			retval = ENOMEM;
2536			break;
2537		}
2538
2539		mtx_lock(&softc->ctl_lock);
2540		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2541		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2542		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2543			mtx_unlock(&softc->ctl_lock);
2544			free(entries, M_CTL);
2545			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2546			       __func__, (uintmax_t)ooa_hdr->lun_num);
2547			retval = EINVAL;
2548			break;
2549		}
2550
2551		cur_fill_num = 0;
2552
2553		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2554			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2555				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2556					ooa_hdr, entries);
2557				if (retval != 0)
2558					break;
2559			}
2560			if (retval != 0) {
2561				mtx_unlock(&softc->ctl_lock);
2562				free(entries, M_CTL);
2563				break;
2564			}
2565		} else {
2566			lun = softc->ctl_luns[ooa_hdr->lun_num];
2567
2568			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2569						    entries);
2570		}
2571		mtx_unlock(&softc->ctl_lock);
2572
2573		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2574		ooa_hdr->fill_len = ooa_hdr->fill_num *
2575			sizeof(struct ctl_ooa_entry);
2576		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2577		if (retval != 0) {
2578			printf("%s: error copying out %d bytes for OOA dump\n",
2579			       __func__, ooa_hdr->fill_len);
2580		}
2581
2582		getbintime(&ooa_hdr->cur_bt);
2583
2584		if (cur_fill_num > ooa_hdr->alloc_num) {
2585			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2586			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2587		} else {
2588			ooa_hdr->dropped_num = 0;
2589			ooa_hdr->status = CTL_OOA_OK;
2590		}
2591
2592		free(entries, M_CTL);
2593		break;
2594	}
2595	case CTL_CHECK_OOA: {
2596		union ctl_io *io;
2597		struct ctl_lun *lun;
2598		struct ctl_ooa_info *ooa_info;
2599
2600
2601		ooa_info = (struct ctl_ooa_info *)addr;
2602
2603		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2604			ooa_info->status = CTL_OOA_INVALID_LUN;
2605			break;
2606		}
2607		mtx_lock(&softc->ctl_lock);
2608		lun = softc->ctl_luns[ooa_info->lun_id];
2609		if (lun == NULL) {
2610			mtx_unlock(&softc->ctl_lock);
2611			ooa_info->status = CTL_OOA_INVALID_LUN;
2612			break;
2613		}
2614		mtx_lock(&lun->lun_lock);
2615		mtx_unlock(&softc->ctl_lock);
2616		ooa_info->num_entries = 0;
2617		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2618		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2619		     &io->io_hdr, ooa_links)) {
2620			ooa_info->num_entries++;
2621		}
2622		mtx_unlock(&lun->lun_lock);
2623
2624		ooa_info->status = CTL_OOA_SUCCESS;
2625
2626		break;
2627	}
2628	case CTL_HARD_START:
2629	case CTL_HARD_STOP: {
2630		struct ctl_fe_ioctl_startstop_info ss_info;
2631		struct cfi_metatask *metatask;
2632		struct mtx hs_mtx;
2633
2634		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2635
2636		cv_init(&ss_info.sem, "hard start/stop cv" );
2637
2638		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2639		if (metatask == NULL) {
2640			retval = ENOMEM;
2641			mtx_destroy(&hs_mtx);
2642			break;
2643		}
2644
2645		if (cmd == CTL_HARD_START)
2646			metatask->tasktype = CFI_TASK_STARTUP;
2647		else
2648			metatask->tasktype = CFI_TASK_SHUTDOWN;
2649
2650		metatask->callback = ctl_ioctl_hard_startstop_callback;
2651		metatask->callback_arg = &ss_info;
2652
2653		cfi_action(metatask);
2654
2655		/* Wait for the callback */
2656		mtx_lock(&hs_mtx);
2657		cv_wait_sig(&ss_info.sem, &hs_mtx);
2658		mtx_unlock(&hs_mtx);
2659
2660		/*
2661		 * All information has been copied from the metatask by the
2662		 * time cv_broadcast() is called, so we free the metatask here.
2663		 */
2664		cfi_free_metatask(metatask);
2665
2666		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2667
2668		mtx_destroy(&hs_mtx);
2669		break;
2670	}
2671	case CTL_BBRREAD: {
2672		struct ctl_bbrread_info *bbr_info;
2673		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2674		struct mtx bbr_mtx;
2675		struct cfi_metatask *metatask;
2676
2677		bbr_info = (struct ctl_bbrread_info *)addr;
2678
2679		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2680
2681		bzero(&bbr_mtx, sizeof(bbr_mtx));
2682		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2683
2684		fe_bbr_info.bbr_info = bbr_info;
2685		fe_bbr_info.lock = &bbr_mtx;
2686
2687		cv_init(&fe_bbr_info.sem, "BBR read cv");
2688		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2689
2690		if (metatask == NULL) {
2691			mtx_destroy(&bbr_mtx);
2692			cv_destroy(&fe_bbr_info.sem);
2693			retval = ENOMEM;
2694			break;
2695		}
2696		metatask->tasktype = CFI_TASK_BBRREAD;
2697		metatask->callback = ctl_ioctl_bbrread_callback;
2698		metatask->callback_arg = &fe_bbr_info;
2699		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2700		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2701		metatask->taskinfo.bbrread.len = bbr_info->len;
2702
2703		cfi_action(metatask);
2704
2705		mtx_lock(&bbr_mtx);
2706		while (fe_bbr_info.wakeup_done == 0)
2707			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2708		mtx_unlock(&bbr_mtx);
2709
2710		bbr_info->status = metatask->status;
2711		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2712		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2713		memcpy(&bbr_info->sense_data,
2714		       &metatask->taskinfo.bbrread.sense_data,
2715		       ctl_min(sizeof(bbr_info->sense_data),
2716			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2717
2718		cfi_free_metatask(metatask);
2719
2720		mtx_destroy(&bbr_mtx);
2721		cv_destroy(&fe_bbr_info.sem);
2722
2723		break;
2724	}
2725	case CTL_DELAY_IO: {
2726		struct ctl_io_delay_info *delay_info;
2727#ifdef CTL_IO_DELAY
2728		struct ctl_lun *lun;
2729#endif /* CTL_IO_DELAY */
2730
2731		delay_info = (struct ctl_io_delay_info *)addr;
2732
2733#ifdef CTL_IO_DELAY
2734		mtx_lock(&softc->ctl_lock);
2735
2736		if ((delay_info->lun_id > CTL_MAX_LUNS)
2737		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2738			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2739		} else {
2740			lun = softc->ctl_luns[delay_info->lun_id];
2741			mtx_lock(&lun->lun_lock);
2742
2743			delay_info->status = CTL_DELAY_STATUS_OK;
2744
2745			switch (delay_info->delay_type) {
2746			case CTL_DELAY_TYPE_CONT:
2747				break;
2748			case CTL_DELAY_TYPE_ONESHOT:
2749				break;
2750			default:
2751				delay_info->status =
2752					CTL_DELAY_STATUS_INVALID_TYPE;
2753				break;
2754			}
2755
2756			switch (delay_info->delay_loc) {
2757			case CTL_DELAY_LOC_DATAMOVE:
2758				lun->delay_info.datamove_type =
2759					delay_info->delay_type;
2760				lun->delay_info.datamove_delay =
2761					delay_info->delay_secs;
2762				break;
2763			case CTL_DELAY_LOC_DONE:
2764				lun->delay_info.done_type =
2765					delay_info->delay_type;
2766				lun->delay_info.done_delay =
2767					delay_info->delay_secs;
2768				break;
2769			default:
2770				delay_info->status =
2771					CTL_DELAY_STATUS_INVALID_LOC;
2772				break;
2773			}
2774			mtx_unlock(&lun->lun_lock);
2775		}
2776
2777		mtx_unlock(&softc->ctl_lock);
2778#else
2779		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2780#endif /* CTL_IO_DELAY */
2781		break;
2782	}
2783	case CTL_REALSYNC_SET: {
2784		int *syncstate;
2785
2786		syncstate = (int *)addr;
2787
2788		mtx_lock(&softc->ctl_lock);
2789		switch (*syncstate) {
2790		case 0:
2791			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2792			break;
2793		case 1:
2794			softc->flags |= CTL_FLAG_REAL_SYNC;
2795			break;
2796		default:
2797			retval = EINVAL;
2798			break;
2799		}
2800		mtx_unlock(&softc->ctl_lock);
2801		break;
2802	}
2803	case CTL_REALSYNC_GET: {
2804		int *syncstate;
2805
2806		syncstate = (int*)addr;
2807
2808		mtx_lock(&softc->ctl_lock);
2809		if (softc->flags & CTL_FLAG_REAL_SYNC)
2810			*syncstate = 1;
2811		else
2812			*syncstate = 0;
2813		mtx_unlock(&softc->ctl_lock);
2814
2815		break;
2816	}
2817	case CTL_SETSYNC:
2818	case CTL_GETSYNC: {
2819		struct ctl_sync_info *sync_info;
2820		struct ctl_lun *lun;
2821
2822		sync_info = (struct ctl_sync_info *)addr;
2823
2824		mtx_lock(&softc->ctl_lock);
2825		lun = softc->ctl_luns[sync_info->lun_id];
2826		if (lun == NULL) {
2827			mtx_unlock(&softc->ctl_lock);
2828			sync_info->status = CTL_GS_SYNC_NO_LUN;
2829		}
2830		/*
2831		 * Get or set the sync interval.  We're not bounds checking
2832		 * in the set case, hopefully the user won't do something
2833		 * silly.
2834		 */
2835		mtx_lock(&lun->lun_lock);
2836		mtx_unlock(&softc->ctl_lock);
2837		if (cmd == CTL_GETSYNC)
2838			sync_info->sync_interval = lun->sync_interval;
2839		else
2840			lun->sync_interval = sync_info->sync_interval;
2841		mtx_unlock(&lun->lun_lock);
2842
2843		sync_info->status = CTL_GS_SYNC_OK;
2844
2845		break;
2846	}
2847	case CTL_GETSTATS: {
2848		struct ctl_stats *stats;
2849		struct ctl_lun *lun;
2850		int i;
2851
2852		stats = (struct ctl_stats *)addr;
2853
2854		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2855		     stats->alloc_len) {
2856			stats->status = CTL_SS_NEED_MORE_SPACE;
2857			stats->num_luns = softc->num_luns;
2858			break;
2859		}
2860		/*
2861		 * XXX KDM no locking here.  If the LUN list changes,
2862		 * things can blow up.
2863		 */
2864		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2865		     i++, lun = STAILQ_NEXT(lun, links)) {
2866			retval = copyout(&lun->stats, &stats->lun_stats[i],
2867					 sizeof(lun->stats));
2868			if (retval != 0)
2869				break;
2870		}
2871		stats->num_luns = softc->num_luns;
2872		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2873				 softc->num_luns;
2874		stats->status = CTL_SS_OK;
2875#ifdef CTL_TIME_IO
2876		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2877#else
2878		stats->flags = CTL_STATS_FLAG_NONE;
2879#endif
2880		getnanouptime(&stats->timestamp);
2881		break;
2882	}
2883	case CTL_ERROR_INJECT: {
2884		struct ctl_error_desc *err_desc, *new_err_desc;
2885		struct ctl_lun *lun;
2886
2887		err_desc = (struct ctl_error_desc *)addr;
2888
2889		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2890				      M_WAITOK | M_ZERO);
2891		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2892
2893		mtx_lock(&softc->ctl_lock);
2894		lun = softc->ctl_luns[err_desc->lun_id];
2895		if (lun == NULL) {
2896			mtx_unlock(&softc->ctl_lock);
2897			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2898			       __func__, (uintmax_t)err_desc->lun_id);
2899			retval = EINVAL;
2900			break;
2901		}
2902		mtx_lock(&lun->lun_lock);
2903		mtx_unlock(&softc->ctl_lock);
2904
2905		/*
2906		 * We could do some checking here to verify the validity
2907		 * of the request, but given the complexity of error
2908		 * injection requests, the checking logic would be fairly
2909		 * complex.
2910		 *
2911		 * For now, if the request is invalid, it just won't get
2912		 * executed and might get deleted.
2913		 */
2914		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2915
2916		/*
2917		 * XXX KDM check to make sure the serial number is unique,
2918		 * in case we somehow manage to wrap.  That shouldn't
2919		 * happen for a very long time, but it's the right thing to
2920		 * do.
2921		 */
2922		new_err_desc->serial = lun->error_serial;
2923		err_desc->serial = lun->error_serial;
2924		lun->error_serial++;
2925
2926		mtx_unlock(&lun->lun_lock);
2927		break;
2928	}
2929	case CTL_ERROR_INJECT_DELETE: {
2930		struct ctl_error_desc *delete_desc, *desc, *desc2;
2931		struct ctl_lun *lun;
2932		int delete_done;
2933
2934		delete_desc = (struct ctl_error_desc *)addr;
2935		delete_done = 0;
2936
2937		mtx_lock(&softc->ctl_lock);
2938		lun = softc->ctl_luns[delete_desc->lun_id];
2939		if (lun == NULL) {
2940			mtx_unlock(&softc->ctl_lock);
2941			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2942			       __func__, (uintmax_t)delete_desc->lun_id);
2943			retval = EINVAL;
2944			break;
2945		}
2946		mtx_lock(&lun->lun_lock);
2947		mtx_unlock(&softc->ctl_lock);
2948		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2949			if (desc->serial != delete_desc->serial)
2950				continue;
2951
2952			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2953				      links);
2954			free(desc, M_CTL);
2955			delete_done = 1;
2956		}
2957		mtx_unlock(&lun->lun_lock);
2958		if (delete_done == 0) {
2959			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2960			       "error serial %ju on LUN %u\n", __func__,
2961			       delete_desc->serial, delete_desc->lun_id);
2962			retval = EINVAL;
2963			break;
2964		}
2965		break;
2966	}
2967	case CTL_DUMP_STRUCTS: {
2968		int i, j, k, idx;
2969		struct ctl_port *port;
2970		struct ctl_frontend *fe;
2971
2972		mtx_lock(&softc->ctl_lock);
2973		printf("CTL Persistent Reservation information start:\n");
2974		for (i = 0; i < CTL_MAX_LUNS; i++) {
2975			struct ctl_lun *lun;
2976
2977			lun = softc->ctl_luns[i];
2978
2979			if ((lun == NULL)
2980			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2981				continue;
2982
2983			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2984				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2985					idx = j * CTL_MAX_INIT_PER_PORT + k;
2986					if (lun->per_res[idx].registered == 0)
2987						continue;
2988					printf("  LUN %d port %d iid %d key "
2989					       "%#jx\n", i, j, k,
2990					       (uintmax_t)scsi_8btou64(
2991					       lun->per_res[idx].res_key.key));
2992				}
2993			}
2994		}
2995		printf("CTL Persistent Reservation information end\n");
2996		printf("CTL Ports:\n");
2997		STAILQ_FOREACH(port, &softc->port_list, links) {
2998			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2999			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3000			       port->frontend->name, port->port_type,
3001			       port->physical_port, port->virtual_port,
3002			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3003			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3004				if (port->wwpn_iid[j].in_use == 0 &&
3005				    port->wwpn_iid[j].wwpn == 0 &&
3006				    port->wwpn_iid[j].name == NULL)
3007					continue;
3008
3009				printf("    iid %u use %d WWPN %#jx '%s'\n",
3010				    j, port->wwpn_iid[j].in_use,
3011				    (uintmax_t)port->wwpn_iid[j].wwpn,
3012				    port->wwpn_iid[j].name);
3013			}
3014		}
3015		printf("CTL Port information end\n");
3016		mtx_unlock(&softc->ctl_lock);
3017		/*
3018		 * XXX KDM calling this without a lock.  We'd likely want
3019		 * to drop the lock before calling the frontend's dump
3020		 * routine anyway.
3021		 */
3022		printf("CTL Frontends:\n");
3023		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3024			printf("  Frontend '%s'\n", fe->name);
3025			if (fe->fe_dump != NULL)
3026				fe->fe_dump();
3027		}
3028		printf("CTL Frontend information end\n");
3029		break;
3030	}
3031	case CTL_LUN_REQ: {
3032		struct ctl_lun_req *lun_req;
3033		struct ctl_backend_driver *backend;
3034
3035		lun_req = (struct ctl_lun_req *)addr;
3036
3037		backend = ctl_backend_find(lun_req->backend);
3038		if (backend == NULL) {
3039			lun_req->status = CTL_LUN_ERROR;
3040			snprintf(lun_req->error_str,
3041				 sizeof(lun_req->error_str),
3042				 "Backend \"%s\" not found.",
3043				 lun_req->backend);
3044			break;
3045		}
3046		if (lun_req->num_be_args > 0) {
3047			lun_req->kern_be_args = ctl_copyin_args(
3048				lun_req->num_be_args,
3049				lun_req->be_args,
3050				lun_req->error_str,
3051				sizeof(lun_req->error_str));
3052			if (lun_req->kern_be_args == NULL) {
3053				lun_req->status = CTL_LUN_ERROR;
3054				break;
3055			}
3056		}
3057
3058		retval = backend->ioctl(dev, cmd, addr, flag, td);
3059
3060		if (lun_req->num_be_args > 0) {
3061			ctl_copyout_args(lun_req->num_be_args,
3062				      lun_req->kern_be_args);
3063			ctl_free_args(lun_req->num_be_args,
3064				      lun_req->kern_be_args);
3065		}
3066		break;
3067	}
3068	case CTL_LUN_LIST: {
3069		struct sbuf *sb;
3070		struct ctl_lun *lun;
3071		struct ctl_lun_list *list;
3072		struct ctl_option *opt;
3073
3074		list = (struct ctl_lun_list *)addr;
3075
3076		/*
3077		 * Allocate a fixed length sbuf here, based on the length
3078		 * of the user's buffer.  We could allocate an auto-extending
3079		 * buffer, and then tell the user how much larger our
3080		 * amount of data is than his buffer, but that presents
3081		 * some problems:
3082		 *
3083		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3084		 *     we can't hold a lock while calling them with an
3085		 *     auto-extending buffer.
3086 		 *
3087		 * 2.  There is not currently a LUN reference counting
3088		 *     mechanism, outside of outstanding transactions on
3089		 *     the LUN's OOA queue.  So a LUN could go away on us
3090		 *     while we're getting the LUN number, backend-specific
3091		 *     information, etc.  Thus, given the way things
3092		 *     currently work, we need to hold the CTL lock while
3093		 *     grabbing LUN information.
3094		 *
3095		 * So, from the user's standpoint, the best thing to do is
3096		 * allocate what he thinks is a reasonable buffer length,
3097		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3098		 * double the buffer length and try again.  (And repeat
3099		 * that until he succeeds.)
3100		 */
3101		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3102		if (sb == NULL) {
3103			list->status = CTL_LUN_LIST_ERROR;
3104			snprintf(list->error_str, sizeof(list->error_str),
3105				 "Unable to allocate %d bytes for LUN list",
3106				 list->alloc_len);
3107			break;
3108		}
3109
3110		sbuf_printf(sb, "<ctllunlist>\n");
3111
3112		mtx_lock(&softc->ctl_lock);
3113		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3114			mtx_lock(&lun->lun_lock);
3115			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3116					     (uintmax_t)lun->lun);
3117
3118			/*
3119			 * Bail out as soon as we see that we've overfilled
3120			 * the buffer.
3121			 */
3122			if (retval != 0)
3123				break;
3124
3125			retval = sbuf_printf(sb, "\t<backend_type>%s"
3126					     "</backend_type>\n",
3127					     (lun->backend == NULL) ?  "none" :
3128					     lun->backend->name);
3129
3130			if (retval != 0)
3131				break;
3132
3133			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3134					     lun->be_lun->lun_type);
3135
3136			if (retval != 0)
3137				break;
3138
3139			if (lun->backend == NULL) {
3140				retval = sbuf_printf(sb, "</lun>\n");
3141				if (retval != 0)
3142					break;
3143				continue;
3144			}
3145
3146			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3147					     (lun->be_lun->maxlba > 0) ?
3148					     lun->be_lun->maxlba + 1 : 0);
3149
3150			if (retval != 0)
3151				break;
3152
3153			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3154					     lun->be_lun->blocksize);
3155
3156			if (retval != 0)
3157				break;
3158
3159			retval = sbuf_printf(sb, "\t<serial_number>");
3160
3161			if (retval != 0)
3162				break;
3163
3164			retval = ctl_sbuf_printf_esc(sb,
3165						     lun->be_lun->serial_num);
3166
3167			if (retval != 0)
3168				break;
3169
3170			retval = sbuf_printf(sb, "</serial_number>\n");
3171
3172			if (retval != 0)
3173				break;
3174
3175			retval = sbuf_printf(sb, "\t<device_id>");
3176
3177			if (retval != 0)
3178				break;
3179
3180			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3181
3182			if (retval != 0)
3183				break;
3184
3185			retval = sbuf_printf(sb, "</device_id>\n");
3186
3187			if (retval != 0)
3188				break;
3189
3190			if (lun->backend->lun_info != NULL) {
3191				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3192				if (retval != 0)
3193					break;
3194			}
3195			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3196				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3197				    opt->name, opt->value, opt->name);
3198				if (retval != 0)
3199					break;
3200			}
3201
3202			retval = sbuf_printf(sb, "</lun>\n");
3203
3204			if (retval != 0)
3205				break;
3206			mtx_unlock(&lun->lun_lock);
3207		}
3208		if (lun != NULL)
3209			mtx_unlock(&lun->lun_lock);
3210		mtx_unlock(&softc->ctl_lock);
3211
3212		if ((retval != 0)
3213		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3214			retval = 0;
3215			sbuf_delete(sb);
3216			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3217			snprintf(list->error_str, sizeof(list->error_str),
3218				 "Out of space, %d bytes is too small",
3219				 list->alloc_len);
3220			break;
3221		}
3222
3223		sbuf_finish(sb);
3224
3225		retval = copyout(sbuf_data(sb), list->lun_xml,
3226				 sbuf_len(sb) + 1);
3227
3228		list->fill_len = sbuf_len(sb) + 1;
3229		list->status = CTL_LUN_LIST_OK;
3230		sbuf_delete(sb);
3231		break;
3232	}
3233	case CTL_ISCSI: {
3234		struct ctl_iscsi *ci;
3235		struct ctl_frontend *fe;
3236
3237		ci = (struct ctl_iscsi *)addr;
3238
3239		fe = ctl_frontend_find("iscsi");
3240		if (fe == NULL) {
3241			ci->status = CTL_ISCSI_ERROR;
3242			snprintf(ci->error_str, sizeof(ci->error_str),
3243			    "Frontend \"iscsi\" not found.");
3244			break;
3245		}
3246
3247		retval = fe->ioctl(dev, cmd, addr, flag, td);
3248		break;
3249	}
3250	case CTL_PORT_REQ: {
3251		struct ctl_req *req;
3252		struct ctl_frontend *fe;
3253
3254		req = (struct ctl_req *)addr;
3255
3256		fe = ctl_frontend_find(req->driver);
3257		if (fe == NULL) {
3258			req->status = CTL_LUN_ERROR;
3259			snprintf(req->error_str, sizeof(req->error_str),
3260			    "Frontend \"%s\" not found.", req->driver);
3261			break;
3262		}
3263		if (req->num_args > 0) {
3264			req->kern_args = ctl_copyin_args(req->num_args,
3265			    req->args, req->error_str, sizeof(req->error_str));
3266			if (req->kern_args == NULL) {
3267				req->status = CTL_LUN_ERROR;
3268				break;
3269			}
3270		}
3271
3272		retval = fe->ioctl(dev, cmd, addr, flag, td);
3273
3274		if (req->num_args > 0) {
3275			ctl_copyout_args(req->num_args, req->kern_args);
3276			ctl_free_args(req->num_args, req->kern_args);
3277		}
3278		break;
3279	}
3280	case CTL_PORT_LIST: {
3281		struct sbuf *sb;
3282		struct ctl_port *port;
3283		struct ctl_lun_list *list;
3284		struct ctl_option *opt;
3285
3286		list = (struct ctl_lun_list *)addr;
3287
3288		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3289		if (sb == NULL) {
3290			list->status = CTL_LUN_LIST_ERROR;
3291			snprintf(list->error_str, sizeof(list->error_str),
3292				 "Unable to allocate %d bytes for LUN list",
3293				 list->alloc_len);
3294			break;
3295		}
3296
3297		sbuf_printf(sb, "<ctlportlist>\n");
3298
3299		mtx_lock(&softc->ctl_lock);
3300		STAILQ_FOREACH(port, &softc->port_list, links) {
3301			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3302					     (uintmax_t)port->targ_port);
3303
3304			/*
3305			 * Bail out as soon as we see that we've overfilled
3306			 * the buffer.
3307			 */
3308			if (retval != 0)
3309				break;
3310
3311			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3312			    "</frontend_type>\n", port->frontend->name);
3313			if (retval != 0)
3314				break;
3315
3316			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3317					     port->port_type);
3318			if (retval != 0)
3319				break;
3320
3321			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3322			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3323			if (retval != 0)
3324				break;
3325
3326			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3327			    port->port_name);
3328			if (retval != 0)
3329				break;
3330
3331			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3332			    port->physical_port);
3333			if (retval != 0)
3334				break;
3335
3336			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3337			    port->virtual_port);
3338			if (retval != 0)
3339				break;
3340
3341			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3342			    (uintmax_t)port->wwnn);
3343			if (retval != 0)
3344				break;
3345
3346			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3347			    (uintmax_t)port->wwpn);
3348			if (retval != 0)
3349				break;
3350
3351			if (port->port_info != NULL) {
3352				retval = port->port_info(port->onoff_arg, sb);
3353				if (retval != 0)
3354					break;
3355			}
3356			STAILQ_FOREACH(opt, &port->options, links) {
3357				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3358				    opt->name, opt->value, opt->name);
3359				if (retval != 0)
3360					break;
3361			}
3362
3363			retval = sbuf_printf(sb, "</targ_port>\n");
3364			if (retval != 0)
3365				break;
3366		}
3367		mtx_unlock(&softc->ctl_lock);
3368
3369		if ((retval != 0)
3370		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3371			retval = 0;
3372			sbuf_delete(sb);
3373			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3374			snprintf(list->error_str, sizeof(list->error_str),
3375				 "Out of space, %d bytes is too small",
3376				 list->alloc_len);
3377			break;
3378		}
3379
3380		sbuf_finish(sb);
3381
3382		retval = copyout(sbuf_data(sb), list->lun_xml,
3383				 sbuf_len(sb) + 1);
3384
3385		list->fill_len = sbuf_len(sb) + 1;
3386		list->status = CTL_LUN_LIST_OK;
3387		sbuf_delete(sb);
3388		break;
3389	}
3390	default: {
3391		/* XXX KDM should we fix this? */
3392#if 0
3393		struct ctl_backend_driver *backend;
3394		unsigned int type;
3395		int found;
3396
3397		found = 0;
3398
3399		/*
3400		 * We encode the backend type as the ioctl type for backend
3401		 * ioctls.  So parse it out here, and then search for a
3402		 * backend of this type.
3403		 */
3404		type = _IOC_TYPE(cmd);
3405
3406		STAILQ_FOREACH(backend, &softc->be_list, links) {
3407			if (backend->type == type) {
3408				found = 1;
3409				break;
3410			}
3411		}
3412		if (found == 0) {
3413			printf("ctl: unknown ioctl command %#lx or backend "
3414			       "%d\n", cmd, type);
3415			retval = EINVAL;
3416			break;
3417		}
3418		retval = backend->ioctl(dev, cmd, addr, flag, td);
3419#endif
3420		retval = ENOTTY;
3421		break;
3422	}
3423	}
3424	return (retval);
3425}
3426
3427uint32_t
3428ctl_get_initindex(struct ctl_nexus *nexus)
3429{
3430	if (nexus->targ_port < CTL_MAX_PORTS)
3431		return (nexus->initid.id +
3432			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3433	else
3434		return (nexus->initid.id +
3435		       ((nexus->targ_port - CTL_MAX_PORTS) *
3436			CTL_MAX_INIT_PER_PORT));
3437}
3438
3439uint32_t
3440ctl_get_resindex(struct ctl_nexus *nexus)
3441{
3442	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3443}
3444
3445uint32_t
3446ctl_port_idx(int port_num)
3447{
3448	if (port_num < CTL_MAX_PORTS)
3449		return(port_num);
3450	else
3451		return(port_num - CTL_MAX_PORTS);
3452}
3453
3454static uint32_t
3455ctl_map_lun(int port_num, uint32_t lun_id)
3456{
3457	struct ctl_port *port;
3458
3459	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3460	if (port == NULL)
3461		return (UINT32_MAX);
3462	if (port->lun_map == NULL)
3463		return (lun_id);
3464	return (port->lun_map(port->targ_lun_arg, lun_id));
3465}
3466
3467static uint32_t
3468ctl_map_lun_back(int port_num, uint32_t lun_id)
3469{
3470	struct ctl_port *port;
3471	uint32_t i;
3472
3473	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3474	if (port->lun_map == NULL)
3475		return (lun_id);
3476	for (i = 0; i < CTL_MAX_LUNS; i++) {
3477		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3478			return (i);
3479	}
3480	return (UINT32_MAX);
3481}
3482
3483/*
3484 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3485 * that are a power of 2.
3486 */
3487int
3488ctl_ffz(uint32_t *mask, uint32_t size)
3489{
3490	uint32_t num_chunks, num_pieces;
3491	int i, j;
3492
3493	num_chunks = (size >> 5);
3494	if (num_chunks == 0)
3495		num_chunks++;
3496	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3497
3498	for (i = 0; i < num_chunks; i++) {
3499		for (j = 0; j < num_pieces; j++) {
3500			if ((mask[i] & (1 << j)) == 0)
3501				return ((i << 5) + j);
3502		}
3503	}
3504
3505	return (-1);
3506}
3507
3508int
3509ctl_set_mask(uint32_t *mask, uint32_t bit)
3510{
3511	uint32_t chunk, piece;
3512
3513	chunk = bit >> 5;
3514	piece = bit % (sizeof(uint32_t) * 8);
3515
3516	if ((mask[chunk] & (1 << piece)) != 0)
3517		return (-1);
3518	else
3519		mask[chunk] |= (1 << piece);
3520
3521	return (0);
3522}
3523
3524int
3525ctl_clear_mask(uint32_t *mask, uint32_t bit)
3526{
3527	uint32_t chunk, piece;
3528
3529	chunk = bit >> 5;
3530	piece = bit % (sizeof(uint32_t) * 8);
3531
3532	if ((mask[chunk] & (1 << piece)) == 0)
3533		return (-1);
3534	else
3535		mask[chunk] &= ~(1 << piece);
3536
3537	return (0);
3538}
3539
3540int
3541ctl_is_set(uint32_t *mask, uint32_t bit)
3542{
3543	uint32_t chunk, piece;
3544
3545	chunk = bit >> 5;
3546	piece = bit % (sizeof(uint32_t) * 8);
3547
3548	if ((mask[chunk] & (1 << piece)) == 0)
3549		return (0);
3550	else
3551		return (1);
3552}
3553
3554#ifdef unused
3555/*
3556 * The bus, target and lun are optional, they can be filled in later.
3557 * can_wait is used to determine whether we can wait on the malloc or not.
3558 */
3559union ctl_io*
3560ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3561	      uint32_t targ_lun, int can_wait)
3562{
3563	union ctl_io *io;
3564
3565	if (can_wait)
3566		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3567	else
3568		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3569
3570	if (io != NULL) {
3571		io->io_hdr.io_type = io_type;
3572		io->io_hdr.targ_port = targ_port;
3573		/*
3574		 * XXX KDM this needs to change/go away.  We need to move
3575		 * to a preallocated pool of ctl_scsiio structures.
3576		 */
3577		io->io_hdr.nexus.targ_target.id = targ_target;
3578		io->io_hdr.nexus.targ_lun = targ_lun;
3579	}
3580
3581	return (io);
3582}
3583
3584void
3585ctl_kfree_io(union ctl_io *io)
3586{
3587	free(io, M_CTL);
3588}
3589#endif /* unused */
3590
3591/*
3592 * ctl_softc, pool_type, total_ctl_io are passed in.
3593 * npool is passed out.
3594 */
3595int
3596ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3597		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3598{
3599	uint32_t i;
3600	union ctl_io *cur_io, *next_io;
3601	struct ctl_io_pool *pool;
3602	int retval;
3603
3604	retval = 0;
3605
3606	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3607					    M_NOWAIT | M_ZERO);
3608	if (pool == NULL) {
3609		retval = ENOMEM;
3610		goto bailout;
3611	}
3612
3613	pool->type = pool_type;
3614	pool->ctl_softc = ctl_softc;
3615
3616	mtx_lock(&ctl_softc->pool_lock);
3617	pool->id = ctl_softc->cur_pool_id++;
3618	mtx_unlock(&ctl_softc->pool_lock);
3619
3620	pool->flags = CTL_POOL_FLAG_NONE;
3621	pool->refcount = 1;		/* Reference for validity. */
3622	STAILQ_INIT(&pool->free_queue);
3623
3624	/*
3625	 * XXX KDM other options here:
3626	 * - allocate a page at a time
3627	 * - allocate one big chunk of memory.
3628	 * Page allocation might work well, but would take a little more
3629	 * tracking.
3630	 */
3631	for (i = 0; i < total_ctl_io; i++) {
3632		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3633						M_NOWAIT);
3634		if (cur_io == NULL) {
3635			retval = ENOMEM;
3636			break;
3637		}
3638		cur_io->io_hdr.pool = pool;
3639		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3640		pool->total_ctl_io++;
3641		pool->free_ctl_io++;
3642	}
3643
3644	if (retval != 0) {
3645		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3646		     cur_io != NULL; cur_io = next_io) {
3647			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3648							      links);
3649			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3650				      ctl_io_hdr, links);
3651			free(cur_io, M_CTLIO);
3652		}
3653
3654		free(pool, M_CTL);
3655		goto bailout;
3656	}
3657	mtx_lock(&ctl_softc->pool_lock);
3658	ctl_softc->num_pools++;
3659	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3660	/*
3661	 * Increment our usage count if this is an external consumer, so we
3662	 * can't get unloaded until the external consumer (most likely a
3663	 * FETD) unloads and frees his pool.
3664	 *
3665	 * XXX KDM will this increment the caller's module use count, or
3666	 * mine?
3667	 */
3668#if 0
3669	if ((pool_type != CTL_POOL_EMERGENCY)
3670	 && (pool_type != CTL_POOL_INTERNAL)
3671	 && (pool_type != CTL_POOL_4OTHERSC))
3672		MOD_INC_USE_COUNT;
3673#endif
3674
3675	mtx_unlock(&ctl_softc->pool_lock);
3676
3677	*npool = pool;
3678
3679bailout:
3680
3681	return (retval);
3682}
3683
3684static int
3685ctl_pool_acquire(struct ctl_io_pool *pool)
3686{
3687
3688	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3689
3690	if (pool->flags & CTL_POOL_FLAG_INVALID)
3691		return (EINVAL);
3692
3693	pool->refcount++;
3694
3695	return (0);
3696}
3697
3698static void
3699ctl_pool_release(struct ctl_io_pool *pool)
3700{
3701	struct ctl_softc *ctl_softc = pool->ctl_softc;
3702	union ctl_io *io;
3703
3704	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3705
3706	if (--pool->refcount != 0)
3707		return;
3708
3709	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3710		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3711			      links);
3712		free(io, M_CTLIO);
3713	}
3714
3715	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3716	ctl_softc->num_pools--;
3717
3718	/*
3719	 * XXX KDM will this decrement the caller's usage count or mine?
3720	 */
3721#if 0
3722	if ((pool->type != CTL_POOL_EMERGENCY)
3723	 && (pool->type != CTL_POOL_INTERNAL)
3724	 && (pool->type != CTL_POOL_4OTHERSC))
3725		MOD_DEC_USE_COUNT;
3726#endif
3727
3728	free(pool, M_CTL);
3729}
3730
3731void
3732ctl_pool_free(struct ctl_io_pool *pool)
3733{
3734	struct ctl_softc *ctl_softc;
3735
3736	if (pool == NULL)
3737		return;
3738
3739	ctl_softc = pool->ctl_softc;
3740	mtx_lock(&ctl_softc->pool_lock);
3741	pool->flags |= CTL_POOL_FLAG_INVALID;
3742	ctl_pool_release(pool);
3743	mtx_unlock(&ctl_softc->pool_lock);
3744}
3745
3746/*
3747 * This routine does not block (except for spinlocks of course).
3748 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3749 * possible.
3750 */
3751union ctl_io *
3752ctl_alloc_io(void *pool_ref)
3753{
3754	union ctl_io *io;
3755	struct ctl_softc *ctl_softc;
3756	struct ctl_io_pool *pool, *npool;
3757	struct ctl_io_pool *emergency_pool;
3758
3759	pool = (struct ctl_io_pool *)pool_ref;
3760
3761	if (pool == NULL) {
3762		printf("%s: pool is NULL\n", __func__);
3763		return (NULL);
3764	}
3765
3766	emergency_pool = NULL;
3767
3768	ctl_softc = pool->ctl_softc;
3769
3770	mtx_lock(&ctl_softc->pool_lock);
3771	/*
3772	 * First, try to get the io structure from the user's pool.
3773	 */
3774	if (ctl_pool_acquire(pool) == 0) {
3775		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3776		if (io != NULL) {
3777			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3778			pool->total_allocated++;
3779			pool->free_ctl_io--;
3780			mtx_unlock(&ctl_softc->pool_lock);
3781			return (io);
3782		} else
3783			ctl_pool_release(pool);
3784	}
3785	/*
3786	 * If he doesn't have any io structures left, search for an
3787	 * emergency pool and grab one from there.
3788	 */
3789	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3790		if (npool->type != CTL_POOL_EMERGENCY)
3791			continue;
3792
3793		if (ctl_pool_acquire(npool) != 0)
3794			continue;
3795
3796		emergency_pool = npool;
3797
3798		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3799		if (io != NULL) {
3800			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3801			npool->total_allocated++;
3802			npool->free_ctl_io--;
3803			mtx_unlock(&ctl_softc->pool_lock);
3804			return (io);
3805		} else
3806			ctl_pool_release(npool);
3807	}
3808
3809	/* Drop the spinlock before we malloc */
3810	mtx_unlock(&ctl_softc->pool_lock);
3811
3812	/*
3813	 * The emergency pool (if it exists) didn't have one, so try an
3814	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3815	 */
3816	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3817	if (io != NULL) {
3818		/*
3819		 * If the emergency pool exists but is empty, add this
3820		 * ctl_io to its list when it gets freed.
3821		 */
3822		if (emergency_pool != NULL) {
3823			mtx_lock(&ctl_softc->pool_lock);
3824			if (ctl_pool_acquire(emergency_pool) == 0) {
3825				io->io_hdr.pool = emergency_pool;
3826				emergency_pool->total_ctl_io++;
3827				/*
3828				 * Need to bump this, otherwise
3829				 * total_allocated and total_freed won't
3830				 * match when we no longer have anything
3831				 * outstanding.
3832				 */
3833				emergency_pool->total_allocated++;
3834			}
3835			mtx_unlock(&ctl_softc->pool_lock);
3836		} else
3837			io->io_hdr.pool = NULL;
3838	}
3839
3840	return (io);
3841}
3842
3843void
3844ctl_free_io(union ctl_io *io)
3845{
3846	if (io == NULL)
3847		return;
3848
3849	/*
3850	 * If this ctl_io has a pool, return it to that pool.
3851	 */
3852	if (io->io_hdr.pool != NULL) {
3853		struct ctl_io_pool *pool;
3854
3855		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3856		mtx_lock(&pool->ctl_softc->pool_lock);
3857		io->io_hdr.io_type = 0xff;
3858		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3859		pool->total_freed++;
3860		pool->free_ctl_io++;
3861		ctl_pool_release(pool);
3862		mtx_unlock(&pool->ctl_softc->pool_lock);
3863	} else {
3864		/*
3865		 * Otherwise, just free it.  We probably malloced it and
3866		 * the emergency pool wasn't available.
3867		 */
3868		free(io, M_CTLIO);
3869	}
3870
3871}
3872
3873void
3874ctl_zero_io(union ctl_io *io)
3875{
3876	void *pool_ref;
3877
3878	if (io == NULL)
3879		return;
3880
3881	/*
3882	 * May need to preserve linked list pointers at some point too.
3883	 */
3884	pool_ref = io->io_hdr.pool;
3885
3886	memset(io, 0, sizeof(*io));
3887
3888	io->io_hdr.pool = pool_ref;
3889}
3890
3891/*
3892 * This routine is currently used for internal copies of ctl_ios that need
3893 * to persist for some reason after we've already returned status to the
3894 * FETD.  (Thus the flag set.)
3895 *
3896 * XXX XXX
3897 * Note that this makes a blind copy of all fields in the ctl_io, except
3898 * for the pool reference.  This includes any memory that has been
3899 * allocated!  That memory will no longer be valid after done has been
3900 * called, so this would be VERY DANGEROUS for command that actually does
3901 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3902 * start and stop commands, which don't transfer any data, so this is not a
3903 * problem.  If it is used for anything else, the caller would also need to
3904 * allocate data buffer space and this routine would need to be modified to
3905 * copy the data buffer(s) as well.
3906 */
3907void
3908ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3909{
3910	void *pool_ref;
3911
3912	if ((src == NULL)
3913	 || (dest == NULL))
3914		return;
3915
3916	/*
3917	 * May need to preserve linked list pointers at some point too.
3918	 */
3919	pool_ref = dest->io_hdr.pool;
3920
3921	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3922
3923	dest->io_hdr.pool = pool_ref;
3924	/*
3925	 * We need to know that this is an internal copy, and doesn't need
3926	 * to get passed back to the FETD that allocated it.
3927	 */
3928	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3929}
3930
3931#ifdef NEEDTOPORT
3932static void
3933ctl_update_power_subpage(struct copan_power_subpage *page)
3934{
3935	int num_luns, num_partitions, config_type;
3936	struct ctl_softc *softc;
3937	cs_BOOL_t aor_present, shelf_50pct_power;
3938	cs_raidset_personality_t rs_type;
3939	int max_active_luns;
3940
3941	softc = control_softc;
3942
3943	/* subtract out the processor LUN */
3944	num_luns = softc->num_luns - 1;
3945	/*
3946	 * Default to 7 LUNs active, which was the only number we allowed
3947	 * in the past.
3948	 */
3949	max_active_luns = 7;
3950
3951	num_partitions = config_GetRsPartitionInfo();
3952	config_type = config_GetConfigType();
3953	shelf_50pct_power = config_GetShelfPowerMode();
3954	aor_present = config_IsAorRsPresent();
3955
3956	rs_type = ddb_GetRsRaidType(1);
3957	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3958	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3959		EPRINT(0, "Unsupported RS type %d!", rs_type);
3960	}
3961
3962
3963	page->total_luns = num_luns;
3964
3965	switch (config_type) {
3966	case 40:
3967		/*
3968		 * In a 40 drive configuration, it doesn't matter what DC
3969		 * cards we have, whether we have AOR enabled or not,
3970		 * partitioning or not, or what type of RAIDset we have.
3971		 * In that scenario, we can power up every LUN we present
3972		 * to the user.
3973		 */
3974		max_active_luns = num_luns;
3975
3976		break;
3977	case 64:
3978		if (shelf_50pct_power == CS_FALSE) {
3979			/* 25% power */
3980			if (aor_present == CS_TRUE) {
3981				if (rs_type ==
3982				     CS_RAIDSET_PERSONALITY_RAID5) {
3983					max_active_luns = 7;
3984				} else if (rs_type ==
3985					 CS_RAIDSET_PERSONALITY_RAID1){
3986					max_active_luns = 14;
3987				} else {
3988					/* XXX KDM now what?? */
3989				}
3990			} else {
3991				if (rs_type ==
3992				     CS_RAIDSET_PERSONALITY_RAID5) {
3993					max_active_luns = 8;
3994				} else if (rs_type ==
3995					 CS_RAIDSET_PERSONALITY_RAID1){
3996					max_active_luns = 16;
3997				} else {
3998					/* XXX KDM now what?? */
3999				}
4000			}
4001		} else {
4002			/* 50% power */
4003			/*
4004			 * With 50% power in a 64 drive configuration, we
4005			 * can power all LUNs we present.
4006			 */
4007			max_active_luns = num_luns;
4008		}
4009		break;
4010	case 112:
4011		if (shelf_50pct_power == CS_FALSE) {
4012			/* 25% power */
4013			if (aor_present == CS_TRUE) {
4014				if (rs_type ==
4015				     CS_RAIDSET_PERSONALITY_RAID5) {
4016					max_active_luns = 7;
4017				} else if (rs_type ==
4018					 CS_RAIDSET_PERSONALITY_RAID1){
4019					max_active_luns = 14;
4020				} else {
4021					/* XXX KDM now what?? */
4022				}
4023			} else {
4024				if (rs_type ==
4025				     CS_RAIDSET_PERSONALITY_RAID5) {
4026					max_active_luns = 8;
4027				} else if (rs_type ==
4028					 CS_RAIDSET_PERSONALITY_RAID1){
4029					max_active_luns = 16;
4030				} else {
4031					/* XXX KDM now what?? */
4032				}
4033			}
4034		} else {
4035			/* 50% power */
4036			if (aor_present == CS_TRUE) {
4037				if (rs_type ==
4038				     CS_RAIDSET_PERSONALITY_RAID5) {
4039					max_active_luns = 14;
4040				} else if (rs_type ==
4041					 CS_RAIDSET_PERSONALITY_RAID1){
4042					/*
4043					 * We're assuming here that disk
4044					 * caching is enabled, and so we're
4045					 * able to power up half of each
4046					 * LUN, and cache all writes.
4047					 */
4048					max_active_luns = num_luns;
4049				} else {
4050					/* XXX KDM now what?? */
4051				}
4052			} else {
4053				if (rs_type ==
4054				     CS_RAIDSET_PERSONALITY_RAID5) {
4055					max_active_luns = 15;
4056				} else if (rs_type ==
4057					 CS_RAIDSET_PERSONALITY_RAID1){
4058					max_active_luns = 30;
4059				} else {
4060					/* XXX KDM now what?? */
4061				}
4062			}
4063		}
4064		break;
4065	default:
4066		/*
4067		 * In this case, we have an unknown configuration, so we
4068		 * just use the default from above.
4069		 */
4070		break;
4071	}
4072
4073	page->max_active_luns = max_active_luns;
4074#if 0
4075	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4076	       page->total_luns, page->max_active_luns);
4077#endif
4078}
4079#endif /* NEEDTOPORT */
4080
4081/*
4082 * This routine could be used in the future to load default and/or saved
4083 * mode page parameters for a particuar lun.
4084 */
4085static int
4086ctl_init_page_index(struct ctl_lun *lun)
4087{
4088	int i;
4089	struct ctl_page_index *page_index;
4090	struct ctl_softc *softc;
4091
4092	memcpy(&lun->mode_pages.index, page_index_template,
4093	       sizeof(page_index_template));
4094
4095	softc = lun->ctl_softc;
4096
4097	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4098
4099		page_index = &lun->mode_pages.index[i];
4100		/*
4101		 * If this is a disk-only mode page, there's no point in
4102		 * setting it up.  For some pages, we have to have some
4103		 * basic information about the disk in order to calculate the
4104		 * mode page data.
4105		 */
4106		if ((lun->be_lun->lun_type != T_DIRECT)
4107		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4108			continue;
4109
4110		switch (page_index->page_code & SMPH_PC_MASK) {
4111		case SMS_FORMAT_DEVICE_PAGE: {
4112			struct scsi_format_page *format_page;
4113
4114			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4115				panic("subpage is incorrect!");
4116
4117			/*
4118			 * Sectors per track are set above.  Bytes per
4119			 * sector need to be set here on a per-LUN basis.
4120			 */
4121			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4122			       &format_page_default,
4123			       sizeof(format_page_default));
4124			memcpy(&lun->mode_pages.format_page[
4125			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4126			       sizeof(format_page_changeable));
4127			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4128			       &format_page_default,
4129			       sizeof(format_page_default));
4130			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4131			       &format_page_default,
4132			       sizeof(format_page_default));
4133
4134			format_page = &lun->mode_pages.format_page[
4135				CTL_PAGE_CURRENT];
4136			scsi_ulto2b(lun->be_lun->blocksize,
4137				    format_page->bytes_per_sector);
4138
4139			format_page = &lun->mode_pages.format_page[
4140				CTL_PAGE_DEFAULT];
4141			scsi_ulto2b(lun->be_lun->blocksize,
4142				    format_page->bytes_per_sector);
4143
4144			format_page = &lun->mode_pages.format_page[
4145				CTL_PAGE_SAVED];
4146			scsi_ulto2b(lun->be_lun->blocksize,
4147				    format_page->bytes_per_sector);
4148
4149			page_index->page_data =
4150				(uint8_t *)lun->mode_pages.format_page;
4151			break;
4152		}
4153		case SMS_RIGID_DISK_PAGE: {
4154			struct scsi_rigid_disk_page *rigid_disk_page;
4155			uint32_t sectors_per_cylinder;
4156			uint64_t cylinders;
4157#ifndef	__XSCALE__
4158			int shift;
4159#endif /* !__XSCALE__ */
4160
4161			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4162				panic("invalid subpage value %d",
4163				      page_index->subpage);
4164
4165			/*
4166			 * Rotation rate and sectors per track are set
4167			 * above.  We calculate the cylinders here based on
4168			 * capacity.  Due to the number of heads and
4169			 * sectors per track we're using, smaller arrays
4170			 * may turn out to have 0 cylinders.  Linux and
4171			 * FreeBSD don't pay attention to these mode pages
4172			 * to figure out capacity, but Solaris does.  It
4173			 * seems to deal with 0 cylinders just fine, and
4174			 * works out a fake geometry based on the capacity.
4175			 */
4176			memcpy(&lun->mode_pages.rigid_disk_page[
4177			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4178			       sizeof(rigid_disk_page_default));
4179			memcpy(&lun->mode_pages.rigid_disk_page[
4180			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4181			       sizeof(rigid_disk_page_changeable));
4182			memcpy(&lun->mode_pages.rigid_disk_page[
4183			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4184			       sizeof(rigid_disk_page_default));
4185			memcpy(&lun->mode_pages.rigid_disk_page[
4186			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4187			       sizeof(rigid_disk_page_default));
4188
4189			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4190				CTL_DEFAULT_HEADS;
4191
4192			/*
4193			 * The divide method here will be more accurate,
4194			 * probably, but results in floating point being
4195			 * used in the kernel on i386 (__udivdi3()).  On the
4196			 * XScale, though, __udivdi3() is implemented in
4197			 * software.
4198			 *
4199			 * The shift method for cylinder calculation is
4200			 * accurate if sectors_per_cylinder is a power of
4201			 * 2.  Otherwise it might be slightly off -- you
4202			 * might have a bit of a truncation problem.
4203			 */
4204#ifdef	__XSCALE__
4205			cylinders = (lun->be_lun->maxlba + 1) /
4206				sectors_per_cylinder;
4207#else
4208			for (shift = 31; shift > 0; shift--) {
4209				if (sectors_per_cylinder & (1 << shift))
4210					break;
4211			}
4212			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4213#endif
4214
4215			/*
4216			 * We've basically got 3 bytes, or 24 bits for the
4217			 * cylinder size in the mode page.  If we're over,
4218			 * just round down to 2^24.
4219			 */
4220			if (cylinders > 0xffffff)
4221				cylinders = 0xffffff;
4222
4223			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4224				CTL_PAGE_CURRENT];
4225			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4226
4227			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4228				CTL_PAGE_DEFAULT];
4229			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4230
4231			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4232				CTL_PAGE_SAVED];
4233			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4234
4235			page_index->page_data =
4236				(uint8_t *)lun->mode_pages.rigid_disk_page;
4237			break;
4238		}
4239		case SMS_CACHING_PAGE: {
4240
4241			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4242				panic("invalid subpage value %d",
4243				      page_index->subpage);
4244			/*
4245			 * Defaults should be okay here, no calculations
4246			 * needed.
4247			 */
4248			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4249			       &caching_page_default,
4250			       sizeof(caching_page_default));
4251			memcpy(&lun->mode_pages.caching_page[
4252			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4253			       sizeof(caching_page_changeable));
4254			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4255			       &caching_page_default,
4256			       sizeof(caching_page_default));
4257			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4258			       &caching_page_default,
4259			       sizeof(caching_page_default));
4260			page_index->page_data =
4261				(uint8_t *)lun->mode_pages.caching_page;
4262			break;
4263		}
4264		case SMS_CONTROL_MODE_PAGE: {
4265
4266			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4267				panic("invalid subpage value %d",
4268				      page_index->subpage);
4269
4270			/*
4271			 * Defaults should be okay here, no calculations
4272			 * needed.
4273			 */
4274			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4275			       &control_page_default,
4276			       sizeof(control_page_default));
4277			memcpy(&lun->mode_pages.control_page[
4278			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4279			       sizeof(control_page_changeable));
4280			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4281			       &control_page_default,
4282			       sizeof(control_page_default));
4283			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4284			       &control_page_default,
4285			       sizeof(control_page_default));
4286			page_index->page_data =
4287				(uint8_t *)lun->mode_pages.control_page;
4288			break;
4289
4290		}
4291		case SMS_VENDOR_SPECIFIC_PAGE:{
4292			switch (page_index->subpage) {
4293			case PWR_SUBPAGE_CODE: {
4294				struct copan_power_subpage *current_page,
4295							   *saved_page;
4296
4297				memcpy(&lun->mode_pages.power_subpage[
4298				       CTL_PAGE_CURRENT],
4299				       &power_page_default,
4300				       sizeof(power_page_default));
4301				memcpy(&lun->mode_pages.power_subpage[
4302				       CTL_PAGE_CHANGEABLE],
4303				       &power_page_changeable,
4304				       sizeof(power_page_changeable));
4305				memcpy(&lun->mode_pages.power_subpage[
4306				       CTL_PAGE_DEFAULT],
4307				       &power_page_default,
4308				       sizeof(power_page_default));
4309				memcpy(&lun->mode_pages.power_subpage[
4310				       CTL_PAGE_SAVED],
4311				       &power_page_default,
4312				       sizeof(power_page_default));
4313				page_index->page_data =
4314				    (uint8_t *)lun->mode_pages.power_subpage;
4315
4316				current_page = (struct copan_power_subpage *)
4317					(page_index->page_data +
4318					 (page_index->page_len *
4319					  CTL_PAGE_CURRENT));
4320			        saved_page = (struct copan_power_subpage *)
4321				        (page_index->page_data +
4322					 (page_index->page_len *
4323					  CTL_PAGE_SAVED));
4324				break;
4325			}
4326			case APS_SUBPAGE_CODE: {
4327				struct copan_aps_subpage *current_page,
4328							 *saved_page;
4329
4330				// This gets set multiple times but
4331				// it should always be the same. It's
4332				// only done during init so who cares.
4333				index_to_aps_page = i;
4334
4335				memcpy(&lun->mode_pages.aps_subpage[
4336				       CTL_PAGE_CURRENT],
4337				       &aps_page_default,
4338				       sizeof(aps_page_default));
4339				memcpy(&lun->mode_pages.aps_subpage[
4340				       CTL_PAGE_CHANGEABLE],
4341				       &aps_page_changeable,
4342				       sizeof(aps_page_changeable));
4343				memcpy(&lun->mode_pages.aps_subpage[
4344				       CTL_PAGE_DEFAULT],
4345				       &aps_page_default,
4346				       sizeof(aps_page_default));
4347				memcpy(&lun->mode_pages.aps_subpage[
4348				       CTL_PAGE_SAVED],
4349				       &aps_page_default,
4350				       sizeof(aps_page_default));
4351				page_index->page_data =
4352					(uint8_t *)lun->mode_pages.aps_subpage;
4353
4354				current_page = (struct copan_aps_subpage *)
4355					(page_index->page_data +
4356					 (page_index->page_len *
4357					  CTL_PAGE_CURRENT));
4358				saved_page = (struct copan_aps_subpage *)
4359					(page_index->page_data +
4360					 (page_index->page_len *
4361					  CTL_PAGE_SAVED));
4362				break;
4363			}
4364			case DBGCNF_SUBPAGE_CODE: {
4365				struct copan_debugconf_subpage *current_page,
4366							       *saved_page;
4367
4368				memcpy(&lun->mode_pages.debugconf_subpage[
4369				       CTL_PAGE_CURRENT],
4370				       &debugconf_page_default,
4371				       sizeof(debugconf_page_default));
4372				memcpy(&lun->mode_pages.debugconf_subpage[
4373				       CTL_PAGE_CHANGEABLE],
4374				       &debugconf_page_changeable,
4375				       sizeof(debugconf_page_changeable));
4376				memcpy(&lun->mode_pages.debugconf_subpage[
4377				       CTL_PAGE_DEFAULT],
4378				       &debugconf_page_default,
4379				       sizeof(debugconf_page_default));
4380				memcpy(&lun->mode_pages.debugconf_subpage[
4381				       CTL_PAGE_SAVED],
4382				       &debugconf_page_default,
4383				       sizeof(debugconf_page_default));
4384				page_index->page_data =
4385					(uint8_t *)lun->mode_pages.debugconf_subpage;
4386
4387				current_page = (struct copan_debugconf_subpage *)
4388					(page_index->page_data +
4389					 (page_index->page_len *
4390					  CTL_PAGE_CURRENT));
4391				saved_page = (struct copan_debugconf_subpage *)
4392					(page_index->page_data +
4393					 (page_index->page_len *
4394					  CTL_PAGE_SAVED));
4395				break;
4396			}
4397			default:
4398				panic("invalid subpage value %d",
4399				      page_index->subpage);
4400				break;
4401			}
4402   			break;
4403		}
4404		default:
4405			panic("invalid page value %d",
4406			      page_index->page_code & SMPH_PC_MASK);
4407			break;
4408    	}
4409	}
4410
4411	return (CTL_RETVAL_COMPLETE);
4412}
4413
4414/*
4415 * LUN allocation.
4416 *
4417 * Requirements:
4418 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4419 *   wants us to allocate the LUN and he can block.
4420 * - ctl_softc is always set
4421 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4422 *
4423 * Returns 0 for success, non-zero (errno) for failure.
4424 */
4425static int
4426ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4427	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4428{
4429	struct ctl_lun *nlun, *lun;
4430	struct ctl_port *port;
4431	struct scsi_vpd_id_descriptor *desc;
4432	struct scsi_vpd_id_t10 *t10id;
4433	const char *eui, *naa, *scsiname, *vendor;
4434	int lun_number, i, lun_malloced;
4435	int devidlen, idlen1, idlen2 = 0, len;
4436
4437	if (be_lun == NULL)
4438		return (EINVAL);
4439
4440	/*
4441	 * We currently only support Direct Access or Processor LUN types.
4442	 */
4443	switch (be_lun->lun_type) {
4444	case T_DIRECT:
4445		break;
4446	case T_PROCESSOR:
4447		break;
4448	case T_SEQUENTIAL:
4449	case T_CHANGER:
4450	default:
4451		be_lun->lun_config_status(be_lun->be_lun,
4452					  CTL_LUN_CONFIG_FAILURE);
4453		break;
4454	}
4455	if (ctl_lun == NULL) {
4456		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4457		lun_malloced = 1;
4458	} else {
4459		lun_malloced = 0;
4460		lun = ctl_lun;
4461	}
4462
4463	memset(lun, 0, sizeof(*lun));
4464	if (lun_malloced)
4465		lun->flags = CTL_LUN_MALLOCED;
4466
4467	/* Generate LUN ID. */
4468	devidlen = max(CTL_DEVID_MIN_LEN,
4469	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4470	idlen1 = sizeof(*t10id) + devidlen;
4471	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4472	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4473	if (scsiname != NULL) {
4474		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4475		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4476	}
4477	eui = ctl_get_opt(&be_lun->options, "eui");
4478	if (eui != NULL) {
4479		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4480	}
4481	naa = ctl_get_opt(&be_lun->options, "naa");
4482	if (naa != NULL) {
4483		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4484	}
4485	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4486	    M_CTL, M_WAITOK | M_ZERO);
4487	lun->lun_devid->len = len;
4488	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4489	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4490	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4491	desc->length = idlen1;
4492	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4493	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4494	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4495		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4496	} else {
4497		strncpy(t10id->vendor, vendor,
4498		    min(sizeof(t10id->vendor), strlen(vendor)));
4499	}
4500	strncpy((char *)t10id->vendor_spec_id,
4501	    (char *)be_lun->device_id, devidlen);
4502	if (scsiname != NULL) {
4503		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4504		    desc->length);
4505		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4506		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4507		    SVPD_ID_TYPE_SCSI_NAME;
4508		desc->length = idlen2;
4509		strlcpy(desc->identifier, scsiname, idlen2);
4510	}
4511	if (eui != NULL) {
4512		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4513		    desc->length);
4514		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4515		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4516		    SVPD_ID_TYPE_EUI64;
4517		desc->length = 8;
4518		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4519	}
4520	if (naa != NULL) {
4521		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4522		    desc->length);
4523		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4524		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4525		    SVPD_ID_TYPE_NAA;
4526		desc->length = 8;
4527		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4528	}
4529
4530	mtx_lock(&ctl_softc->ctl_lock);
4531	/*
4532	 * See if the caller requested a particular LUN number.  If so, see
4533	 * if it is available.  Otherwise, allocate the first available LUN.
4534	 */
4535	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4536		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4537		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4538			mtx_unlock(&ctl_softc->ctl_lock);
4539			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4540				printf("ctl: requested LUN ID %d is higher "
4541				       "than CTL_MAX_LUNS - 1 (%d)\n",
4542				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4543			} else {
4544				/*
4545				 * XXX KDM return an error, or just assign
4546				 * another LUN ID in this case??
4547				 */
4548				printf("ctl: requested LUN ID %d is already "
4549				       "in use\n", be_lun->req_lun_id);
4550			}
4551			if (lun->flags & CTL_LUN_MALLOCED)
4552				free(lun, M_CTL);
4553			be_lun->lun_config_status(be_lun->be_lun,
4554						  CTL_LUN_CONFIG_FAILURE);
4555			return (ENOSPC);
4556		}
4557		lun_number = be_lun->req_lun_id;
4558	} else {
4559		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4560		if (lun_number == -1) {
4561			mtx_unlock(&ctl_softc->ctl_lock);
4562			printf("ctl: can't allocate LUN on target %ju, out of "
4563			       "LUNs\n", (uintmax_t)target_id.id);
4564			if (lun->flags & CTL_LUN_MALLOCED)
4565				free(lun, M_CTL);
4566			be_lun->lun_config_status(be_lun->be_lun,
4567						  CTL_LUN_CONFIG_FAILURE);
4568			return (ENOSPC);
4569		}
4570	}
4571	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4572
4573	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4574	lun->target = target_id;
4575	lun->lun = lun_number;
4576	lun->be_lun = be_lun;
4577	/*
4578	 * The processor LUN is always enabled.  Disk LUNs come on line
4579	 * disabled, and must be enabled by the backend.
4580	 */
4581	lun->flags |= CTL_LUN_DISABLED;
4582	lun->backend = be_lun->be;
4583	be_lun->ctl_lun = lun;
4584	be_lun->lun_id = lun_number;
4585	atomic_add_int(&be_lun->be->num_luns, 1);
4586	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4587		lun->flags |= CTL_LUN_STOPPED;
4588
4589	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4590		lun->flags |= CTL_LUN_INOPERABLE;
4591
4592	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4593		lun->flags |= CTL_LUN_PRIMARY_SC;
4594
4595	lun->ctl_softc = ctl_softc;
4596	TAILQ_INIT(&lun->ooa_queue);
4597	TAILQ_INIT(&lun->blocked_queue);
4598	STAILQ_INIT(&lun->error_list);
4599	ctl_tpc_init(lun);
4600
4601	/*
4602	 * Initialize the mode page index.
4603	 */
4604	ctl_init_page_index(lun);
4605
4606	/*
4607	 * Set the poweron UA for all initiators on this LUN only.
4608	 */
4609	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4610		lun->pending_ua[i] = CTL_UA_POWERON;
4611
4612	/*
4613	 * Now, before we insert this lun on the lun list, set the lun
4614	 * inventory changed UA for all other luns.
4615	 */
4616	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4617		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4618			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4619		}
4620	}
4621
4622	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4623
4624	ctl_softc->ctl_luns[lun_number] = lun;
4625
4626	ctl_softc->num_luns++;
4627
4628	/* Setup statistics gathering */
4629	lun->stats.device_type = be_lun->lun_type;
4630	lun->stats.lun_number = lun_number;
4631	if (lun->stats.device_type == T_DIRECT)
4632		lun->stats.blocksize = be_lun->blocksize;
4633	else
4634		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4635	for (i = 0;i < CTL_MAX_PORTS;i++)
4636		lun->stats.ports[i].targ_port = i;
4637
4638	mtx_unlock(&ctl_softc->ctl_lock);
4639
4640	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4641
4642	/*
4643	 * Run through each registered FETD and bring it online if it isn't
4644	 * already.  Enable the target ID if it hasn't been enabled, and
4645	 * enable this particular LUN.
4646	 */
4647	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4648		int retval;
4649
4650		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4651		if (retval != 0) {
4652			printf("ctl_alloc_lun: FETD %s port %d returned error "
4653			       "%d for lun_enable on target %ju lun %d\n",
4654			       port->port_name, port->targ_port, retval,
4655			       (uintmax_t)target_id.id, lun_number);
4656		} else
4657			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4658	}
4659	return (0);
4660}
4661
4662/*
4663 * Delete a LUN.
4664 * Assumptions:
4665 * - LUN has already been marked invalid and any pending I/O has been taken
4666 *   care of.
4667 */
4668static int
4669ctl_free_lun(struct ctl_lun *lun)
4670{
4671	struct ctl_softc *softc;
4672#if 0
4673	struct ctl_port *port;
4674#endif
4675	struct ctl_lun *nlun;
4676	int i;
4677
4678	softc = lun->ctl_softc;
4679
4680	mtx_assert(&softc->ctl_lock, MA_OWNED);
4681
4682	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4683
4684	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4685
4686	softc->ctl_luns[lun->lun] = NULL;
4687
4688	if (!TAILQ_EMPTY(&lun->ooa_queue))
4689		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4690
4691	softc->num_luns--;
4692
4693	/*
4694	 * XXX KDM this scheme only works for a single target/multiple LUN
4695	 * setup.  It needs to be revamped for a multiple target scheme.
4696	 *
4697	 * XXX KDM this results in port->lun_disable() getting called twice,
4698	 * once when ctl_disable_lun() is called, and a second time here.
4699	 * We really need to re-think the LUN disable semantics.  There
4700	 * should probably be several steps/levels to LUN removal:
4701	 *  - disable
4702	 *  - invalidate
4703	 *  - free
4704 	 *
4705	 * Right now we only have a disable method when communicating to
4706	 * the front end ports, at least for individual LUNs.
4707	 */
4708#if 0
4709	STAILQ_FOREACH(port, &softc->port_list, links) {
4710		int retval;
4711
4712		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4713					 lun->lun);
4714		if (retval != 0) {
4715			printf("ctl_free_lun: FETD %s port %d returned error "
4716			       "%d for lun_disable on target %ju lun %jd\n",
4717			       port->port_name, port->targ_port, retval,
4718			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4719		}
4720
4721		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4722			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4723
4724			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4725			if (retval != 0) {
4726				printf("ctl_free_lun: FETD %s port %d "
4727				       "returned error %d for targ_disable on "
4728				       "target %ju\n", port->port_name,
4729				       port->targ_port, retval,
4730				       (uintmax_t)lun->target.id);
4731			} else
4732				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4733
4734			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4735				continue;
4736
4737#if 0
4738			port->port_offline(port->onoff_arg);
4739			port->status &= ~CTL_PORT_STATUS_ONLINE;
4740#endif
4741		}
4742	}
4743#endif
4744
4745	/*
4746	 * Tell the backend to free resources, if this LUN has a backend.
4747	 */
4748	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4749	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4750
4751	ctl_tpc_shutdown(lun);
4752	mtx_destroy(&lun->lun_lock);
4753	free(lun->lun_devid, M_CTL);
4754	if (lun->flags & CTL_LUN_MALLOCED)
4755		free(lun, M_CTL);
4756
4757	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4758		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4759			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4760		}
4761	}
4762
4763	return (0);
4764}
4765
4766static void
4767ctl_create_lun(struct ctl_be_lun *be_lun)
4768{
4769	struct ctl_softc *ctl_softc;
4770
4771	ctl_softc = control_softc;
4772
4773	/*
4774	 * ctl_alloc_lun() should handle all potential failure cases.
4775	 */
4776	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4777}
4778
4779int
4780ctl_add_lun(struct ctl_be_lun *be_lun)
4781{
4782	struct ctl_softc *ctl_softc = control_softc;
4783
4784	mtx_lock(&ctl_softc->ctl_lock);
4785	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4786	mtx_unlock(&ctl_softc->ctl_lock);
4787	wakeup(&ctl_softc->pending_lun_queue);
4788
4789	return (0);
4790}
4791
4792int
4793ctl_enable_lun(struct ctl_be_lun *be_lun)
4794{
4795	struct ctl_softc *ctl_softc;
4796	struct ctl_port *port, *nport;
4797	struct ctl_lun *lun;
4798	int retval;
4799
4800	ctl_softc = control_softc;
4801
4802	lun = (struct ctl_lun *)be_lun->ctl_lun;
4803
4804	mtx_lock(&ctl_softc->ctl_lock);
4805	mtx_lock(&lun->lun_lock);
4806	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4807		/*
4808		 * eh?  Why did we get called if the LUN is already
4809		 * enabled?
4810		 */
4811		mtx_unlock(&lun->lun_lock);
4812		mtx_unlock(&ctl_softc->ctl_lock);
4813		return (0);
4814	}
4815	lun->flags &= ~CTL_LUN_DISABLED;
4816	mtx_unlock(&lun->lun_lock);
4817
4818	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4819		nport = STAILQ_NEXT(port, links);
4820
4821		/*
4822		 * Drop the lock while we call the FETD's enable routine.
4823		 * This can lead to a callback into CTL (at least in the
4824		 * case of the internal initiator frontend.
4825		 */
4826		mtx_unlock(&ctl_softc->ctl_lock);
4827		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4828		mtx_lock(&ctl_softc->ctl_lock);
4829		if (retval != 0) {
4830			printf("%s: FETD %s port %d returned error "
4831			       "%d for lun_enable on target %ju lun %jd\n",
4832			       __func__, port->port_name, port->targ_port, retval,
4833			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4834		}
4835#if 0
4836		 else {
4837            /* NOTE:  TODO:  why does lun enable affect port status? */
4838			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4839		}
4840#endif
4841	}
4842
4843	mtx_unlock(&ctl_softc->ctl_lock);
4844
4845	return (0);
4846}
4847
4848int
4849ctl_disable_lun(struct ctl_be_lun *be_lun)
4850{
4851	struct ctl_softc *ctl_softc;
4852	struct ctl_port *port;
4853	struct ctl_lun *lun;
4854	int retval;
4855
4856	ctl_softc = control_softc;
4857
4858	lun = (struct ctl_lun *)be_lun->ctl_lun;
4859
4860	mtx_lock(&ctl_softc->ctl_lock);
4861	mtx_lock(&lun->lun_lock);
4862	if (lun->flags & CTL_LUN_DISABLED) {
4863		mtx_unlock(&lun->lun_lock);
4864		mtx_unlock(&ctl_softc->ctl_lock);
4865		return (0);
4866	}
4867	lun->flags |= CTL_LUN_DISABLED;
4868	mtx_unlock(&lun->lun_lock);
4869
4870	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4871		mtx_unlock(&ctl_softc->ctl_lock);
4872		/*
4873		 * Drop the lock before we call the frontend's disable
4874		 * routine, to avoid lock order reversals.
4875		 *
4876		 * XXX KDM what happens if the frontend list changes while
4877		 * we're traversing it?  It's unlikely, but should be handled.
4878		 */
4879		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4880					 lun->lun);
4881		mtx_lock(&ctl_softc->ctl_lock);
4882		if (retval != 0) {
4883			printf("ctl_alloc_lun: FETD %s port %d returned error "
4884			       "%d for lun_disable on target %ju lun %jd\n",
4885			       port->port_name, port->targ_port, retval,
4886			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4887		}
4888	}
4889
4890	mtx_unlock(&ctl_softc->ctl_lock);
4891
4892	return (0);
4893}
4894
4895int
4896ctl_start_lun(struct ctl_be_lun *be_lun)
4897{
4898	struct ctl_softc *ctl_softc;
4899	struct ctl_lun *lun;
4900
4901	ctl_softc = control_softc;
4902
4903	lun = (struct ctl_lun *)be_lun->ctl_lun;
4904
4905	mtx_lock(&lun->lun_lock);
4906	lun->flags &= ~CTL_LUN_STOPPED;
4907	mtx_unlock(&lun->lun_lock);
4908
4909	return (0);
4910}
4911
4912int
4913ctl_stop_lun(struct ctl_be_lun *be_lun)
4914{
4915	struct ctl_softc *ctl_softc;
4916	struct ctl_lun *lun;
4917
4918	ctl_softc = control_softc;
4919
4920	lun = (struct ctl_lun *)be_lun->ctl_lun;
4921
4922	mtx_lock(&lun->lun_lock);
4923	lun->flags |= CTL_LUN_STOPPED;
4924	mtx_unlock(&lun->lun_lock);
4925
4926	return (0);
4927}
4928
4929int
4930ctl_lun_offline(struct ctl_be_lun *be_lun)
4931{
4932	struct ctl_softc *ctl_softc;
4933	struct ctl_lun *lun;
4934
4935	ctl_softc = control_softc;
4936
4937	lun = (struct ctl_lun *)be_lun->ctl_lun;
4938
4939	mtx_lock(&lun->lun_lock);
4940	lun->flags |= CTL_LUN_OFFLINE;
4941	mtx_unlock(&lun->lun_lock);
4942
4943	return (0);
4944}
4945
4946int
4947ctl_lun_online(struct ctl_be_lun *be_lun)
4948{
4949	struct ctl_softc *ctl_softc;
4950	struct ctl_lun *lun;
4951
4952	ctl_softc = control_softc;
4953
4954	lun = (struct ctl_lun *)be_lun->ctl_lun;
4955
4956	mtx_lock(&lun->lun_lock);
4957	lun->flags &= ~CTL_LUN_OFFLINE;
4958	mtx_unlock(&lun->lun_lock);
4959
4960	return (0);
4961}
4962
4963int
4964ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4965{
4966	struct ctl_softc *ctl_softc;
4967	struct ctl_lun *lun;
4968
4969	ctl_softc = control_softc;
4970
4971	lun = (struct ctl_lun *)be_lun->ctl_lun;
4972
4973	mtx_lock(&lun->lun_lock);
4974
4975	/*
4976	 * The LUN needs to be disabled before it can be marked invalid.
4977	 */
4978	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4979		mtx_unlock(&lun->lun_lock);
4980		return (-1);
4981	}
4982	/*
4983	 * Mark the LUN invalid.
4984	 */
4985	lun->flags |= CTL_LUN_INVALID;
4986
4987	/*
4988	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4989	 * If we have something in the OOA queue, we'll free it when the
4990	 * last I/O completes.
4991	 */
4992	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4993		mtx_unlock(&lun->lun_lock);
4994		mtx_lock(&ctl_softc->ctl_lock);
4995		ctl_free_lun(lun);
4996		mtx_unlock(&ctl_softc->ctl_lock);
4997	} else
4998		mtx_unlock(&lun->lun_lock);
4999
5000	return (0);
5001}
5002
5003int
5004ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5005{
5006	struct ctl_softc *ctl_softc;
5007	struct ctl_lun *lun;
5008
5009	ctl_softc = control_softc;
5010	lun = (struct ctl_lun *)be_lun->ctl_lun;
5011
5012	mtx_lock(&lun->lun_lock);
5013	lun->flags |= CTL_LUN_INOPERABLE;
5014	mtx_unlock(&lun->lun_lock);
5015
5016	return (0);
5017}
5018
5019int
5020ctl_lun_operable(struct ctl_be_lun *be_lun)
5021{
5022	struct ctl_softc *ctl_softc;
5023	struct ctl_lun *lun;
5024
5025	ctl_softc = control_softc;
5026	lun = (struct ctl_lun *)be_lun->ctl_lun;
5027
5028	mtx_lock(&lun->lun_lock);
5029	lun->flags &= ~CTL_LUN_INOPERABLE;
5030	mtx_unlock(&lun->lun_lock);
5031
5032	return (0);
5033}
5034
5035int
5036ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5037		   int lock)
5038{
5039	struct ctl_softc *softc;
5040	struct ctl_lun *lun;
5041	struct copan_aps_subpage *current_sp;
5042	struct ctl_page_index *page_index;
5043	int i;
5044
5045	softc = control_softc;
5046
5047	mtx_lock(&softc->ctl_lock);
5048
5049	lun = (struct ctl_lun *)be_lun->ctl_lun;
5050	mtx_lock(&lun->lun_lock);
5051
5052	page_index = NULL;
5053	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5054		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5055		     APS_PAGE_CODE)
5056			continue;
5057
5058		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5059			continue;
5060		page_index = &lun->mode_pages.index[i];
5061	}
5062
5063	if (page_index == NULL) {
5064		mtx_unlock(&lun->lun_lock);
5065		mtx_unlock(&softc->ctl_lock);
5066		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5067		       (uintmax_t)lun->lun);
5068		return (1);
5069	}
5070#if 0
5071	if ((softc->aps_locked_lun != 0)
5072	 && (softc->aps_locked_lun != lun->lun)) {
5073		printf("%s: attempt to lock LUN %llu when %llu is already "
5074		       "locked\n");
5075		mtx_unlock(&lun->lun_lock);
5076		mtx_unlock(&softc->ctl_lock);
5077		return (1);
5078	}
5079#endif
5080
5081	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5082		(page_index->page_len * CTL_PAGE_CURRENT));
5083
5084	if (lock != 0) {
5085		current_sp->lock_active = APS_LOCK_ACTIVE;
5086		softc->aps_locked_lun = lun->lun;
5087	} else {
5088		current_sp->lock_active = 0;
5089		softc->aps_locked_lun = 0;
5090	}
5091
5092
5093	/*
5094	 * If we're in HA mode, try to send the lock message to the other
5095	 * side.
5096	 */
5097	if (ctl_is_single == 0) {
5098		int isc_retval;
5099		union ctl_ha_msg lock_msg;
5100
5101		lock_msg.hdr.nexus = *nexus;
5102		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5103		if (lock != 0)
5104			lock_msg.aps.lock_flag = 1;
5105		else
5106			lock_msg.aps.lock_flag = 0;
5107		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5108					 sizeof(lock_msg), 0);
5109		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5110			printf("%s: APS (lock=%d) error returned from "
5111			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5112			mtx_unlock(&lun->lun_lock);
5113			mtx_unlock(&softc->ctl_lock);
5114			return (1);
5115		}
5116	}
5117
5118	mtx_unlock(&lun->lun_lock);
5119	mtx_unlock(&softc->ctl_lock);
5120
5121	return (0);
5122}
5123
5124void
5125ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5126{
5127	struct ctl_lun *lun;
5128	struct ctl_softc *softc;
5129	int i;
5130
5131	softc = control_softc;
5132
5133	lun = (struct ctl_lun *)be_lun->ctl_lun;
5134
5135	mtx_lock(&lun->lun_lock);
5136
5137	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5138		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5139
5140	mtx_unlock(&lun->lun_lock);
5141}
5142
5143/*
5144 * Backend "memory move is complete" callback for requests that never
5145 * make it down to say RAIDCore's configuration code.
5146 */
5147int
5148ctl_config_move_done(union ctl_io *io)
5149{
5150	int retval;
5151
5152	retval = CTL_RETVAL_COMPLETE;
5153
5154
5155	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5156	/*
5157	 * XXX KDM this shouldn't happen, but what if it does?
5158	 */
5159	if (io->io_hdr.io_type != CTL_IO_SCSI)
5160		panic("I/O type isn't CTL_IO_SCSI!");
5161
5162	if ((io->io_hdr.port_status == 0)
5163	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5164	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5165		io->io_hdr.status = CTL_SUCCESS;
5166	else if ((io->io_hdr.port_status != 0)
5167	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5168	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5169		/*
5170		 * For hardware error sense keys, the sense key
5171		 * specific value is defined to be a retry count,
5172		 * but we use it to pass back an internal FETD
5173		 * error code.  XXX KDM  Hopefully the FETD is only
5174		 * using 16 bits for an error code, since that's
5175		 * all the space we have in the sks field.
5176		 */
5177		ctl_set_internal_failure(&io->scsiio,
5178					 /*sks_valid*/ 1,
5179					 /*retry_count*/
5180					 io->io_hdr.port_status);
5181		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5182			free(io->scsiio.kern_data_ptr, M_CTL);
5183		ctl_done(io);
5184		goto bailout;
5185	}
5186
5187	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5188	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5189	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5190		/*
5191		 * XXX KDM just assuming a single pointer here, and not a
5192		 * S/G list.  If we start using S/G lists for config data,
5193		 * we'll need to know how to clean them up here as well.
5194		 */
5195		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5196			free(io->scsiio.kern_data_ptr, M_CTL);
5197		/* Hopefully the user has already set the status... */
5198		ctl_done(io);
5199	} else {
5200		/*
5201		 * XXX KDM now we need to continue data movement.  Some
5202		 * options:
5203		 * - call ctl_scsiio() again?  We don't do this for data
5204		 *   writes, because for those at least we know ahead of
5205		 *   time where the write will go and how long it is.  For
5206		 *   config writes, though, that information is largely
5207		 *   contained within the write itself, thus we need to
5208		 *   parse out the data again.
5209		 *
5210		 * - Call some other function once the data is in?
5211		 */
5212
5213		/*
5214		 * XXX KDM call ctl_scsiio() again for now, and check flag
5215		 * bits to see whether we're allocated or not.
5216		 */
5217		retval = ctl_scsiio(&io->scsiio);
5218	}
5219bailout:
5220	return (retval);
5221}
5222
5223/*
5224 * This gets called by a backend driver when it is done with a
5225 * data_submit method.
5226 */
5227void
5228ctl_data_submit_done(union ctl_io *io)
5229{
5230	/*
5231	 * If the IO_CONT flag is set, we need to call the supplied
5232	 * function to continue processing the I/O, instead of completing
5233	 * the I/O just yet.
5234	 *
5235	 * If there is an error, though, we don't want to keep processing.
5236	 * Instead, just send status back to the initiator.
5237	 */
5238	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5239	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5240	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5241	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5242		io->scsiio.io_cont(io);
5243		return;
5244	}
5245	ctl_done(io);
5246}
5247
5248/*
5249 * This gets called by a backend driver when it is done with a
5250 * configuration write.
5251 */
5252void
5253ctl_config_write_done(union ctl_io *io)
5254{
5255	/*
5256	 * If the IO_CONT flag is set, we need to call the supplied
5257	 * function to continue processing the I/O, instead of completing
5258	 * the I/O just yet.
5259	 *
5260	 * If there is an error, though, we don't want to keep processing.
5261	 * Instead, just send status back to the initiator.
5262	 */
5263	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5264	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5265	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5266		io->scsiio.io_cont(io);
5267		return;
5268	}
5269	/*
5270	 * Since a configuration write can be done for commands that actually
5271	 * have data allocated, like write buffer, and commands that have
5272	 * no data, like start/stop unit, we need to check here.
5273	 */
5274	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5275		free(io->scsiio.kern_data_ptr, M_CTL);
5276	ctl_done(io);
5277}
5278
5279/*
5280 * SCSI release command.
5281 */
5282int
5283ctl_scsi_release(struct ctl_scsiio *ctsio)
5284{
5285	int length, longid, thirdparty_id, resv_id;
5286	struct ctl_softc *ctl_softc;
5287	struct ctl_lun *lun;
5288
5289	length = 0;
5290	resv_id = 0;
5291
5292	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5293
5294	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5295	ctl_softc = control_softc;
5296
5297	switch (ctsio->cdb[0]) {
5298	case RELEASE_10: {
5299		struct scsi_release_10 *cdb;
5300
5301		cdb = (struct scsi_release_10 *)ctsio->cdb;
5302
5303		if (cdb->byte2 & SR10_LONGID)
5304			longid = 1;
5305		else
5306			thirdparty_id = cdb->thirdparty_id;
5307
5308		resv_id = cdb->resv_id;
5309		length = scsi_2btoul(cdb->length);
5310		break;
5311	}
5312	}
5313
5314
5315	/*
5316	 * XXX KDM right now, we only support LUN reservation.  We don't
5317	 * support 3rd party reservations, or extent reservations, which
5318	 * might actually need the parameter list.  If we've gotten this
5319	 * far, we've got a LUN reservation.  Anything else got kicked out
5320	 * above.  So, according to SPC, ignore the length.
5321	 */
5322	length = 0;
5323
5324	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5325	 && (length > 0)) {
5326		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5327		ctsio->kern_data_len = length;
5328		ctsio->kern_total_len = length;
5329		ctsio->kern_data_resid = 0;
5330		ctsio->kern_rel_offset = 0;
5331		ctsio->kern_sg_entries = 0;
5332		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5333		ctsio->be_move_done = ctl_config_move_done;
5334		ctl_datamove((union ctl_io *)ctsio);
5335
5336		return (CTL_RETVAL_COMPLETE);
5337	}
5338
5339	if (length > 0)
5340		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5341
5342	mtx_lock(&lun->lun_lock);
5343
5344	/*
5345	 * According to SPC, it is not an error for an intiator to attempt
5346	 * to release a reservation on a LUN that isn't reserved, or that
5347	 * is reserved by another initiator.  The reservation can only be
5348	 * released, though, by the initiator who made it or by one of
5349	 * several reset type events.
5350	 */
5351	if (lun->flags & CTL_LUN_RESERVED) {
5352		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5353		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5354		 && (ctsio->io_hdr.nexus.targ_target.id ==
5355		     lun->rsv_nexus.targ_target.id)) {
5356			lun->flags &= ~CTL_LUN_RESERVED;
5357		}
5358	}
5359
5360	mtx_unlock(&lun->lun_lock);
5361
5362	ctsio->scsi_status = SCSI_STATUS_OK;
5363	ctsio->io_hdr.status = CTL_SUCCESS;
5364
5365	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5366		free(ctsio->kern_data_ptr, M_CTL);
5367		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5368	}
5369
5370	ctl_done((union ctl_io *)ctsio);
5371	return (CTL_RETVAL_COMPLETE);
5372}
5373
5374int
5375ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5376{
5377	int extent, thirdparty, longid;
5378	int resv_id, length;
5379	uint64_t thirdparty_id;
5380	struct ctl_softc *ctl_softc;
5381	struct ctl_lun *lun;
5382
5383	extent = 0;
5384	thirdparty = 0;
5385	longid = 0;
5386	resv_id = 0;
5387	length = 0;
5388	thirdparty_id = 0;
5389
5390	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5391
5392	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5393	ctl_softc = control_softc;
5394
5395	switch (ctsio->cdb[0]) {
5396	case RESERVE_10: {
5397		struct scsi_reserve_10 *cdb;
5398
5399		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5400
5401		if (cdb->byte2 & SR10_LONGID)
5402			longid = 1;
5403		else
5404			thirdparty_id = cdb->thirdparty_id;
5405
5406		resv_id = cdb->resv_id;
5407		length = scsi_2btoul(cdb->length);
5408		break;
5409	}
5410	}
5411
5412	/*
5413	 * XXX KDM right now, we only support LUN reservation.  We don't
5414	 * support 3rd party reservations, or extent reservations, which
5415	 * might actually need the parameter list.  If we've gotten this
5416	 * far, we've got a LUN reservation.  Anything else got kicked out
5417	 * above.  So, according to SPC, ignore the length.
5418	 */
5419	length = 0;
5420
5421	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5422	 && (length > 0)) {
5423		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5424		ctsio->kern_data_len = length;
5425		ctsio->kern_total_len = length;
5426		ctsio->kern_data_resid = 0;
5427		ctsio->kern_rel_offset = 0;
5428		ctsio->kern_sg_entries = 0;
5429		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5430		ctsio->be_move_done = ctl_config_move_done;
5431		ctl_datamove((union ctl_io *)ctsio);
5432
5433		return (CTL_RETVAL_COMPLETE);
5434	}
5435
5436	if (length > 0)
5437		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5438
5439	mtx_lock(&lun->lun_lock);
5440	if (lun->flags & CTL_LUN_RESERVED) {
5441		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5442		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5443		 || (ctsio->io_hdr.nexus.targ_target.id !=
5444		     lun->rsv_nexus.targ_target.id)) {
5445			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5446			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5447			goto bailout;
5448		}
5449	}
5450
5451	lun->flags |= CTL_LUN_RESERVED;
5452	lun->rsv_nexus = ctsio->io_hdr.nexus;
5453
5454	ctsio->scsi_status = SCSI_STATUS_OK;
5455	ctsio->io_hdr.status = CTL_SUCCESS;
5456
5457bailout:
5458	mtx_unlock(&lun->lun_lock);
5459
5460	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5461		free(ctsio->kern_data_ptr, M_CTL);
5462		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5463	}
5464
5465	ctl_done((union ctl_io *)ctsio);
5466	return (CTL_RETVAL_COMPLETE);
5467}
5468
5469int
5470ctl_start_stop(struct ctl_scsiio *ctsio)
5471{
5472	struct scsi_start_stop_unit *cdb;
5473	struct ctl_lun *lun;
5474	struct ctl_softc *ctl_softc;
5475	int retval;
5476
5477	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5478
5479	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5480	ctl_softc = control_softc;
5481	retval = 0;
5482
5483	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5484
5485	/*
5486	 * XXX KDM
5487	 * We don't support the immediate bit on a stop unit.  In order to
5488	 * do that, we would need to code up a way to know that a stop is
5489	 * pending, and hold off any new commands until it completes, one
5490	 * way or another.  Then we could accept or reject those commands
5491	 * depending on its status.  We would almost need to do the reverse
5492	 * of what we do below for an immediate start -- return the copy of
5493	 * the ctl_io to the FETD with status to send to the host (and to
5494	 * free the copy!) and then free the original I/O once the stop
5495	 * actually completes.  That way, the OOA queue mechanism can work
5496	 * to block commands that shouldn't proceed.  Another alternative
5497	 * would be to put the copy in the queue in place of the original,
5498	 * and return the original back to the caller.  That could be
5499	 * slightly safer..
5500	 */
5501	if ((cdb->byte2 & SSS_IMMED)
5502	 && ((cdb->how & SSS_START) == 0)) {
5503		ctl_set_invalid_field(ctsio,
5504				      /*sks_valid*/ 1,
5505				      /*command*/ 1,
5506				      /*field*/ 1,
5507				      /*bit_valid*/ 1,
5508				      /*bit*/ 0);
5509		ctl_done((union ctl_io *)ctsio);
5510		return (CTL_RETVAL_COMPLETE);
5511	}
5512
5513	if ((lun->flags & CTL_LUN_PR_RESERVED)
5514	 && ((cdb->how & SSS_START)==0)) {
5515		uint32_t residx;
5516
5517		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5518		if (!lun->per_res[residx].registered
5519		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5520
5521			ctl_set_reservation_conflict(ctsio);
5522			ctl_done((union ctl_io *)ctsio);
5523			return (CTL_RETVAL_COMPLETE);
5524		}
5525	}
5526
5527	/*
5528	 * If there is no backend on this device, we can't start or stop
5529	 * it.  In theory we shouldn't get any start/stop commands in the
5530	 * first place at this level if the LUN doesn't have a backend.
5531	 * That should get stopped by the command decode code.
5532	 */
5533	if (lun->backend == NULL) {
5534		ctl_set_invalid_opcode(ctsio);
5535		ctl_done((union ctl_io *)ctsio);
5536		return (CTL_RETVAL_COMPLETE);
5537	}
5538
5539	/*
5540	 * XXX KDM Copan-specific offline behavior.
5541	 * Figure out a reasonable way to port this?
5542	 */
5543#ifdef NEEDTOPORT
5544	mtx_lock(&lun->lun_lock);
5545
5546	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5547	 && (lun->flags & CTL_LUN_OFFLINE)) {
5548		/*
5549		 * If the LUN is offline, and the on/offline bit isn't set,
5550		 * reject the start or stop.  Otherwise, let it through.
5551		 */
5552		mtx_unlock(&lun->lun_lock);
5553		ctl_set_lun_not_ready(ctsio);
5554		ctl_done((union ctl_io *)ctsio);
5555	} else {
5556		mtx_unlock(&lun->lun_lock);
5557#endif /* NEEDTOPORT */
5558		/*
5559		 * This could be a start or a stop when we're online,
5560		 * or a stop/offline or start/online.  A start or stop when
5561		 * we're offline is covered in the case above.
5562		 */
5563		/*
5564		 * In the non-immediate case, we send the request to
5565		 * the backend and return status to the user when
5566		 * it is done.
5567		 *
5568		 * In the immediate case, we allocate a new ctl_io
5569		 * to hold a copy of the request, and send that to
5570		 * the backend.  We then set good status on the
5571		 * user's request and return it immediately.
5572		 */
5573		if (cdb->byte2 & SSS_IMMED) {
5574			union ctl_io *new_io;
5575
5576			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5577			if (new_io == NULL) {
5578				ctl_set_busy(ctsio);
5579				ctl_done((union ctl_io *)ctsio);
5580			} else {
5581				ctl_copy_io((union ctl_io *)ctsio,
5582					    new_io);
5583				retval = lun->backend->config_write(new_io);
5584				ctl_set_success(ctsio);
5585				ctl_done((union ctl_io *)ctsio);
5586			}
5587		} else {
5588			retval = lun->backend->config_write(
5589				(union ctl_io *)ctsio);
5590		}
5591#ifdef NEEDTOPORT
5592	}
5593#endif
5594	return (retval);
5595}
5596
5597/*
5598 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5599 * we don't really do anything with the LBA and length fields if the user
5600 * passes them in.  Instead we'll just flush out the cache for the entire
5601 * LUN.
5602 */
5603int
5604ctl_sync_cache(struct ctl_scsiio *ctsio)
5605{
5606	struct ctl_lun *lun;
5607	struct ctl_softc *ctl_softc;
5608	uint64_t starting_lba;
5609	uint32_t block_count;
5610	int retval;
5611
5612	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5613
5614	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5615	ctl_softc = control_softc;
5616	retval = 0;
5617
5618	switch (ctsio->cdb[0]) {
5619	case SYNCHRONIZE_CACHE: {
5620		struct scsi_sync_cache *cdb;
5621		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5622
5623		starting_lba = scsi_4btoul(cdb->begin_lba);
5624		block_count = scsi_2btoul(cdb->lb_count);
5625		break;
5626	}
5627	case SYNCHRONIZE_CACHE_16: {
5628		struct scsi_sync_cache_16 *cdb;
5629		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5630
5631		starting_lba = scsi_8btou64(cdb->begin_lba);
5632		block_count = scsi_4btoul(cdb->lb_count);
5633		break;
5634	}
5635	default:
5636		ctl_set_invalid_opcode(ctsio);
5637		ctl_done((union ctl_io *)ctsio);
5638		goto bailout;
5639		break; /* NOTREACHED */
5640	}
5641
5642	/*
5643	 * We check the LBA and length, but don't do anything with them.
5644	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5645	 * get flushed.  This check will just help satisfy anyone who wants
5646	 * to see an error for an out of range LBA.
5647	 */
5648	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5649		ctl_set_lba_out_of_range(ctsio);
5650		ctl_done((union ctl_io *)ctsio);
5651		goto bailout;
5652	}
5653
5654	/*
5655	 * If this LUN has no backend, we can't flush the cache anyway.
5656	 */
5657	if (lun->backend == NULL) {
5658		ctl_set_invalid_opcode(ctsio);
5659		ctl_done((union ctl_io *)ctsio);
5660		goto bailout;
5661	}
5662
5663	/*
5664	 * Check to see whether we're configured to send the SYNCHRONIZE
5665	 * CACHE command directly to the back end.
5666	 */
5667	mtx_lock(&lun->lun_lock);
5668	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5669	 && (++(lun->sync_count) >= lun->sync_interval)) {
5670		lun->sync_count = 0;
5671		mtx_unlock(&lun->lun_lock);
5672		retval = lun->backend->config_write((union ctl_io *)ctsio);
5673	} else {
5674		mtx_unlock(&lun->lun_lock);
5675		ctl_set_success(ctsio);
5676		ctl_done((union ctl_io *)ctsio);
5677	}
5678
5679bailout:
5680
5681	return (retval);
5682}
5683
5684int
5685ctl_format(struct ctl_scsiio *ctsio)
5686{
5687	struct scsi_format *cdb;
5688	struct ctl_lun *lun;
5689	struct ctl_softc *ctl_softc;
5690	int length, defect_list_len;
5691
5692	CTL_DEBUG_PRINT(("ctl_format\n"));
5693
5694	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5695	ctl_softc = control_softc;
5696
5697	cdb = (struct scsi_format *)ctsio->cdb;
5698
5699	length = 0;
5700	if (cdb->byte2 & SF_FMTDATA) {
5701		if (cdb->byte2 & SF_LONGLIST)
5702			length = sizeof(struct scsi_format_header_long);
5703		else
5704			length = sizeof(struct scsi_format_header_short);
5705	}
5706
5707	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5708	 && (length > 0)) {
5709		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5710		ctsio->kern_data_len = length;
5711		ctsio->kern_total_len = length;
5712		ctsio->kern_data_resid = 0;
5713		ctsio->kern_rel_offset = 0;
5714		ctsio->kern_sg_entries = 0;
5715		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5716		ctsio->be_move_done = ctl_config_move_done;
5717		ctl_datamove((union ctl_io *)ctsio);
5718
5719		return (CTL_RETVAL_COMPLETE);
5720	}
5721
5722	defect_list_len = 0;
5723
5724	if (cdb->byte2 & SF_FMTDATA) {
5725		if (cdb->byte2 & SF_LONGLIST) {
5726			struct scsi_format_header_long *header;
5727
5728			header = (struct scsi_format_header_long *)
5729				ctsio->kern_data_ptr;
5730
5731			defect_list_len = scsi_4btoul(header->defect_list_len);
5732			if (defect_list_len != 0) {
5733				ctl_set_invalid_field(ctsio,
5734						      /*sks_valid*/ 1,
5735						      /*command*/ 0,
5736						      /*field*/ 2,
5737						      /*bit_valid*/ 0,
5738						      /*bit*/ 0);
5739				goto bailout;
5740			}
5741		} else {
5742			struct scsi_format_header_short *header;
5743
5744			header = (struct scsi_format_header_short *)
5745				ctsio->kern_data_ptr;
5746
5747			defect_list_len = scsi_2btoul(header->defect_list_len);
5748			if (defect_list_len != 0) {
5749				ctl_set_invalid_field(ctsio,
5750						      /*sks_valid*/ 1,
5751						      /*command*/ 0,
5752						      /*field*/ 2,
5753						      /*bit_valid*/ 0,
5754						      /*bit*/ 0);
5755				goto bailout;
5756			}
5757		}
5758	}
5759
5760	/*
5761	 * The format command will clear out the "Medium format corrupted"
5762	 * status if set by the configuration code.  That status is really
5763	 * just a way to notify the host that we have lost the media, and
5764	 * get them to issue a command that will basically make them think
5765	 * they're blowing away the media.
5766	 */
5767	mtx_lock(&lun->lun_lock);
5768	lun->flags &= ~CTL_LUN_INOPERABLE;
5769	mtx_unlock(&lun->lun_lock);
5770
5771	ctsio->scsi_status = SCSI_STATUS_OK;
5772	ctsio->io_hdr.status = CTL_SUCCESS;
5773bailout:
5774
5775	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5776		free(ctsio->kern_data_ptr, M_CTL);
5777		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5778	}
5779
5780	ctl_done((union ctl_io *)ctsio);
5781	return (CTL_RETVAL_COMPLETE);
5782}
5783
5784int
5785ctl_read_buffer(struct ctl_scsiio *ctsio)
5786{
5787	struct scsi_read_buffer *cdb;
5788	struct ctl_lun *lun;
5789	int buffer_offset, len;
5790	static uint8_t descr[4];
5791	static uint8_t echo_descr[4] = { 0 };
5792
5793	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5794
5795	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5796	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5797
5798	if (lun->flags & CTL_LUN_PR_RESERVED) {
5799		uint32_t residx;
5800
5801		/*
5802		 * XXX KDM need a lock here.
5803		 */
5804		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5805		if ((lun->res_type == SPR_TYPE_EX_AC
5806		  && residx != lun->pr_res_idx)
5807		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5808		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5809		  && !lun->per_res[residx].registered)) {
5810			ctl_set_reservation_conflict(ctsio);
5811			ctl_done((union ctl_io *)ctsio);
5812			return (CTL_RETVAL_COMPLETE);
5813	        }
5814	}
5815
5816	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5817	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5818	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5819		ctl_set_invalid_field(ctsio,
5820				      /*sks_valid*/ 1,
5821				      /*command*/ 1,
5822				      /*field*/ 1,
5823				      /*bit_valid*/ 1,
5824				      /*bit*/ 4);
5825		ctl_done((union ctl_io *)ctsio);
5826		return (CTL_RETVAL_COMPLETE);
5827	}
5828
5829	len = scsi_3btoul(cdb->length);
5830	buffer_offset = scsi_3btoul(cdb->offset);
5831
5832	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5833		ctl_set_invalid_field(ctsio,
5834				      /*sks_valid*/ 1,
5835				      /*command*/ 1,
5836				      /*field*/ 6,
5837				      /*bit_valid*/ 0,
5838				      /*bit*/ 0);
5839		ctl_done((union ctl_io *)ctsio);
5840		return (CTL_RETVAL_COMPLETE);
5841	}
5842
5843	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5844		descr[0] = 0;
5845		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5846		ctsio->kern_data_ptr = descr;
5847		len = min(len, sizeof(descr));
5848	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5849		ctsio->kern_data_ptr = echo_descr;
5850		len = min(len, sizeof(echo_descr));
5851	} else
5852		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5853	ctsio->kern_data_len = len;
5854	ctsio->kern_total_len = len;
5855	ctsio->kern_data_resid = 0;
5856	ctsio->kern_rel_offset = 0;
5857	ctsio->kern_sg_entries = 0;
5858	ctsio->be_move_done = ctl_config_move_done;
5859	ctl_datamove((union ctl_io *)ctsio);
5860
5861	return (CTL_RETVAL_COMPLETE);
5862}
5863
5864int
5865ctl_write_buffer(struct ctl_scsiio *ctsio)
5866{
5867	struct scsi_write_buffer *cdb;
5868	struct ctl_lun *lun;
5869	int buffer_offset, len;
5870
5871	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5872
5873	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5874	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5875
5876	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5877		ctl_set_invalid_field(ctsio,
5878				      /*sks_valid*/ 1,
5879				      /*command*/ 1,
5880				      /*field*/ 1,
5881				      /*bit_valid*/ 1,
5882				      /*bit*/ 4);
5883		ctl_done((union ctl_io *)ctsio);
5884		return (CTL_RETVAL_COMPLETE);
5885	}
5886
5887	len = scsi_3btoul(cdb->length);
5888	buffer_offset = scsi_3btoul(cdb->offset);
5889
5890	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5891		ctl_set_invalid_field(ctsio,
5892				      /*sks_valid*/ 1,
5893				      /*command*/ 1,
5894				      /*field*/ 6,
5895				      /*bit_valid*/ 0,
5896				      /*bit*/ 0);
5897		ctl_done((union ctl_io *)ctsio);
5898		return (CTL_RETVAL_COMPLETE);
5899	}
5900
5901	/*
5902	 * If we've got a kernel request that hasn't been malloced yet,
5903	 * malloc it and tell the caller the data buffer is here.
5904	 */
5905	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5906		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5907		ctsio->kern_data_len = len;
5908		ctsio->kern_total_len = len;
5909		ctsio->kern_data_resid = 0;
5910		ctsio->kern_rel_offset = 0;
5911		ctsio->kern_sg_entries = 0;
5912		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5913		ctsio->be_move_done = ctl_config_move_done;
5914		ctl_datamove((union ctl_io *)ctsio);
5915
5916		return (CTL_RETVAL_COMPLETE);
5917	}
5918
5919	ctl_done((union ctl_io *)ctsio);
5920
5921	return (CTL_RETVAL_COMPLETE);
5922}
5923
5924int
5925ctl_write_same(struct ctl_scsiio *ctsio)
5926{
5927	struct ctl_lun *lun;
5928	struct ctl_lba_len_flags *lbalen;
5929	uint64_t lba;
5930	uint32_t num_blocks;
5931	int len, retval;
5932	uint8_t byte2;
5933
5934	retval = CTL_RETVAL_COMPLETE;
5935
5936	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5937
5938	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5939
5940	switch (ctsio->cdb[0]) {
5941	case WRITE_SAME_10: {
5942		struct scsi_write_same_10 *cdb;
5943
5944		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5945
5946		lba = scsi_4btoul(cdb->addr);
5947		num_blocks = scsi_2btoul(cdb->length);
5948		byte2 = cdb->byte2;
5949		break;
5950	}
5951	case WRITE_SAME_16: {
5952		struct scsi_write_same_16 *cdb;
5953
5954		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5955
5956		lba = scsi_8btou64(cdb->addr);
5957		num_blocks = scsi_4btoul(cdb->length);
5958		byte2 = cdb->byte2;
5959		break;
5960	}
5961	default:
5962		/*
5963		 * We got a command we don't support.  This shouldn't
5964		 * happen, commands should be filtered out above us.
5965		 */
5966		ctl_set_invalid_opcode(ctsio);
5967		ctl_done((union ctl_io *)ctsio);
5968
5969		return (CTL_RETVAL_COMPLETE);
5970		break; /* NOTREACHED */
5971	}
5972
5973	/*
5974	 * The first check is to make sure we're in bounds, the second
5975	 * check is to catch wrap-around problems.  If the lba + num blocks
5976	 * is less than the lba, then we've wrapped around and the block
5977	 * range is invalid anyway.
5978	 */
5979	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5980	 || ((lba + num_blocks) < lba)) {
5981		ctl_set_lba_out_of_range(ctsio);
5982		ctl_done((union ctl_io *)ctsio);
5983		return (CTL_RETVAL_COMPLETE);
5984	}
5985
5986	/* Zero number of blocks means "to the last logical block" */
5987	if (num_blocks == 0) {
5988		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5989			ctl_set_invalid_field(ctsio,
5990					      /*sks_valid*/ 0,
5991					      /*command*/ 1,
5992					      /*field*/ 0,
5993					      /*bit_valid*/ 0,
5994					      /*bit*/ 0);
5995			ctl_done((union ctl_io *)ctsio);
5996			return (CTL_RETVAL_COMPLETE);
5997		}
5998		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5999	}
6000
6001	len = lun->be_lun->blocksize;
6002
6003	/*
6004	 * If we've got a kernel request that hasn't been malloced yet,
6005	 * malloc it and tell the caller the data buffer is here.
6006	 */
6007	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6008		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6009		ctsio->kern_data_len = len;
6010		ctsio->kern_total_len = len;
6011		ctsio->kern_data_resid = 0;
6012		ctsio->kern_rel_offset = 0;
6013		ctsio->kern_sg_entries = 0;
6014		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6015		ctsio->be_move_done = ctl_config_move_done;
6016		ctl_datamove((union ctl_io *)ctsio);
6017
6018		return (CTL_RETVAL_COMPLETE);
6019	}
6020
6021	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6022	lbalen->lba = lba;
6023	lbalen->len = num_blocks;
6024	lbalen->flags = byte2;
6025	retval = lun->backend->config_write((union ctl_io *)ctsio);
6026
6027	return (retval);
6028}
6029
6030int
6031ctl_unmap(struct ctl_scsiio *ctsio)
6032{
6033	struct ctl_lun *lun;
6034	struct scsi_unmap *cdb;
6035	struct ctl_ptr_len_flags *ptrlen;
6036	struct scsi_unmap_header *hdr;
6037	struct scsi_unmap_desc *buf, *end;
6038	uint64_t lba;
6039	uint32_t num_blocks;
6040	int len, retval;
6041	uint8_t byte2;
6042
6043	retval = CTL_RETVAL_COMPLETE;
6044
6045	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6046
6047	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6048	cdb = (struct scsi_unmap *)ctsio->cdb;
6049
6050	len = scsi_2btoul(cdb->length);
6051	byte2 = cdb->byte2;
6052
6053	/*
6054	 * If we've got a kernel request that hasn't been malloced yet,
6055	 * malloc it and tell the caller the data buffer is here.
6056	 */
6057	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6058		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6059		ctsio->kern_data_len = len;
6060		ctsio->kern_total_len = len;
6061		ctsio->kern_data_resid = 0;
6062		ctsio->kern_rel_offset = 0;
6063		ctsio->kern_sg_entries = 0;
6064		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6065		ctsio->be_move_done = ctl_config_move_done;
6066		ctl_datamove((union ctl_io *)ctsio);
6067
6068		return (CTL_RETVAL_COMPLETE);
6069	}
6070
6071	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6072	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6073	if (len < sizeof (*hdr) ||
6074	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6075	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6076	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6077		ctl_set_invalid_field(ctsio,
6078				      /*sks_valid*/ 0,
6079				      /*command*/ 0,
6080				      /*field*/ 0,
6081				      /*bit_valid*/ 0,
6082				      /*bit*/ 0);
6083		ctl_done((union ctl_io *)ctsio);
6084		return (CTL_RETVAL_COMPLETE);
6085	}
6086	len = scsi_2btoul(hdr->desc_length);
6087	buf = (struct scsi_unmap_desc *)(hdr + 1);
6088	end = buf + len / sizeof(*buf);
6089
6090	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6091	ptrlen->ptr = (void *)buf;
6092	ptrlen->len = len;
6093	ptrlen->flags = byte2;
6094
6095	for (; buf < end; buf++) {
6096		lba = scsi_8btou64(buf->lba);
6097		num_blocks = scsi_4btoul(buf->length);
6098		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6099		 || ((lba + num_blocks) < lba)) {
6100			ctl_set_lba_out_of_range(ctsio);
6101			ctl_done((union ctl_io *)ctsio);
6102			return (CTL_RETVAL_COMPLETE);
6103		}
6104	}
6105
6106	retval = lun->backend->config_write((union ctl_io *)ctsio);
6107
6108	return (retval);
6109}
6110
6111/*
6112 * Note that this function currently doesn't actually do anything inside
6113 * CTL to enforce things if the DQue bit is turned on.
6114 *
6115 * Also note that this function can't be used in the default case, because
6116 * the DQue bit isn't set in the changeable mask for the control mode page
6117 * anyway.  This is just here as an example for how to implement a page
6118 * handler, and a placeholder in case we want to allow the user to turn
6119 * tagged queueing on and off.
6120 *
6121 * The D_SENSE bit handling is functional, however, and will turn
6122 * descriptor sense on and off for a given LUN.
6123 */
6124int
6125ctl_control_page_handler(struct ctl_scsiio *ctsio,
6126			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6127{
6128	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6129	struct ctl_lun *lun;
6130	struct ctl_softc *softc;
6131	int set_ua;
6132	uint32_t initidx;
6133
6134	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6135	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6136	set_ua = 0;
6137
6138	user_cp = (struct scsi_control_page *)page_ptr;
6139	current_cp = (struct scsi_control_page *)
6140		(page_index->page_data + (page_index->page_len *
6141		CTL_PAGE_CURRENT));
6142	saved_cp = (struct scsi_control_page *)
6143		(page_index->page_data + (page_index->page_len *
6144		CTL_PAGE_SAVED));
6145
6146	softc = control_softc;
6147
6148	mtx_lock(&lun->lun_lock);
6149	if (((current_cp->rlec & SCP_DSENSE) == 0)
6150	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6151		/*
6152		 * Descriptor sense is currently turned off and the user
6153		 * wants to turn it on.
6154		 */
6155		current_cp->rlec |= SCP_DSENSE;
6156		saved_cp->rlec |= SCP_DSENSE;
6157		lun->flags |= CTL_LUN_SENSE_DESC;
6158		set_ua = 1;
6159	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6160		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6161		/*
6162		 * Descriptor sense is currently turned on, and the user
6163		 * wants to turn it off.
6164		 */
6165		current_cp->rlec &= ~SCP_DSENSE;
6166		saved_cp->rlec &= ~SCP_DSENSE;
6167		lun->flags &= ~CTL_LUN_SENSE_DESC;
6168		set_ua = 1;
6169	}
6170	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6171		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6172#ifdef NEEDTOPORT
6173			csevent_log(CSC_CTL | CSC_SHELF_SW |
6174				    CTL_UNTAG_TO_UNTAG,
6175				    csevent_LogType_Trace,
6176				    csevent_Severity_Information,
6177				    csevent_AlertLevel_Green,
6178				    csevent_FRU_Firmware,
6179				    csevent_FRU_Unknown,
6180				    "Received untagged to untagged transition");
6181#endif /* NEEDTOPORT */
6182		} else {
6183#ifdef NEEDTOPORT
6184			csevent_log(CSC_CTL | CSC_SHELF_SW |
6185				    CTL_UNTAG_TO_TAG,
6186				    csevent_LogType_ConfigChange,
6187				    csevent_Severity_Information,
6188				    csevent_AlertLevel_Green,
6189				    csevent_FRU_Firmware,
6190				    csevent_FRU_Unknown,
6191				    "Received untagged to tagged "
6192				    "queueing transition");
6193#endif /* NEEDTOPORT */
6194
6195			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6196			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6197			set_ua = 1;
6198		}
6199	} else {
6200		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6201#ifdef NEEDTOPORT
6202			csevent_log(CSC_CTL | CSC_SHELF_SW |
6203				    CTL_TAG_TO_UNTAG,
6204				    csevent_LogType_ConfigChange,
6205				    csevent_Severity_Warning,
6206				    csevent_AlertLevel_Yellow,
6207				    csevent_FRU_Firmware,
6208				    csevent_FRU_Unknown,
6209				    "Received tagged queueing to untagged "
6210				    "transition");
6211#endif /* NEEDTOPORT */
6212
6213			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6214			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6215			set_ua = 1;
6216		} else {
6217#ifdef NEEDTOPORT
6218			csevent_log(CSC_CTL | CSC_SHELF_SW |
6219				    CTL_TAG_TO_TAG,
6220				    csevent_LogType_Trace,
6221				    csevent_Severity_Information,
6222				    csevent_AlertLevel_Green,
6223				    csevent_FRU_Firmware,
6224				    csevent_FRU_Unknown,
6225				    "Received tagged queueing to tagged "
6226				    "queueing transition");
6227#endif /* NEEDTOPORT */
6228		}
6229	}
6230	if (set_ua != 0) {
6231		int i;
6232		/*
6233		 * Let other initiators know that the mode
6234		 * parameters for this LUN have changed.
6235		 */
6236		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6237			if (i == initidx)
6238				continue;
6239
6240			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6241		}
6242	}
6243	mtx_unlock(&lun->lun_lock);
6244
6245	return (0);
6246}
6247
6248int
6249ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6250		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6251{
6252	return (0);
6253}
6254
6255int
6256ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6257			   struct ctl_page_index *page_index, int pc)
6258{
6259	struct copan_power_subpage *page;
6260
6261	page = (struct copan_power_subpage *)page_index->page_data +
6262		(page_index->page_len * pc);
6263
6264	switch (pc) {
6265	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6266		/*
6267		 * We don't update the changable bits for this page.
6268		 */
6269		break;
6270	case SMS_PAGE_CTRL_CURRENT >> 6:
6271	case SMS_PAGE_CTRL_DEFAULT >> 6:
6272	case SMS_PAGE_CTRL_SAVED >> 6:
6273#ifdef NEEDTOPORT
6274		ctl_update_power_subpage(page);
6275#endif
6276		break;
6277	default:
6278#ifdef NEEDTOPORT
6279		EPRINT(0, "Invalid PC %d!!", pc);
6280#endif
6281		break;
6282	}
6283	return (0);
6284}
6285
6286
6287int
6288ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6289		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6290{
6291	struct copan_aps_subpage *user_sp;
6292	struct copan_aps_subpage *current_sp;
6293	union ctl_modepage_info *modepage_info;
6294	struct ctl_softc *softc;
6295	struct ctl_lun *lun;
6296	int retval;
6297
6298	retval = CTL_RETVAL_COMPLETE;
6299	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6300		     (page_index->page_len * CTL_PAGE_CURRENT));
6301	softc = control_softc;
6302	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6303
6304	user_sp = (struct copan_aps_subpage *)page_ptr;
6305
6306	modepage_info = (union ctl_modepage_info *)
6307		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6308
6309	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6310	modepage_info->header.subpage = page_index->subpage;
6311	modepage_info->aps.lock_active = user_sp->lock_active;
6312
6313	mtx_lock(&softc->ctl_lock);
6314
6315	/*
6316	 * If there is a request to lock the LUN and another LUN is locked
6317	 * this is an error. If the requested LUN is already locked ignore
6318	 * the request. If no LUN is locked attempt to lock it.
6319	 * if there is a request to unlock the LUN and the LUN is currently
6320	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6321	 * if another LUN is locked or no LUN is locked.
6322	 */
6323	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6324		if (softc->aps_locked_lun == lun->lun) {
6325			/*
6326			 * This LUN is already locked, so we're done.
6327			 */
6328			retval = CTL_RETVAL_COMPLETE;
6329		} else if (softc->aps_locked_lun == 0) {
6330			/*
6331			 * No one has the lock, pass the request to the
6332			 * backend.
6333			 */
6334			retval = lun->backend->config_write(
6335				(union ctl_io *)ctsio);
6336		} else {
6337			/*
6338			 * Someone else has the lock, throw out the request.
6339			 */
6340			ctl_set_already_locked(ctsio);
6341			free(ctsio->kern_data_ptr, M_CTL);
6342			ctl_done((union ctl_io *)ctsio);
6343
6344			/*
6345			 * Set the return value so that ctl_do_mode_select()
6346			 * won't try to complete the command.  We already
6347			 * completed it here.
6348			 */
6349			retval = CTL_RETVAL_ERROR;
6350		}
6351	} else if (softc->aps_locked_lun == lun->lun) {
6352		/*
6353		 * This LUN is locked, so pass the unlock request to the
6354		 * backend.
6355		 */
6356		retval = lun->backend->config_write((union ctl_io *)ctsio);
6357	}
6358	mtx_unlock(&softc->ctl_lock);
6359
6360	return (retval);
6361}
6362
6363int
6364ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6365				struct ctl_page_index *page_index,
6366				uint8_t *page_ptr)
6367{
6368	uint8_t *c;
6369	int i;
6370
6371	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6372	ctl_time_io_secs =
6373		(c[0] << 8) |
6374		(c[1] << 0) |
6375		0;
6376	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6377	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6378	printf("page data:");
6379	for (i=0; i<8; i++)
6380		printf(" %.2x",page_ptr[i]);
6381	printf("\n");
6382	return (0);
6383}
6384
6385int
6386ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6387			       struct ctl_page_index *page_index,
6388			       int pc)
6389{
6390	struct copan_debugconf_subpage *page;
6391
6392	page = (struct copan_debugconf_subpage *)page_index->page_data +
6393		(page_index->page_len * pc);
6394
6395	switch (pc) {
6396	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6397	case SMS_PAGE_CTRL_DEFAULT >> 6:
6398	case SMS_PAGE_CTRL_SAVED >> 6:
6399		/*
6400		 * We don't update the changable or default bits for this page.
6401		 */
6402		break;
6403	case SMS_PAGE_CTRL_CURRENT >> 6:
6404		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6405		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6406		break;
6407	default:
6408#ifdef NEEDTOPORT
6409		EPRINT(0, "Invalid PC %d!!", pc);
6410#endif /* NEEDTOPORT */
6411		break;
6412	}
6413	return (0);
6414}
6415
6416
6417static int
6418ctl_do_mode_select(union ctl_io *io)
6419{
6420	struct scsi_mode_page_header *page_header;
6421	struct ctl_page_index *page_index;
6422	struct ctl_scsiio *ctsio;
6423	int control_dev, page_len;
6424	int page_len_offset, page_len_size;
6425	union ctl_modepage_info *modepage_info;
6426	struct ctl_lun *lun;
6427	int *len_left, *len_used;
6428	int retval, i;
6429
6430	ctsio = &io->scsiio;
6431	page_index = NULL;
6432	page_len = 0;
6433	retval = CTL_RETVAL_COMPLETE;
6434
6435	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6436
6437	if (lun->be_lun->lun_type != T_DIRECT)
6438		control_dev = 1;
6439	else
6440		control_dev = 0;
6441
6442	modepage_info = (union ctl_modepage_info *)
6443		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6444	len_left = &modepage_info->header.len_left;
6445	len_used = &modepage_info->header.len_used;
6446
6447do_next_page:
6448
6449	page_header = (struct scsi_mode_page_header *)
6450		(ctsio->kern_data_ptr + *len_used);
6451
6452	if (*len_left == 0) {
6453		free(ctsio->kern_data_ptr, M_CTL);
6454		ctl_set_success(ctsio);
6455		ctl_done((union ctl_io *)ctsio);
6456		return (CTL_RETVAL_COMPLETE);
6457	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6458
6459		free(ctsio->kern_data_ptr, M_CTL);
6460		ctl_set_param_len_error(ctsio);
6461		ctl_done((union ctl_io *)ctsio);
6462		return (CTL_RETVAL_COMPLETE);
6463
6464	} else if ((page_header->page_code & SMPH_SPF)
6465		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6466
6467		free(ctsio->kern_data_ptr, M_CTL);
6468		ctl_set_param_len_error(ctsio);
6469		ctl_done((union ctl_io *)ctsio);
6470		return (CTL_RETVAL_COMPLETE);
6471	}
6472
6473
6474	/*
6475	 * XXX KDM should we do something with the block descriptor?
6476	 */
6477	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6478
6479		if ((control_dev != 0)
6480		 && (lun->mode_pages.index[i].page_flags &
6481		     CTL_PAGE_FLAG_DISK_ONLY))
6482			continue;
6483
6484		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6485		    (page_header->page_code & SMPH_PC_MASK))
6486			continue;
6487
6488		/*
6489		 * If neither page has a subpage code, then we've got a
6490		 * match.
6491		 */
6492		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6493		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6494			page_index = &lun->mode_pages.index[i];
6495			page_len = page_header->page_length;
6496			break;
6497		}
6498
6499		/*
6500		 * If both pages have subpages, then the subpage numbers
6501		 * have to match.
6502		 */
6503		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6504		  && (page_header->page_code & SMPH_SPF)) {
6505			struct scsi_mode_page_header_sp *sph;
6506
6507			sph = (struct scsi_mode_page_header_sp *)page_header;
6508
6509			if (lun->mode_pages.index[i].subpage ==
6510			    sph->subpage) {
6511				page_index = &lun->mode_pages.index[i];
6512				page_len = scsi_2btoul(sph->page_length);
6513				break;
6514			}
6515		}
6516	}
6517
6518	/*
6519	 * If we couldn't find the page, or if we don't have a mode select
6520	 * handler for it, send back an error to the user.
6521	 */
6522	if ((page_index == NULL)
6523	 || (page_index->select_handler == NULL)) {
6524		ctl_set_invalid_field(ctsio,
6525				      /*sks_valid*/ 1,
6526				      /*command*/ 0,
6527				      /*field*/ *len_used,
6528				      /*bit_valid*/ 0,
6529				      /*bit*/ 0);
6530		free(ctsio->kern_data_ptr, M_CTL);
6531		ctl_done((union ctl_io *)ctsio);
6532		return (CTL_RETVAL_COMPLETE);
6533	}
6534
6535	if (page_index->page_code & SMPH_SPF) {
6536		page_len_offset = 2;
6537		page_len_size = 2;
6538	} else {
6539		page_len_size = 1;
6540		page_len_offset = 1;
6541	}
6542
6543	/*
6544	 * If the length the initiator gives us isn't the one we specify in
6545	 * the mode page header, or if they didn't specify enough data in
6546	 * the CDB to avoid truncating this page, kick out the request.
6547	 */
6548	if ((page_len != (page_index->page_len - page_len_offset -
6549			  page_len_size))
6550	 || (*len_left < page_index->page_len)) {
6551
6552
6553		ctl_set_invalid_field(ctsio,
6554				      /*sks_valid*/ 1,
6555				      /*command*/ 0,
6556				      /*field*/ *len_used + page_len_offset,
6557				      /*bit_valid*/ 0,
6558				      /*bit*/ 0);
6559		free(ctsio->kern_data_ptr, M_CTL);
6560		ctl_done((union ctl_io *)ctsio);
6561		return (CTL_RETVAL_COMPLETE);
6562	}
6563
6564	/*
6565	 * Run through the mode page, checking to make sure that the bits
6566	 * the user changed are actually legal for him to change.
6567	 */
6568	for (i = 0; i < page_index->page_len; i++) {
6569		uint8_t *user_byte, *change_mask, *current_byte;
6570		int bad_bit;
6571		int j;
6572
6573		user_byte = (uint8_t *)page_header + i;
6574		change_mask = page_index->page_data +
6575			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6576		current_byte = page_index->page_data +
6577			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6578
6579		/*
6580		 * Check to see whether the user set any bits in this byte
6581		 * that he is not allowed to set.
6582		 */
6583		if ((*user_byte & ~(*change_mask)) ==
6584		    (*current_byte & ~(*change_mask)))
6585			continue;
6586
6587		/*
6588		 * Go through bit by bit to determine which one is illegal.
6589		 */
6590		bad_bit = 0;
6591		for (j = 7; j >= 0; j--) {
6592			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6593			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6594				bad_bit = i;
6595				break;
6596			}
6597		}
6598		ctl_set_invalid_field(ctsio,
6599				      /*sks_valid*/ 1,
6600				      /*command*/ 0,
6601				      /*field*/ *len_used + i,
6602				      /*bit_valid*/ 1,
6603				      /*bit*/ bad_bit);
6604		free(ctsio->kern_data_ptr, M_CTL);
6605		ctl_done((union ctl_io *)ctsio);
6606		return (CTL_RETVAL_COMPLETE);
6607	}
6608
6609	/*
6610	 * Decrement these before we call the page handler, since we may
6611	 * end up getting called back one way or another before the handler
6612	 * returns to this context.
6613	 */
6614	*len_left -= page_index->page_len;
6615	*len_used += page_index->page_len;
6616
6617	retval = page_index->select_handler(ctsio, page_index,
6618					    (uint8_t *)page_header);
6619
6620	/*
6621	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6622	 * wait until this queued command completes to finish processing
6623	 * the mode page.  If it returns anything other than
6624	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6625	 * already set the sense information, freed the data pointer, and
6626	 * completed the io for us.
6627	 */
6628	if (retval != CTL_RETVAL_COMPLETE)
6629		goto bailout_no_done;
6630
6631	/*
6632	 * If the initiator sent us more than one page, parse the next one.
6633	 */
6634	if (*len_left > 0)
6635		goto do_next_page;
6636
6637	ctl_set_success(ctsio);
6638	free(ctsio->kern_data_ptr, M_CTL);
6639	ctl_done((union ctl_io *)ctsio);
6640
6641bailout_no_done:
6642
6643	return (CTL_RETVAL_COMPLETE);
6644
6645}
6646
6647int
6648ctl_mode_select(struct ctl_scsiio *ctsio)
6649{
6650	int param_len, pf, sp;
6651	int header_size, bd_len;
6652	int len_left, len_used;
6653	struct ctl_page_index *page_index;
6654	struct ctl_lun *lun;
6655	int control_dev, page_len;
6656	union ctl_modepage_info *modepage_info;
6657	int retval;
6658
6659	pf = 0;
6660	sp = 0;
6661	page_len = 0;
6662	len_used = 0;
6663	len_left = 0;
6664	retval = 0;
6665	bd_len = 0;
6666	page_index = NULL;
6667
6668	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6669
6670	if (lun->be_lun->lun_type != T_DIRECT)
6671		control_dev = 1;
6672	else
6673		control_dev = 0;
6674
6675	switch (ctsio->cdb[0]) {
6676	case MODE_SELECT_6: {
6677		struct scsi_mode_select_6 *cdb;
6678
6679		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6680
6681		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6682		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6683
6684		param_len = cdb->length;
6685		header_size = sizeof(struct scsi_mode_header_6);
6686		break;
6687	}
6688	case MODE_SELECT_10: {
6689		struct scsi_mode_select_10 *cdb;
6690
6691		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6692
6693		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6694		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6695
6696		param_len = scsi_2btoul(cdb->length);
6697		header_size = sizeof(struct scsi_mode_header_10);
6698		break;
6699	}
6700	default:
6701		ctl_set_invalid_opcode(ctsio);
6702		ctl_done((union ctl_io *)ctsio);
6703		return (CTL_RETVAL_COMPLETE);
6704		break; /* NOTREACHED */
6705	}
6706
6707	/*
6708	 * From SPC-3:
6709	 * "A parameter list length of zero indicates that the Data-Out Buffer
6710	 * shall be empty. This condition shall not be considered as an error."
6711	 */
6712	if (param_len == 0) {
6713		ctl_set_success(ctsio);
6714		ctl_done((union ctl_io *)ctsio);
6715		return (CTL_RETVAL_COMPLETE);
6716	}
6717
6718	/*
6719	 * Since we'll hit this the first time through, prior to
6720	 * allocation, we don't need to free a data buffer here.
6721	 */
6722	if (param_len < header_size) {
6723		ctl_set_param_len_error(ctsio);
6724		ctl_done((union ctl_io *)ctsio);
6725		return (CTL_RETVAL_COMPLETE);
6726	}
6727
6728	/*
6729	 * Allocate the data buffer and grab the user's data.  In theory,
6730	 * we shouldn't have to sanity check the parameter list length here
6731	 * because the maximum size is 64K.  We should be able to malloc
6732	 * that much without too many problems.
6733	 */
6734	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6735		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6736		ctsio->kern_data_len = param_len;
6737		ctsio->kern_total_len = param_len;
6738		ctsio->kern_data_resid = 0;
6739		ctsio->kern_rel_offset = 0;
6740		ctsio->kern_sg_entries = 0;
6741		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6742		ctsio->be_move_done = ctl_config_move_done;
6743		ctl_datamove((union ctl_io *)ctsio);
6744
6745		return (CTL_RETVAL_COMPLETE);
6746	}
6747
6748	switch (ctsio->cdb[0]) {
6749	case MODE_SELECT_6: {
6750		struct scsi_mode_header_6 *mh6;
6751
6752		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6753		bd_len = mh6->blk_desc_len;
6754		break;
6755	}
6756	case MODE_SELECT_10: {
6757		struct scsi_mode_header_10 *mh10;
6758
6759		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6760		bd_len = scsi_2btoul(mh10->blk_desc_len);
6761		break;
6762	}
6763	default:
6764		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6765		break;
6766	}
6767
6768	if (param_len < (header_size + bd_len)) {
6769		free(ctsio->kern_data_ptr, M_CTL);
6770		ctl_set_param_len_error(ctsio);
6771		ctl_done((union ctl_io *)ctsio);
6772		return (CTL_RETVAL_COMPLETE);
6773	}
6774
6775	/*
6776	 * Set the IO_CONT flag, so that if this I/O gets passed to
6777	 * ctl_config_write_done(), it'll get passed back to
6778	 * ctl_do_mode_select() for further processing, or completion if
6779	 * we're all done.
6780	 */
6781	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6782	ctsio->io_cont = ctl_do_mode_select;
6783
6784	modepage_info = (union ctl_modepage_info *)
6785		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6786
6787	memset(modepage_info, 0, sizeof(*modepage_info));
6788
6789	len_left = param_len - header_size - bd_len;
6790	len_used = header_size + bd_len;
6791
6792	modepage_info->header.len_left = len_left;
6793	modepage_info->header.len_used = len_used;
6794
6795	return (ctl_do_mode_select((union ctl_io *)ctsio));
6796}
6797
6798int
6799ctl_mode_sense(struct ctl_scsiio *ctsio)
6800{
6801	struct ctl_lun *lun;
6802	int pc, page_code, dbd, llba, subpage;
6803	int alloc_len, page_len, header_len, total_len;
6804	struct scsi_mode_block_descr *block_desc;
6805	struct ctl_page_index *page_index;
6806	int control_dev;
6807
6808	dbd = 0;
6809	llba = 0;
6810	block_desc = NULL;
6811	page_index = NULL;
6812
6813	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6814
6815	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6816
6817	if (lun->be_lun->lun_type != T_DIRECT)
6818		control_dev = 1;
6819	else
6820		control_dev = 0;
6821
6822	if (lun->flags & CTL_LUN_PR_RESERVED) {
6823		uint32_t residx;
6824
6825		/*
6826		 * XXX KDM need a lock here.
6827		 */
6828		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6829		if ((lun->res_type == SPR_TYPE_EX_AC
6830		  && residx != lun->pr_res_idx)
6831		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6832		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6833		  && !lun->per_res[residx].registered)) {
6834			ctl_set_reservation_conflict(ctsio);
6835			ctl_done((union ctl_io *)ctsio);
6836			return (CTL_RETVAL_COMPLETE);
6837		}
6838	}
6839
6840	switch (ctsio->cdb[0]) {
6841	case MODE_SENSE_6: {
6842		struct scsi_mode_sense_6 *cdb;
6843
6844		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6845
6846		header_len = sizeof(struct scsi_mode_hdr_6);
6847		if (cdb->byte2 & SMS_DBD)
6848			dbd = 1;
6849		else
6850			header_len += sizeof(struct scsi_mode_block_descr);
6851
6852		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6853		page_code = cdb->page & SMS_PAGE_CODE;
6854		subpage = cdb->subpage;
6855		alloc_len = cdb->length;
6856		break;
6857	}
6858	case MODE_SENSE_10: {
6859		struct scsi_mode_sense_10 *cdb;
6860
6861		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6862
6863		header_len = sizeof(struct scsi_mode_hdr_10);
6864
6865		if (cdb->byte2 & SMS_DBD)
6866			dbd = 1;
6867		else
6868			header_len += sizeof(struct scsi_mode_block_descr);
6869		if (cdb->byte2 & SMS10_LLBAA)
6870			llba = 1;
6871		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6872		page_code = cdb->page & SMS_PAGE_CODE;
6873		subpage = cdb->subpage;
6874		alloc_len = scsi_2btoul(cdb->length);
6875		break;
6876	}
6877	default:
6878		ctl_set_invalid_opcode(ctsio);
6879		ctl_done((union ctl_io *)ctsio);
6880		return (CTL_RETVAL_COMPLETE);
6881		break; /* NOTREACHED */
6882	}
6883
6884	/*
6885	 * We have to make a first pass through to calculate the size of
6886	 * the pages that match the user's query.  Then we allocate enough
6887	 * memory to hold it, and actually copy the data into the buffer.
6888	 */
6889	switch (page_code) {
6890	case SMS_ALL_PAGES_PAGE: {
6891		int i;
6892
6893		page_len = 0;
6894
6895		/*
6896		 * At the moment, values other than 0 and 0xff here are
6897		 * reserved according to SPC-3.
6898		 */
6899		if ((subpage != SMS_SUBPAGE_PAGE_0)
6900		 && (subpage != SMS_SUBPAGE_ALL)) {
6901			ctl_set_invalid_field(ctsio,
6902					      /*sks_valid*/ 1,
6903					      /*command*/ 1,
6904					      /*field*/ 3,
6905					      /*bit_valid*/ 0,
6906					      /*bit*/ 0);
6907			ctl_done((union ctl_io *)ctsio);
6908			return (CTL_RETVAL_COMPLETE);
6909		}
6910
6911		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6912			if ((control_dev != 0)
6913			 && (lun->mode_pages.index[i].page_flags &
6914			     CTL_PAGE_FLAG_DISK_ONLY))
6915				continue;
6916
6917			/*
6918			 * We don't use this subpage if the user didn't
6919			 * request all subpages.
6920			 */
6921			if ((lun->mode_pages.index[i].subpage != 0)
6922			 && (subpage == SMS_SUBPAGE_PAGE_0))
6923				continue;
6924
6925#if 0
6926			printf("found page %#x len %d\n",
6927			       lun->mode_pages.index[i].page_code &
6928			       SMPH_PC_MASK,
6929			       lun->mode_pages.index[i].page_len);
6930#endif
6931			page_len += lun->mode_pages.index[i].page_len;
6932		}
6933		break;
6934	}
6935	default: {
6936		int i;
6937
6938		page_len = 0;
6939
6940		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6941			/* Look for the right page code */
6942			if ((lun->mode_pages.index[i].page_code &
6943			     SMPH_PC_MASK) != page_code)
6944				continue;
6945
6946			/* Look for the right subpage or the subpage wildcard*/
6947			if ((lun->mode_pages.index[i].subpage != subpage)
6948			 && (subpage != SMS_SUBPAGE_ALL))
6949				continue;
6950
6951			/* Make sure the page is supported for this dev type */
6952			if ((control_dev != 0)
6953			 && (lun->mode_pages.index[i].page_flags &
6954			     CTL_PAGE_FLAG_DISK_ONLY))
6955				continue;
6956
6957#if 0
6958			printf("found page %#x len %d\n",
6959			       lun->mode_pages.index[i].page_code &
6960			       SMPH_PC_MASK,
6961			       lun->mode_pages.index[i].page_len);
6962#endif
6963
6964			page_len += lun->mode_pages.index[i].page_len;
6965		}
6966
6967		if (page_len == 0) {
6968			ctl_set_invalid_field(ctsio,
6969					      /*sks_valid*/ 1,
6970					      /*command*/ 1,
6971					      /*field*/ 2,
6972					      /*bit_valid*/ 1,
6973					      /*bit*/ 5);
6974			ctl_done((union ctl_io *)ctsio);
6975			return (CTL_RETVAL_COMPLETE);
6976		}
6977		break;
6978	}
6979	}
6980
6981	total_len = header_len + page_len;
6982#if 0
6983	printf("header_len = %d, page_len = %d, total_len = %d\n",
6984	       header_len, page_len, total_len);
6985#endif
6986
6987	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6988	ctsio->kern_sg_entries = 0;
6989	ctsio->kern_data_resid = 0;
6990	ctsio->kern_rel_offset = 0;
6991	if (total_len < alloc_len) {
6992		ctsio->residual = alloc_len - total_len;
6993		ctsio->kern_data_len = total_len;
6994		ctsio->kern_total_len = total_len;
6995	} else {
6996		ctsio->residual = 0;
6997		ctsio->kern_data_len = alloc_len;
6998		ctsio->kern_total_len = alloc_len;
6999	}
7000
7001	switch (ctsio->cdb[0]) {
7002	case MODE_SENSE_6: {
7003		struct scsi_mode_hdr_6 *header;
7004
7005		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7006
7007		header->datalen = ctl_min(total_len - 1, 254);
7008
7009		if (dbd)
7010			header->block_descr_len = 0;
7011		else
7012			header->block_descr_len =
7013				sizeof(struct scsi_mode_block_descr);
7014		block_desc = (struct scsi_mode_block_descr *)&header[1];
7015		break;
7016	}
7017	case MODE_SENSE_10: {
7018		struct scsi_mode_hdr_10 *header;
7019		int datalen;
7020
7021		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7022
7023		datalen = ctl_min(total_len - 2, 65533);
7024		scsi_ulto2b(datalen, header->datalen);
7025		if (dbd)
7026			scsi_ulto2b(0, header->block_descr_len);
7027		else
7028			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7029				    header->block_descr_len);
7030		block_desc = (struct scsi_mode_block_descr *)&header[1];
7031		break;
7032	}
7033	default:
7034		panic("invalid CDB type %#x", ctsio->cdb[0]);
7035		break; /* NOTREACHED */
7036	}
7037
7038	/*
7039	 * If we've got a disk, use its blocksize in the block
7040	 * descriptor.  Otherwise, just set it to 0.
7041	 */
7042	if (dbd == 0) {
7043		if (control_dev != 0)
7044			scsi_ulto3b(lun->be_lun->blocksize,
7045				    block_desc->block_len);
7046		else
7047			scsi_ulto3b(0, block_desc->block_len);
7048	}
7049
7050	switch (page_code) {
7051	case SMS_ALL_PAGES_PAGE: {
7052		int i, data_used;
7053
7054		data_used = header_len;
7055		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7056			struct ctl_page_index *page_index;
7057
7058			page_index = &lun->mode_pages.index[i];
7059
7060			if ((control_dev != 0)
7061			 && (page_index->page_flags &
7062			    CTL_PAGE_FLAG_DISK_ONLY))
7063				continue;
7064
7065			/*
7066			 * We don't use this subpage if the user didn't
7067			 * request all subpages.  We already checked (above)
7068			 * to make sure the user only specified a subpage
7069			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7070			 */
7071			if ((page_index->subpage != 0)
7072			 && (subpage == SMS_SUBPAGE_PAGE_0))
7073				continue;
7074
7075			/*
7076			 * Call the handler, if it exists, to update the
7077			 * page to the latest values.
7078			 */
7079			if (page_index->sense_handler != NULL)
7080				page_index->sense_handler(ctsio, page_index,pc);
7081
7082			memcpy(ctsio->kern_data_ptr + data_used,
7083			       page_index->page_data +
7084			       (page_index->page_len * pc),
7085			       page_index->page_len);
7086			data_used += page_index->page_len;
7087		}
7088		break;
7089	}
7090	default: {
7091		int i, data_used;
7092
7093		data_used = header_len;
7094
7095		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7096			struct ctl_page_index *page_index;
7097
7098			page_index = &lun->mode_pages.index[i];
7099
7100			/* Look for the right page code */
7101			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7102				continue;
7103
7104			/* Look for the right subpage or the subpage wildcard*/
7105			if ((page_index->subpage != subpage)
7106			 && (subpage != SMS_SUBPAGE_ALL))
7107				continue;
7108
7109			/* Make sure the page is supported for this dev type */
7110			if ((control_dev != 0)
7111			 && (page_index->page_flags &
7112			     CTL_PAGE_FLAG_DISK_ONLY))
7113				continue;
7114
7115			/*
7116			 * Call the handler, if it exists, to update the
7117			 * page to the latest values.
7118			 */
7119			if (page_index->sense_handler != NULL)
7120				page_index->sense_handler(ctsio, page_index,pc);
7121
7122			memcpy(ctsio->kern_data_ptr + data_used,
7123			       page_index->page_data +
7124			       (page_index->page_len * pc),
7125			       page_index->page_len);
7126			data_used += page_index->page_len;
7127		}
7128		break;
7129	}
7130	}
7131
7132	ctsio->scsi_status = SCSI_STATUS_OK;
7133
7134	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7135	ctsio->be_move_done = ctl_config_move_done;
7136	ctl_datamove((union ctl_io *)ctsio);
7137
7138	return (CTL_RETVAL_COMPLETE);
7139}
7140
7141int
7142ctl_read_capacity(struct ctl_scsiio *ctsio)
7143{
7144	struct scsi_read_capacity *cdb;
7145	struct scsi_read_capacity_data *data;
7146	struct ctl_lun *lun;
7147	uint32_t lba;
7148
7149	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7150
7151	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7152
7153	lba = scsi_4btoul(cdb->addr);
7154	if (((cdb->pmi & SRC_PMI) == 0)
7155	 && (lba != 0)) {
7156		ctl_set_invalid_field(/*ctsio*/ ctsio,
7157				      /*sks_valid*/ 1,
7158				      /*command*/ 1,
7159				      /*field*/ 2,
7160				      /*bit_valid*/ 0,
7161				      /*bit*/ 0);
7162		ctl_done((union ctl_io *)ctsio);
7163		return (CTL_RETVAL_COMPLETE);
7164	}
7165
7166	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7167
7168	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7169	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7170	ctsio->residual = 0;
7171	ctsio->kern_data_len = sizeof(*data);
7172	ctsio->kern_total_len = sizeof(*data);
7173	ctsio->kern_data_resid = 0;
7174	ctsio->kern_rel_offset = 0;
7175	ctsio->kern_sg_entries = 0;
7176
7177	/*
7178	 * If the maximum LBA is greater than 0xfffffffe, the user must
7179	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7180	 * serivce action set.
7181	 */
7182	if (lun->be_lun->maxlba > 0xfffffffe)
7183		scsi_ulto4b(0xffffffff, data->addr);
7184	else
7185		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7186
7187	/*
7188	 * XXX KDM this may not be 512 bytes...
7189	 */
7190	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7191
7192	ctsio->scsi_status = SCSI_STATUS_OK;
7193
7194	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7195	ctsio->be_move_done = ctl_config_move_done;
7196	ctl_datamove((union ctl_io *)ctsio);
7197
7198	return (CTL_RETVAL_COMPLETE);
7199}
7200
7201int
7202ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7203{
7204	struct scsi_read_capacity_16 *cdb;
7205	struct scsi_read_capacity_data_long *data;
7206	struct ctl_lun *lun;
7207	uint64_t lba;
7208	uint32_t alloc_len;
7209
7210	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7211
7212	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7213
7214	alloc_len = scsi_4btoul(cdb->alloc_len);
7215	lba = scsi_8btou64(cdb->addr);
7216
7217	if ((cdb->reladr & SRC16_PMI)
7218	 && (lba != 0)) {
7219		ctl_set_invalid_field(/*ctsio*/ ctsio,
7220				      /*sks_valid*/ 1,
7221				      /*command*/ 1,
7222				      /*field*/ 2,
7223				      /*bit_valid*/ 0,
7224				      /*bit*/ 0);
7225		ctl_done((union ctl_io *)ctsio);
7226		return (CTL_RETVAL_COMPLETE);
7227	}
7228
7229	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7230
7231	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7232	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7233
7234	if (sizeof(*data) < alloc_len) {
7235		ctsio->residual = alloc_len - sizeof(*data);
7236		ctsio->kern_data_len = sizeof(*data);
7237		ctsio->kern_total_len = sizeof(*data);
7238	} else {
7239		ctsio->residual = 0;
7240		ctsio->kern_data_len = alloc_len;
7241		ctsio->kern_total_len = alloc_len;
7242	}
7243	ctsio->kern_data_resid = 0;
7244	ctsio->kern_rel_offset = 0;
7245	ctsio->kern_sg_entries = 0;
7246
7247	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7248	/* XXX KDM this may not be 512 bytes... */
7249	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7250	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7251	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7252	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7253		data->lalba_lbp[0] |= SRC16_LBPME;
7254
7255	ctsio->scsi_status = SCSI_STATUS_OK;
7256
7257	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7258	ctsio->be_move_done = ctl_config_move_done;
7259	ctl_datamove((union ctl_io *)ctsio);
7260
7261	return (CTL_RETVAL_COMPLETE);
7262}
7263
7264int
7265ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7266{
7267	struct scsi_maintenance_in *cdb;
7268	int retval;
7269	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7270	int num_target_port_groups, num_target_ports, single;
7271	struct ctl_lun *lun;
7272	struct ctl_softc *softc;
7273	struct ctl_port *port;
7274	struct scsi_target_group_data *rtg_ptr;
7275	struct scsi_target_group_data_extended *rtg_ext_ptr;
7276	struct scsi_target_port_group_descriptor *tpg_desc;
7277
7278	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7279
7280	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7281	softc = control_softc;
7282	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7283
7284	retval = CTL_RETVAL_COMPLETE;
7285
7286	switch (cdb->byte2 & STG_PDF_MASK) {
7287	case STG_PDF_LENGTH:
7288		ext = 0;
7289		break;
7290	case STG_PDF_EXTENDED:
7291		ext = 1;
7292		break;
7293	default:
7294		ctl_set_invalid_field(/*ctsio*/ ctsio,
7295				      /*sks_valid*/ 1,
7296				      /*command*/ 1,
7297				      /*field*/ 2,
7298				      /*bit_valid*/ 1,
7299				      /*bit*/ 5);
7300		ctl_done((union ctl_io *)ctsio);
7301		return(retval);
7302	}
7303
7304	single = ctl_is_single;
7305	if (single)
7306		num_target_port_groups = 1;
7307	else
7308		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7309	num_target_ports = 0;
7310	mtx_lock(&softc->ctl_lock);
7311	STAILQ_FOREACH(port, &softc->port_list, links) {
7312		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7313			continue;
7314		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7315			continue;
7316		num_target_ports++;
7317	}
7318	mtx_unlock(&softc->ctl_lock);
7319
7320	if (ext)
7321		total_len = sizeof(struct scsi_target_group_data_extended);
7322	else
7323		total_len = sizeof(struct scsi_target_group_data);
7324	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7325		num_target_port_groups +
7326	    sizeof(struct scsi_target_port_descriptor) *
7327		num_target_ports * num_target_port_groups;
7328
7329	alloc_len = scsi_4btoul(cdb->length);
7330
7331	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7332
7333	ctsio->kern_sg_entries = 0;
7334
7335	if (total_len < alloc_len) {
7336		ctsio->residual = alloc_len - total_len;
7337		ctsio->kern_data_len = total_len;
7338		ctsio->kern_total_len = total_len;
7339	} else {
7340		ctsio->residual = 0;
7341		ctsio->kern_data_len = alloc_len;
7342		ctsio->kern_total_len = alloc_len;
7343	}
7344	ctsio->kern_data_resid = 0;
7345	ctsio->kern_rel_offset = 0;
7346
7347	if (ext) {
7348		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7349		    ctsio->kern_data_ptr;
7350		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7351		rtg_ext_ptr->format_type = 0x10;
7352		rtg_ext_ptr->implicit_transition_time = 0;
7353		tpg_desc = &rtg_ext_ptr->groups[0];
7354	} else {
7355		rtg_ptr = (struct scsi_target_group_data *)
7356		    ctsio->kern_data_ptr;
7357		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7358		tpg_desc = &rtg_ptr->groups[0];
7359	}
7360
7361	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7362	mtx_lock(&softc->ctl_lock);
7363	for (g = 0; g < num_target_port_groups; g++) {
7364		if (g == pg)
7365			tpg_desc->pref_state = TPG_PRIMARY |
7366			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7367		else
7368			tpg_desc->pref_state =
7369			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7370		tpg_desc->support = TPG_AO_SUP;
7371		if (!single)
7372			tpg_desc->support |= TPG_AN_SUP;
7373		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7374		tpg_desc->status = TPG_IMPLICIT;
7375		pc = 0;
7376		STAILQ_FOREACH(port, &softc->port_list, links) {
7377			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7378				continue;
7379			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7380			    CTL_MAX_LUNS)
7381				continue;
7382			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7383			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7384			    relative_target_port_identifier);
7385			pc++;
7386		}
7387		tpg_desc->target_port_count = pc;
7388		tpg_desc = (struct scsi_target_port_group_descriptor *)
7389		    &tpg_desc->descriptors[pc];
7390	}
7391	mtx_unlock(&softc->ctl_lock);
7392
7393	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7394	ctsio->be_move_done = ctl_config_move_done;
7395
7396	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7397			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7398			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7399			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7400			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7401
7402	ctl_datamove((union ctl_io *)ctsio);
7403	return(retval);
7404}
7405
7406int
7407ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7408{
7409	struct ctl_lun *lun;
7410	struct scsi_report_supported_opcodes *cdb;
7411	const struct ctl_cmd_entry *entry, *sentry;
7412	struct scsi_report_supported_opcodes_all *all;
7413	struct scsi_report_supported_opcodes_descr *descr;
7414	struct scsi_report_supported_opcodes_one *one;
7415	int retval;
7416	int alloc_len, total_len;
7417	int opcode, service_action, i, j, num;
7418
7419	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7420
7421	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7422	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7423
7424	retval = CTL_RETVAL_COMPLETE;
7425
7426	opcode = cdb->requested_opcode;
7427	service_action = scsi_2btoul(cdb->requested_service_action);
7428	switch (cdb->options & RSO_OPTIONS_MASK) {
7429	case RSO_OPTIONS_ALL:
7430		num = 0;
7431		for (i = 0; i < 256; i++) {
7432			entry = &ctl_cmd_table[i];
7433			if (entry->flags & CTL_CMD_FLAG_SA5) {
7434				for (j = 0; j < 32; j++) {
7435					sentry = &((const struct ctl_cmd_entry *)
7436					    entry->execute)[j];
7437					if (ctl_cmd_applicable(
7438					    lun->be_lun->lun_type, sentry))
7439						num++;
7440				}
7441			} else {
7442				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7443				    entry))
7444					num++;
7445			}
7446		}
7447		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7448		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7449		break;
7450	case RSO_OPTIONS_OC:
7451		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7452			ctl_set_invalid_field(/*ctsio*/ ctsio,
7453					      /*sks_valid*/ 1,
7454					      /*command*/ 1,
7455					      /*field*/ 2,
7456					      /*bit_valid*/ 1,
7457					      /*bit*/ 2);
7458			ctl_done((union ctl_io *)ctsio);
7459			return (CTL_RETVAL_COMPLETE);
7460		}
7461		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7462		break;
7463	case RSO_OPTIONS_OC_SA:
7464		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7465		    service_action >= 32) {
7466			ctl_set_invalid_field(/*ctsio*/ ctsio,
7467					      /*sks_valid*/ 1,
7468					      /*command*/ 1,
7469					      /*field*/ 2,
7470					      /*bit_valid*/ 1,
7471					      /*bit*/ 2);
7472			ctl_done((union ctl_io *)ctsio);
7473			return (CTL_RETVAL_COMPLETE);
7474		}
7475		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7476		break;
7477	default:
7478		ctl_set_invalid_field(/*ctsio*/ ctsio,
7479				      /*sks_valid*/ 1,
7480				      /*command*/ 1,
7481				      /*field*/ 2,
7482				      /*bit_valid*/ 1,
7483				      /*bit*/ 2);
7484		ctl_done((union ctl_io *)ctsio);
7485		return (CTL_RETVAL_COMPLETE);
7486	}
7487
7488	alloc_len = scsi_4btoul(cdb->length);
7489
7490	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7491
7492	ctsio->kern_sg_entries = 0;
7493
7494	if (total_len < alloc_len) {
7495		ctsio->residual = alloc_len - total_len;
7496		ctsio->kern_data_len = total_len;
7497		ctsio->kern_total_len = total_len;
7498	} else {
7499		ctsio->residual = 0;
7500		ctsio->kern_data_len = alloc_len;
7501		ctsio->kern_total_len = alloc_len;
7502	}
7503	ctsio->kern_data_resid = 0;
7504	ctsio->kern_rel_offset = 0;
7505
7506	switch (cdb->options & RSO_OPTIONS_MASK) {
7507	case RSO_OPTIONS_ALL:
7508		all = (struct scsi_report_supported_opcodes_all *)
7509		    ctsio->kern_data_ptr;
7510		num = 0;
7511		for (i = 0; i < 256; i++) {
7512			entry = &ctl_cmd_table[i];
7513			if (entry->flags & CTL_CMD_FLAG_SA5) {
7514				for (j = 0; j < 32; j++) {
7515					sentry = &((const struct ctl_cmd_entry *)
7516					    entry->execute)[j];
7517					if (!ctl_cmd_applicable(
7518					    lun->be_lun->lun_type, sentry))
7519						continue;
7520					descr = &all->descr[num++];
7521					descr->opcode = i;
7522					scsi_ulto2b(j, descr->service_action);
7523					descr->flags = RSO_SERVACTV;
7524					scsi_ulto2b(sentry->length,
7525					    descr->cdb_length);
7526				}
7527			} else {
7528				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7529				    entry))
7530					continue;
7531				descr = &all->descr[num++];
7532				descr->opcode = i;
7533				scsi_ulto2b(0, descr->service_action);
7534				descr->flags = 0;
7535				scsi_ulto2b(entry->length, descr->cdb_length);
7536			}
7537		}
7538		scsi_ulto4b(
7539		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7540		    all->length);
7541		break;
7542	case RSO_OPTIONS_OC:
7543		one = (struct scsi_report_supported_opcodes_one *)
7544		    ctsio->kern_data_ptr;
7545		entry = &ctl_cmd_table[opcode];
7546		goto fill_one;
7547	case RSO_OPTIONS_OC_SA:
7548		one = (struct scsi_report_supported_opcodes_one *)
7549		    ctsio->kern_data_ptr;
7550		entry = &ctl_cmd_table[opcode];
7551		entry = &((const struct ctl_cmd_entry *)
7552		    entry->execute)[service_action];
7553fill_one:
7554		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7555			one->support = 3;
7556			scsi_ulto2b(entry->length, one->cdb_length);
7557			one->cdb_usage[0] = opcode;
7558			memcpy(&one->cdb_usage[1], entry->usage,
7559			    entry->length - 1);
7560		} else
7561			one->support = 1;
7562		break;
7563	}
7564
7565	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7566	ctsio->be_move_done = ctl_config_move_done;
7567
7568	ctl_datamove((union ctl_io *)ctsio);
7569	return(retval);
7570}
7571
7572int
7573ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7574{
7575	struct ctl_lun *lun;
7576	struct scsi_report_supported_tmf *cdb;
7577	struct scsi_report_supported_tmf_data *data;
7578	int retval;
7579	int alloc_len, total_len;
7580
7581	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7582
7583	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7584	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7585
7586	retval = CTL_RETVAL_COMPLETE;
7587
7588	total_len = sizeof(struct scsi_report_supported_tmf_data);
7589	alloc_len = scsi_4btoul(cdb->length);
7590
7591	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7592
7593	ctsio->kern_sg_entries = 0;
7594
7595	if (total_len < alloc_len) {
7596		ctsio->residual = alloc_len - total_len;
7597		ctsio->kern_data_len = total_len;
7598		ctsio->kern_total_len = total_len;
7599	} else {
7600		ctsio->residual = 0;
7601		ctsio->kern_data_len = alloc_len;
7602		ctsio->kern_total_len = alloc_len;
7603	}
7604	ctsio->kern_data_resid = 0;
7605	ctsio->kern_rel_offset = 0;
7606
7607	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7608	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7609	data->byte2 |= RST_ITNRS;
7610
7611	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7612	ctsio->be_move_done = ctl_config_move_done;
7613
7614	ctl_datamove((union ctl_io *)ctsio);
7615	return (retval);
7616}
7617
7618int
7619ctl_report_timestamp(struct ctl_scsiio *ctsio)
7620{
7621	struct ctl_lun *lun;
7622	struct scsi_report_timestamp *cdb;
7623	struct scsi_report_timestamp_data *data;
7624	struct timeval tv;
7625	int64_t timestamp;
7626	int retval;
7627	int alloc_len, total_len;
7628
7629	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7630
7631	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7632	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7633
7634	retval = CTL_RETVAL_COMPLETE;
7635
7636	total_len = sizeof(struct scsi_report_timestamp_data);
7637	alloc_len = scsi_4btoul(cdb->length);
7638
7639	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7640
7641	ctsio->kern_sg_entries = 0;
7642
7643	if (total_len < alloc_len) {
7644		ctsio->residual = alloc_len - total_len;
7645		ctsio->kern_data_len = total_len;
7646		ctsio->kern_total_len = total_len;
7647	} else {
7648		ctsio->residual = 0;
7649		ctsio->kern_data_len = alloc_len;
7650		ctsio->kern_total_len = alloc_len;
7651	}
7652	ctsio->kern_data_resid = 0;
7653	ctsio->kern_rel_offset = 0;
7654
7655	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7656	scsi_ulto2b(sizeof(*data) - 2, data->length);
7657	data->origin = RTS_ORIG_OUTSIDE;
7658	getmicrotime(&tv);
7659	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7660	scsi_ulto4b(timestamp >> 16, data->timestamp);
7661	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7662
7663	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7664	ctsio->be_move_done = ctl_config_move_done;
7665
7666	ctl_datamove((union ctl_io *)ctsio);
7667	return (retval);
7668}
7669
7670int
7671ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7672{
7673	struct scsi_per_res_in *cdb;
7674	int alloc_len, total_len = 0;
7675	/* struct scsi_per_res_in_rsrv in_data; */
7676	struct ctl_lun *lun;
7677	struct ctl_softc *softc;
7678
7679	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7680
7681	softc = control_softc;
7682
7683	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7684
7685	alloc_len = scsi_2btoul(cdb->length);
7686
7687	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7688
7689retry:
7690	mtx_lock(&lun->lun_lock);
7691	switch (cdb->action) {
7692	case SPRI_RK: /* read keys */
7693		total_len = sizeof(struct scsi_per_res_in_keys) +
7694			lun->pr_key_count *
7695			sizeof(struct scsi_per_res_key);
7696		break;
7697	case SPRI_RR: /* read reservation */
7698		if (lun->flags & CTL_LUN_PR_RESERVED)
7699			total_len = sizeof(struct scsi_per_res_in_rsrv);
7700		else
7701			total_len = sizeof(struct scsi_per_res_in_header);
7702		break;
7703	case SPRI_RC: /* report capabilities */
7704		total_len = sizeof(struct scsi_per_res_cap);
7705		break;
7706	case SPRI_RS: /* read full status */
7707		total_len = sizeof(struct scsi_per_res_in_header) +
7708		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7709		    lun->pr_key_count;
7710		break;
7711	default:
7712		panic("Invalid PR type %x", cdb->action);
7713	}
7714	mtx_unlock(&lun->lun_lock);
7715
7716	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7717
7718	if (total_len < alloc_len) {
7719		ctsio->residual = alloc_len - total_len;
7720		ctsio->kern_data_len = total_len;
7721		ctsio->kern_total_len = total_len;
7722	} else {
7723		ctsio->residual = 0;
7724		ctsio->kern_data_len = alloc_len;
7725		ctsio->kern_total_len = alloc_len;
7726	}
7727
7728	ctsio->kern_data_resid = 0;
7729	ctsio->kern_rel_offset = 0;
7730	ctsio->kern_sg_entries = 0;
7731
7732	mtx_lock(&lun->lun_lock);
7733	switch (cdb->action) {
7734	case SPRI_RK: { // read keys
7735        struct scsi_per_res_in_keys *res_keys;
7736		int i, key_count;
7737
7738		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7739
7740		/*
7741		 * We had to drop the lock to allocate our buffer, which
7742		 * leaves time for someone to come in with another
7743		 * persistent reservation.  (That is unlikely, though,
7744		 * since this should be the only persistent reservation
7745		 * command active right now.)
7746		 */
7747		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7748		    (lun->pr_key_count *
7749		     sizeof(struct scsi_per_res_key)))){
7750			mtx_unlock(&lun->lun_lock);
7751			free(ctsio->kern_data_ptr, M_CTL);
7752			printf("%s: reservation length changed, retrying\n",
7753			       __func__);
7754			goto retry;
7755		}
7756
7757		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7758
7759		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7760			     lun->pr_key_count, res_keys->header.length);
7761
7762		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7763			if (!lun->per_res[i].registered)
7764				continue;
7765
7766			/*
7767			 * We used lun->pr_key_count to calculate the
7768			 * size to allocate.  If it turns out the number of
7769			 * initiators with the registered flag set is
7770			 * larger than that (i.e. they haven't been kept in
7771			 * sync), we've got a problem.
7772			 */
7773			if (key_count >= lun->pr_key_count) {
7774#ifdef NEEDTOPORT
7775				csevent_log(CSC_CTL | CSC_SHELF_SW |
7776					    CTL_PR_ERROR,
7777					    csevent_LogType_Fault,
7778					    csevent_AlertLevel_Yellow,
7779					    csevent_FRU_ShelfController,
7780					    csevent_FRU_Firmware,
7781				        csevent_FRU_Unknown,
7782					    "registered keys %d >= key "
7783					    "count %d", key_count,
7784					    lun->pr_key_count);
7785#endif
7786				key_count++;
7787				continue;
7788			}
7789			memcpy(res_keys->keys[key_count].key,
7790			       lun->per_res[i].res_key.key,
7791			       ctl_min(sizeof(res_keys->keys[key_count].key),
7792			       sizeof(lun->per_res[i].res_key)));
7793			key_count++;
7794		}
7795		break;
7796	}
7797	case SPRI_RR: { // read reservation
7798		struct scsi_per_res_in_rsrv *res;
7799		int tmp_len, header_only;
7800
7801		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7802
7803		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7804
7805		if (lun->flags & CTL_LUN_PR_RESERVED)
7806		{
7807			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7808			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7809				    res->header.length);
7810			header_only = 0;
7811		} else {
7812			tmp_len = sizeof(struct scsi_per_res_in_header);
7813			scsi_ulto4b(0, res->header.length);
7814			header_only = 1;
7815		}
7816
7817		/*
7818		 * We had to drop the lock to allocate our buffer, which
7819		 * leaves time for someone to come in with another
7820		 * persistent reservation.  (That is unlikely, though,
7821		 * since this should be the only persistent reservation
7822		 * command active right now.)
7823		 */
7824		if (tmp_len != total_len) {
7825			mtx_unlock(&lun->lun_lock);
7826			free(ctsio->kern_data_ptr, M_CTL);
7827			printf("%s: reservation status changed, retrying\n",
7828			       __func__);
7829			goto retry;
7830		}
7831
7832		/*
7833		 * No reservation held, so we're done.
7834		 */
7835		if (header_only != 0)
7836			break;
7837
7838		/*
7839		 * If the registration is an All Registrants type, the key
7840		 * is 0, since it doesn't really matter.
7841		 */
7842		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7843			memcpy(res->data.reservation,
7844			       &lun->per_res[lun->pr_res_idx].res_key,
7845			       sizeof(struct scsi_per_res_key));
7846		}
7847		res->data.scopetype = lun->res_type;
7848		break;
7849	}
7850	case SPRI_RC:     //report capabilities
7851	{
7852		struct scsi_per_res_cap *res_cap;
7853		uint16_t type_mask;
7854
7855		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7856		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7857		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7858		type_mask = SPRI_TM_WR_EX_AR |
7859			    SPRI_TM_EX_AC_RO |
7860			    SPRI_TM_WR_EX_RO |
7861			    SPRI_TM_EX_AC |
7862			    SPRI_TM_WR_EX |
7863			    SPRI_TM_EX_AC_AR;
7864		scsi_ulto2b(type_mask, res_cap->type_mask);
7865		break;
7866	}
7867	case SPRI_RS: { // read full status
7868		struct scsi_per_res_in_full *res_status;
7869		struct scsi_per_res_in_full_desc *res_desc;
7870		struct ctl_port *port;
7871		int i, len;
7872
7873		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7874
7875		/*
7876		 * We had to drop the lock to allocate our buffer, which
7877		 * leaves time for someone to come in with another
7878		 * persistent reservation.  (That is unlikely, though,
7879		 * since this should be the only persistent reservation
7880		 * command active right now.)
7881		 */
7882		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7883		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7884		     lun->pr_key_count)){
7885			mtx_unlock(&lun->lun_lock);
7886			free(ctsio->kern_data_ptr, M_CTL);
7887			printf("%s: reservation length changed, retrying\n",
7888			       __func__);
7889			goto retry;
7890		}
7891
7892		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7893
7894		res_desc = &res_status->desc[0];
7895		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7896			if (!lun->per_res[i].registered)
7897				continue;
7898
7899			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7900			    sizeof(res_desc->res_key));
7901			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7902			    (lun->pr_res_idx == i ||
7903			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7904				res_desc->flags = SPRI_FULL_R_HOLDER;
7905				res_desc->scopetype = lun->res_type;
7906			}
7907			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7908			    res_desc->rel_trgt_port_id);
7909			len = 0;
7910			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7911			if (port != NULL)
7912				len = ctl_create_iid(port,
7913				    i % CTL_MAX_INIT_PER_PORT,
7914				    res_desc->transport_id);
7915			scsi_ulto4b(len, res_desc->additional_length);
7916			res_desc = (struct scsi_per_res_in_full_desc *)
7917			    &res_desc->transport_id[len];
7918		}
7919		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7920		    res_status->header.length);
7921		break;
7922	}
7923	default:
7924		/*
7925		 * This is a bug, because we just checked for this above,
7926		 * and should have returned an error.
7927		 */
7928		panic("Invalid PR type %x", cdb->action);
7929		break; /* NOTREACHED */
7930	}
7931	mtx_unlock(&lun->lun_lock);
7932
7933	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7934	ctsio->be_move_done = ctl_config_move_done;
7935
7936	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7937			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7938			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7939			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7940			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7941
7942	ctl_datamove((union ctl_io *)ctsio);
7943
7944	return (CTL_RETVAL_COMPLETE);
7945}
7946
7947/*
7948 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7949 * it should return.
7950 */
7951static int
7952ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7953		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7954		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7955		struct scsi_per_res_out_parms* param)
7956{
7957	union ctl_ha_msg persis_io;
7958	int retval, i;
7959	int isc_retval;
7960
7961	retval = 0;
7962
7963	mtx_lock(&lun->lun_lock);
7964	if (sa_res_key == 0) {
7965		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7966			/* validate scope and type */
7967			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7968			     SPR_LU_SCOPE) {
7969				mtx_unlock(&lun->lun_lock);
7970				ctl_set_invalid_field(/*ctsio*/ ctsio,
7971						      /*sks_valid*/ 1,
7972						      /*command*/ 1,
7973						      /*field*/ 2,
7974						      /*bit_valid*/ 1,
7975						      /*bit*/ 4);
7976				ctl_done((union ctl_io *)ctsio);
7977				return (1);
7978			}
7979
7980		        if (type>8 || type==2 || type==4 || type==0) {
7981				mtx_unlock(&lun->lun_lock);
7982				ctl_set_invalid_field(/*ctsio*/ ctsio,
7983       	           				      /*sks_valid*/ 1,
7984						      /*command*/ 1,
7985						      /*field*/ 2,
7986						      /*bit_valid*/ 1,
7987						      /*bit*/ 0);
7988				ctl_done((union ctl_io *)ctsio);
7989				return (1);
7990		        }
7991
7992			/* temporarily unregister this nexus */
7993			lun->per_res[residx].registered = 0;
7994
7995			/*
7996			 * Unregister everybody else and build UA for
7997			 * them
7998			 */
7999			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8000				if (lun->per_res[i].registered == 0)
8001					continue;
8002
8003				if (!persis_offset
8004				 && i <CTL_MAX_INITIATORS)
8005					lun->pending_ua[i] |=
8006						CTL_UA_REG_PREEMPT;
8007				else if (persis_offset
8008				      && i >= persis_offset)
8009					lun->pending_ua[i-persis_offset] |=
8010						CTL_UA_REG_PREEMPT;
8011				lun->per_res[i].registered = 0;
8012				memset(&lun->per_res[i].res_key, 0,
8013				       sizeof(struct scsi_per_res_key));
8014			}
8015			lun->per_res[residx].registered = 1;
8016			lun->pr_key_count = 1;
8017			lun->res_type = type;
8018			if (lun->res_type != SPR_TYPE_WR_EX_AR
8019			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8020				lun->pr_res_idx = residx;
8021
8022			/* send msg to other side */
8023			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8024			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8025			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8026			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8027			persis_io.pr.pr_info.res_type = type;
8028			memcpy(persis_io.pr.pr_info.sa_res_key,
8029			       param->serv_act_res_key,
8030			       sizeof(param->serv_act_res_key));
8031			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8032			     &persis_io, sizeof(persis_io), 0)) >
8033			     CTL_HA_STATUS_SUCCESS) {
8034				printf("CTL:Persis Out error returned "
8035				       "from ctl_ha_msg_send %d\n",
8036				       isc_retval);
8037			}
8038		} else {
8039			/* not all registrants */
8040			mtx_unlock(&lun->lun_lock);
8041			free(ctsio->kern_data_ptr, M_CTL);
8042			ctl_set_invalid_field(ctsio,
8043					      /*sks_valid*/ 1,
8044					      /*command*/ 0,
8045					      /*field*/ 8,
8046					      /*bit_valid*/ 0,
8047					      /*bit*/ 0);
8048			ctl_done((union ctl_io *)ctsio);
8049			return (1);
8050		}
8051	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8052		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8053		int found = 0;
8054
8055		if (res_key == sa_res_key) {
8056			/* special case */
8057			/*
8058			 * The spec implies this is not good but doesn't
8059			 * say what to do. There are two choices either
8060			 * generate a res conflict or check condition
8061			 * with illegal field in parameter data. Since
8062			 * that is what is done when the sa_res_key is
8063			 * zero I'll take that approach since this has
8064			 * to do with the sa_res_key.
8065			 */
8066			mtx_unlock(&lun->lun_lock);
8067			free(ctsio->kern_data_ptr, M_CTL);
8068			ctl_set_invalid_field(ctsio,
8069					      /*sks_valid*/ 1,
8070					      /*command*/ 0,
8071					      /*field*/ 8,
8072					      /*bit_valid*/ 0,
8073					      /*bit*/ 0);
8074			ctl_done((union ctl_io *)ctsio);
8075			return (1);
8076		}
8077
8078		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8079			if (lun->per_res[i].registered
8080			 && memcmp(param->serv_act_res_key,
8081			    lun->per_res[i].res_key.key,
8082			    sizeof(struct scsi_per_res_key)) != 0)
8083				continue;
8084
8085			found = 1;
8086			lun->per_res[i].registered = 0;
8087			memset(&lun->per_res[i].res_key, 0,
8088			       sizeof(struct scsi_per_res_key));
8089			lun->pr_key_count--;
8090
8091			if (!persis_offset && i < CTL_MAX_INITIATORS)
8092				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8093			else if (persis_offset && i >= persis_offset)
8094				lun->pending_ua[i-persis_offset] |=
8095					CTL_UA_REG_PREEMPT;
8096		}
8097		if (!found) {
8098			mtx_unlock(&lun->lun_lock);
8099			free(ctsio->kern_data_ptr, M_CTL);
8100			ctl_set_reservation_conflict(ctsio);
8101			ctl_done((union ctl_io *)ctsio);
8102			return (CTL_RETVAL_COMPLETE);
8103		}
8104		/* send msg to other side */
8105		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8106		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8107		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8108		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8109		persis_io.pr.pr_info.res_type = type;
8110		memcpy(persis_io.pr.pr_info.sa_res_key,
8111		       param->serv_act_res_key,
8112		       sizeof(param->serv_act_res_key));
8113		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8114		     &persis_io, sizeof(persis_io), 0)) >
8115		     CTL_HA_STATUS_SUCCESS) {
8116			printf("CTL:Persis Out error returned from "
8117			       "ctl_ha_msg_send %d\n", isc_retval);
8118		}
8119	} else {
8120		/* Reserved but not all registrants */
8121		/* sa_res_key is res holder */
8122		if (memcmp(param->serv_act_res_key,
8123                   lun->per_res[lun->pr_res_idx].res_key.key,
8124                   sizeof(struct scsi_per_res_key)) == 0) {
8125			/* validate scope and type */
8126			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8127			     SPR_LU_SCOPE) {
8128				mtx_unlock(&lun->lun_lock);
8129				ctl_set_invalid_field(/*ctsio*/ ctsio,
8130						      /*sks_valid*/ 1,
8131						      /*command*/ 1,
8132						      /*field*/ 2,
8133						      /*bit_valid*/ 1,
8134						      /*bit*/ 4);
8135				ctl_done((union ctl_io *)ctsio);
8136				return (1);
8137			}
8138
8139			if (type>8 || type==2 || type==4 || type==0) {
8140				mtx_unlock(&lun->lun_lock);
8141				ctl_set_invalid_field(/*ctsio*/ ctsio,
8142						      /*sks_valid*/ 1,
8143						      /*command*/ 1,
8144						      /*field*/ 2,
8145						      /*bit_valid*/ 1,
8146						      /*bit*/ 0);
8147				ctl_done((union ctl_io *)ctsio);
8148				return (1);
8149			}
8150
8151			/*
8152			 * Do the following:
8153			 * if sa_res_key != res_key remove all
8154			 * registrants w/sa_res_key and generate UA
8155			 * for these registrants(Registrations
8156			 * Preempted) if it wasn't an exclusive
8157			 * reservation generate UA(Reservations
8158			 * Preempted) for all other registered nexuses
8159			 * if the type has changed. Establish the new
8160			 * reservation and holder. If res_key and
8161			 * sa_res_key are the same do the above
8162			 * except don't unregister the res holder.
8163			 */
8164
8165			/*
8166			 * Temporarily unregister so it won't get
8167			 * removed or UA generated
8168			 */
8169			lun->per_res[residx].registered = 0;
8170			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8171				if (lun->per_res[i].registered == 0)
8172					continue;
8173
8174				if (memcmp(param->serv_act_res_key,
8175				    lun->per_res[i].res_key.key,
8176				    sizeof(struct scsi_per_res_key)) == 0) {
8177					lun->per_res[i].registered = 0;
8178					memset(&lun->per_res[i].res_key,
8179					       0,
8180					       sizeof(struct scsi_per_res_key));
8181					lun->pr_key_count--;
8182
8183					if (!persis_offset
8184					 && i < CTL_MAX_INITIATORS)
8185						lun->pending_ua[i] |=
8186							CTL_UA_REG_PREEMPT;
8187					else if (persis_offset
8188					      && i >= persis_offset)
8189						lun->pending_ua[i-persis_offset] |=
8190						  CTL_UA_REG_PREEMPT;
8191				} else if (type != lun->res_type
8192					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8193					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8194						if (!persis_offset
8195						 && i < CTL_MAX_INITIATORS)
8196							lun->pending_ua[i] |=
8197							CTL_UA_RES_RELEASE;
8198						else if (persis_offset
8199						      && i >= persis_offset)
8200							lun->pending_ua[
8201							i-persis_offset] |=
8202							CTL_UA_RES_RELEASE;
8203				}
8204			}
8205			lun->per_res[residx].registered = 1;
8206			lun->res_type = type;
8207			if (lun->res_type != SPR_TYPE_WR_EX_AR
8208			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8209				lun->pr_res_idx = residx;
8210			else
8211				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8212
8213			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8214			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8215			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8216			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8217			persis_io.pr.pr_info.res_type = type;
8218			memcpy(persis_io.pr.pr_info.sa_res_key,
8219			       param->serv_act_res_key,
8220			       sizeof(param->serv_act_res_key));
8221			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8222			     &persis_io, sizeof(persis_io), 0)) >
8223			     CTL_HA_STATUS_SUCCESS) {
8224				printf("CTL:Persis Out error returned "
8225				       "from ctl_ha_msg_send %d\n",
8226				       isc_retval);
8227			}
8228		} else {
8229			/*
8230			 * sa_res_key is not the res holder just
8231			 * remove registrants
8232			 */
8233			int found=0;
8234
8235			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8236				if (memcmp(param->serv_act_res_key,
8237				    lun->per_res[i].res_key.key,
8238				    sizeof(struct scsi_per_res_key)) != 0)
8239					continue;
8240
8241				found = 1;
8242				lun->per_res[i].registered = 0;
8243				memset(&lun->per_res[i].res_key, 0,
8244				       sizeof(struct scsi_per_res_key));
8245				lun->pr_key_count--;
8246
8247				if (!persis_offset
8248				 && i < CTL_MAX_INITIATORS)
8249					lun->pending_ua[i] |=
8250						CTL_UA_REG_PREEMPT;
8251				else if (persis_offset
8252				      && i >= persis_offset)
8253					lun->pending_ua[i-persis_offset] |=
8254						CTL_UA_REG_PREEMPT;
8255			}
8256
8257			if (!found) {
8258				mtx_unlock(&lun->lun_lock);
8259				free(ctsio->kern_data_ptr, M_CTL);
8260				ctl_set_reservation_conflict(ctsio);
8261				ctl_done((union ctl_io *)ctsio);
8262		        	return (1);
8263			}
8264			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8265			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8266			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8267			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8268			persis_io.pr.pr_info.res_type = type;
8269			memcpy(persis_io.pr.pr_info.sa_res_key,
8270			       param->serv_act_res_key,
8271			       sizeof(param->serv_act_res_key));
8272			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8273			     &persis_io, sizeof(persis_io), 0)) >
8274			     CTL_HA_STATUS_SUCCESS) {
8275				printf("CTL:Persis Out error returned "
8276				       "from ctl_ha_msg_send %d\n",
8277				isc_retval);
8278			}
8279		}
8280	}
8281
8282	lun->PRGeneration++;
8283	mtx_unlock(&lun->lun_lock);
8284
8285	return (retval);
8286}
8287
8288static void
8289ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8290{
8291	int i;
8292
8293	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8294	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8295	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8296		   msg->pr.pr_info.sa_res_key,
8297		   sizeof(struct scsi_per_res_key)) != 0) {
8298		uint64_t sa_res_key;
8299		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8300
8301		if (sa_res_key == 0) {
8302			/* temporarily unregister this nexus */
8303			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8304
8305			/*
8306			 * Unregister everybody else and build UA for
8307			 * them
8308			 */
8309			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8310				if (lun->per_res[i].registered == 0)
8311					continue;
8312
8313				if (!persis_offset
8314				 && i < CTL_MAX_INITIATORS)
8315					lun->pending_ua[i] |=
8316						CTL_UA_REG_PREEMPT;
8317				else if (persis_offset && i >= persis_offset)
8318					lun->pending_ua[i - persis_offset] |=
8319						CTL_UA_REG_PREEMPT;
8320				lun->per_res[i].registered = 0;
8321				memset(&lun->per_res[i].res_key, 0,
8322				       sizeof(struct scsi_per_res_key));
8323			}
8324
8325			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8326			lun->pr_key_count = 1;
8327			lun->res_type = msg->pr.pr_info.res_type;
8328			if (lun->res_type != SPR_TYPE_WR_EX_AR
8329			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8330				lun->pr_res_idx = msg->pr.pr_info.residx;
8331		} else {
8332		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8333				if (memcmp(msg->pr.pr_info.sa_res_key,
8334		                   lun->per_res[i].res_key.key,
8335		                   sizeof(struct scsi_per_res_key)) != 0)
8336					continue;
8337
8338				lun->per_res[i].registered = 0;
8339				memset(&lun->per_res[i].res_key, 0,
8340				       sizeof(struct scsi_per_res_key));
8341				lun->pr_key_count--;
8342
8343				if (!persis_offset
8344				 && i < persis_offset)
8345					lun->pending_ua[i] |=
8346						CTL_UA_REG_PREEMPT;
8347				else if (persis_offset
8348				      && i >= persis_offset)
8349					lun->pending_ua[i - persis_offset] |=
8350						CTL_UA_REG_PREEMPT;
8351			}
8352		}
8353	} else {
8354		/*
8355		 * Temporarily unregister so it won't get removed
8356		 * or UA generated
8357		 */
8358		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8359		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8360			if (lun->per_res[i].registered == 0)
8361				continue;
8362
8363			if (memcmp(msg->pr.pr_info.sa_res_key,
8364	                   lun->per_res[i].res_key.key,
8365	                   sizeof(struct scsi_per_res_key)) == 0) {
8366				lun->per_res[i].registered = 0;
8367				memset(&lun->per_res[i].res_key, 0,
8368				       sizeof(struct scsi_per_res_key));
8369				lun->pr_key_count--;
8370				if (!persis_offset
8371				 && i < CTL_MAX_INITIATORS)
8372					lun->pending_ua[i] |=
8373						CTL_UA_REG_PREEMPT;
8374				else if (persis_offset
8375				      && i >= persis_offset)
8376					lun->pending_ua[i - persis_offset] |=
8377						CTL_UA_REG_PREEMPT;
8378			} else if (msg->pr.pr_info.res_type != lun->res_type
8379				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8380				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8381					if (!persis_offset
8382					 && i < persis_offset)
8383						lun->pending_ua[i] |=
8384							CTL_UA_RES_RELEASE;
8385					else if (persis_offset
8386					      && i >= persis_offset)
8387					lun->pending_ua[i - persis_offset] |=
8388						CTL_UA_RES_RELEASE;
8389			}
8390		}
8391		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8392		lun->res_type = msg->pr.pr_info.res_type;
8393		if (lun->res_type != SPR_TYPE_WR_EX_AR
8394		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8395			lun->pr_res_idx = msg->pr.pr_info.residx;
8396		else
8397			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8398	}
8399	lun->PRGeneration++;
8400
8401}
8402
8403
8404int
8405ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8406{
8407	int retval;
8408	int isc_retval;
8409	u_int32_t param_len;
8410	struct scsi_per_res_out *cdb;
8411	struct ctl_lun *lun;
8412	struct scsi_per_res_out_parms* param;
8413	struct ctl_softc *softc;
8414	uint32_t residx;
8415	uint64_t res_key, sa_res_key;
8416	uint8_t type;
8417	union ctl_ha_msg persis_io;
8418	int    i;
8419
8420	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8421
8422	retval = CTL_RETVAL_COMPLETE;
8423
8424	softc = control_softc;
8425
8426	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8427	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8428
8429	/*
8430	 * We only support whole-LUN scope.  The scope & type are ignored for
8431	 * register, register and ignore existing key and clear.
8432	 * We sometimes ignore scope and type on preempts too!!
8433	 * Verify reservation type here as well.
8434	 */
8435	type = cdb->scope_type & SPR_TYPE_MASK;
8436	if ((cdb->action == SPRO_RESERVE)
8437	 || (cdb->action == SPRO_RELEASE)) {
8438		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8439			ctl_set_invalid_field(/*ctsio*/ ctsio,
8440					      /*sks_valid*/ 1,
8441					      /*command*/ 1,
8442					      /*field*/ 2,
8443					      /*bit_valid*/ 1,
8444					      /*bit*/ 4);
8445			ctl_done((union ctl_io *)ctsio);
8446			return (CTL_RETVAL_COMPLETE);
8447		}
8448
8449		if (type>8 || type==2 || type==4 || type==0) {
8450			ctl_set_invalid_field(/*ctsio*/ ctsio,
8451					      /*sks_valid*/ 1,
8452					      /*command*/ 1,
8453					      /*field*/ 2,
8454					      /*bit_valid*/ 1,
8455					      /*bit*/ 0);
8456			ctl_done((union ctl_io *)ctsio);
8457			return (CTL_RETVAL_COMPLETE);
8458		}
8459	}
8460
8461	param_len = scsi_4btoul(cdb->length);
8462
8463	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8464		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8465		ctsio->kern_data_len = param_len;
8466		ctsio->kern_total_len = param_len;
8467		ctsio->kern_data_resid = 0;
8468		ctsio->kern_rel_offset = 0;
8469		ctsio->kern_sg_entries = 0;
8470		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8471		ctsio->be_move_done = ctl_config_move_done;
8472		ctl_datamove((union ctl_io *)ctsio);
8473
8474		return (CTL_RETVAL_COMPLETE);
8475	}
8476
8477	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8478
8479	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8480	res_key = scsi_8btou64(param->res_key.key);
8481	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8482
8483	/*
8484	 * Validate the reservation key here except for SPRO_REG_IGNO
8485	 * This must be done for all other service actions
8486	 */
8487	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8488		mtx_lock(&lun->lun_lock);
8489		if (lun->per_res[residx].registered) {
8490		    if (memcmp(param->res_key.key,
8491			       lun->per_res[residx].res_key.key,
8492			       ctl_min(sizeof(param->res_key),
8493			       sizeof(lun->per_res[residx].res_key))) != 0) {
8494				/*
8495				 * The current key passed in doesn't match
8496				 * the one the initiator previously
8497				 * registered.
8498				 */
8499				mtx_unlock(&lun->lun_lock);
8500				free(ctsio->kern_data_ptr, M_CTL);
8501				ctl_set_reservation_conflict(ctsio);
8502				ctl_done((union ctl_io *)ctsio);
8503				return (CTL_RETVAL_COMPLETE);
8504			}
8505		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8506			/*
8507			 * We are not registered
8508			 */
8509			mtx_unlock(&lun->lun_lock);
8510			free(ctsio->kern_data_ptr, M_CTL);
8511			ctl_set_reservation_conflict(ctsio);
8512			ctl_done((union ctl_io *)ctsio);
8513			return (CTL_RETVAL_COMPLETE);
8514		} else if (res_key != 0) {
8515			/*
8516			 * We are not registered and trying to register but
8517			 * the register key isn't zero.
8518			 */
8519			mtx_unlock(&lun->lun_lock);
8520			free(ctsio->kern_data_ptr, M_CTL);
8521			ctl_set_reservation_conflict(ctsio);
8522			ctl_done((union ctl_io *)ctsio);
8523			return (CTL_RETVAL_COMPLETE);
8524		}
8525		mtx_unlock(&lun->lun_lock);
8526	}
8527
8528	switch (cdb->action & SPRO_ACTION_MASK) {
8529	case SPRO_REGISTER:
8530	case SPRO_REG_IGNO: {
8531
8532#if 0
8533		printf("Registration received\n");
8534#endif
8535
8536		/*
8537		 * We don't support any of these options, as we report in
8538		 * the read capabilities request (see
8539		 * ctl_persistent_reserve_in(), above).
8540		 */
8541		if ((param->flags & SPR_SPEC_I_PT)
8542		 || (param->flags & SPR_ALL_TG_PT)
8543		 || (param->flags & SPR_APTPL)) {
8544			int bit_ptr;
8545
8546			if (param->flags & SPR_APTPL)
8547				bit_ptr = 0;
8548			else if (param->flags & SPR_ALL_TG_PT)
8549				bit_ptr = 2;
8550			else /* SPR_SPEC_I_PT */
8551				bit_ptr = 3;
8552
8553			free(ctsio->kern_data_ptr, M_CTL);
8554			ctl_set_invalid_field(ctsio,
8555					      /*sks_valid*/ 1,
8556					      /*command*/ 0,
8557					      /*field*/ 20,
8558					      /*bit_valid*/ 1,
8559					      /*bit*/ bit_ptr);
8560			ctl_done((union ctl_io *)ctsio);
8561			return (CTL_RETVAL_COMPLETE);
8562		}
8563
8564		mtx_lock(&lun->lun_lock);
8565
8566		/*
8567		 * The initiator wants to clear the
8568		 * key/unregister.
8569		 */
8570		if (sa_res_key == 0) {
8571			if ((res_key == 0
8572			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8573			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8574			  && !lun->per_res[residx].registered)) {
8575				mtx_unlock(&lun->lun_lock);
8576				goto done;
8577			}
8578
8579			lun->per_res[residx].registered = 0;
8580			memset(&lun->per_res[residx].res_key,
8581			       0, sizeof(lun->per_res[residx].res_key));
8582			lun->pr_key_count--;
8583
8584			if (residx == lun->pr_res_idx) {
8585				lun->flags &= ~CTL_LUN_PR_RESERVED;
8586				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8587
8588				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8589				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8590				 && lun->pr_key_count) {
8591					/*
8592					 * If the reservation is a registrants
8593					 * only type we need to generate a UA
8594					 * for other registered inits.  The
8595					 * sense code should be RESERVATIONS
8596					 * RELEASED
8597					 */
8598
8599					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8600						if (lun->per_res[
8601						    i+persis_offset].registered
8602						    == 0)
8603							continue;
8604						lun->pending_ua[i] |=
8605							CTL_UA_RES_RELEASE;
8606					}
8607				}
8608				lun->res_type = 0;
8609			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8610				if (lun->pr_key_count==0) {
8611					lun->flags &= ~CTL_LUN_PR_RESERVED;
8612					lun->res_type = 0;
8613					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8614				}
8615			}
8616			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8617			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8618			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8619			persis_io.pr.pr_info.residx = residx;
8620			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8621			     &persis_io, sizeof(persis_io), 0 )) >
8622			     CTL_HA_STATUS_SUCCESS) {
8623				printf("CTL:Persis Out error returned from "
8624				       "ctl_ha_msg_send %d\n", isc_retval);
8625			}
8626		} else /* sa_res_key != 0 */ {
8627
8628			/*
8629			 * If we aren't registered currently then increment
8630			 * the key count and set the registered flag.
8631			 */
8632			if (!lun->per_res[residx].registered) {
8633				lun->pr_key_count++;
8634				lun->per_res[residx].registered = 1;
8635			}
8636
8637			memcpy(&lun->per_res[residx].res_key,
8638			       param->serv_act_res_key,
8639			       ctl_min(sizeof(param->serv_act_res_key),
8640			       sizeof(lun->per_res[residx].res_key)));
8641
8642			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8643			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8644			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8645			persis_io.pr.pr_info.residx = residx;
8646			memcpy(persis_io.pr.pr_info.sa_res_key,
8647			       param->serv_act_res_key,
8648			       sizeof(param->serv_act_res_key));
8649			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8650			     &persis_io, sizeof(persis_io), 0)) >
8651			     CTL_HA_STATUS_SUCCESS) {
8652				printf("CTL:Persis Out error returned from "
8653				       "ctl_ha_msg_send %d\n", isc_retval);
8654			}
8655		}
8656		lun->PRGeneration++;
8657		mtx_unlock(&lun->lun_lock);
8658
8659		break;
8660	}
8661	case SPRO_RESERVE:
8662#if 0
8663                printf("Reserve executed type %d\n", type);
8664#endif
8665		mtx_lock(&lun->lun_lock);
8666		if (lun->flags & CTL_LUN_PR_RESERVED) {
8667			/*
8668			 * if this isn't the reservation holder and it's
8669			 * not a "all registrants" type or if the type is
8670			 * different then we have a conflict
8671			 */
8672			if ((lun->pr_res_idx != residx
8673			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8674			 || lun->res_type != type) {
8675				mtx_unlock(&lun->lun_lock);
8676				free(ctsio->kern_data_ptr, M_CTL);
8677				ctl_set_reservation_conflict(ctsio);
8678				ctl_done((union ctl_io *)ctsio);
8679				return (CTL_RETVAL_COMPLETE);
8680			}
8681			mtx_unlock(&lun->lun_lock);
8682		} else /* create a reservation */ {
8683			/*
8684			 * If it's not an "all registrants" type record
8685			 * reservation holder
8686			 */
8687			if (type != SPR_TYPE_WR_EX_AR
8688			 && type != SPR_TYPE_EX_AC_AR)
8689				lun->pr_res_idx = residx; /* Res holder */
8690			else
8691				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8692
8693			lun->flags |= CTL_LUN_PR_RESERVED;
8694			lun->res_type = type;
8695
8696			mtx_unlock(&lun->lun_lock);
8697
8698			/* send msg to other side */
8699			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8700			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8701			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8702			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8703			persis_io.pr.pr_info.res_type = type;
8704			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8705			     &persis_io, sizeof(persis_io), 0)) >
8706			     CTL_HA_STATUS_SUCCESS) {
8707				printf("CTL:Persis Out error returned from "
8708				       "ctl_ha_msg_send %d\n", isc_retval);
8709			}
8710		}
8711		break;
8712
8713	case SPRO_RELEASE:
8714		mtx_lock(&lun->lun_lock);
8715		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8716			/* No reservation exists return good status */
8717			mtx_unlock(&lun->lun_lock);
8718			goto done;
8719		}
8720		/*
8721		 * Is this nexus a reservation holder?
8722		 */
8723		if (lun->pr_res_idx != residx
8724		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8725			/*
8726			 * not a res holder return good status but
8727			 * do nothing
8728			 */
8729			mtx_unlock(&lun->lun_lock);
8730			goto done;
8731		}
8732
8733		if (lun->res_type != type) {
8734			mtx_unlock(&lun->lun_lock);
8735			free(ctsio->kern_data_ptr, M_CTL);
8736			ctl_set_illegal_pr_release(ctsio);
8737			ctl_done((union ctl_io *)ctsio);
8738			return (CTL_RETVAL_COMPLETE);
8739		}
8740
8741		/* okay to release */
8742		lun->flags &= ~CTL_LUN_PR_RESERVED;
8743		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8744		lun->res_type = 0;
8745
8746		/*
8747		 * if this isn't an exclusive access
8748		 * res generate UA for all other
8749		 * registrants.
8750		 */
8751		if (type != SPR_TYPE_EX_AC
8752		 && type != SPR_TYPE_WR_EX) {
8753			/*
8754			 * temporarily unregister so we don't generate UA
8755			 */
8756			lun->per_res[residx].registered = 0;
8757
8758			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8759				if (lun->per_res[i+persis_offset].registered
8760				    == 0)
8761					continue;
8762				lun->pending_ua[i] |=
8763					CTL_UA_RES_RELEASE;
8764			}
8765
8766			lun->per_res[residx].registered = 1;
8767		}
8768		mtx_unlock(&lun->lun_lock);
8769		/* Send msg to other side */
8770		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8771		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8772		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8773		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8774		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8775			printf("CTL:Persis Out error returned from "
8776			       "ctl_ha_msg_send %d\n", isc_retval);
8777		}
8778		break;
8779
8780	case SPRO_CLEAR:
8781		/* send msg to other side */
8782
8783		mtx_lock(&lun->lun_lock);
8784		lun->flags &= ~CTL_LUN_PR_RESERVED;
8785		lun->res_type = 0;
8786		lun->pr_key_count = 0;
8787		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8788
8789
8790		memset(&lun->per_res[residx].res_key,
8791		       0, sizeof(lun->per_res[residx].res_key));
8792		lun->per_res[residx].registered = 0;
8793
8794		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8795			if (lun->per_res[i].registered) {
8796				if (!persis_offset && i < CTL_MAX_INITIATORS)
8797					lun->pending_ua[i] |=
8798						CTL_UA_RES_PREEMPT;
8799				else if (persis_offset && i >= persis_offset)
8800					lun->pending_ua[i-persis_offset] |=
8801					    CTL_UA_RES_PREEMPT;
8802
8803				memset(&lun->per_res[i].res_key,
8804				       0, sizeof(struct scsi_per_res_key));
8805				lun->per_res[i].registered = 0;
8806			}
8807		lun->PRGeneration++;
8808		mtx_unlock(&lun->lun_lock);
8809		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8810		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8811		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8812		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8813		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8814			printf("CTL:Persis Out error returned from "
8815			       "ctl_ha_msg_send %d\n", isc_retval);
8816		}
8817		break;
8818
8819	case SPRO_PREEMPT: {
8820		int nretval;
8821
8822		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8823					  residx, ctsio, cdb, param);
8824		if (nretval != 0)
8825			return (CTL_RETVAL_COMPLETE);
8826		break;
8827	}
8828	default:
8829		panic("Invalid PR type %x", cdb->action);
8830	}
8831
8832done:
8833	free(ctsio->kern_data_ptr, M_CTL);
8834	ctl_set_success(ctsio);
8835	ctl_done((union ctl_io *)ctsio);
8836
8837	return (retval);
8838}
8839
8840/*
8841 * This routine is for handling a message from the other SC pertaining to
8842 * persistent reserve out. All the error checking will have been done
8843 * so only perorming the action need be done here to keep the two
8844 * in sync.
8845 */
8846static void
8847ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8848{
8849	struct ctl_lun *lun;
8850	struct ctl_softc *softc;
8851	int i;
8852	uint32_t targ_lun;
8853
8854	softc = control_softc;
8855
8856	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8857	lun = softc->ctl_luns[targ_lun];
8858	mtx_lock(&lun->lun_lock);
8859	switch(msg->pr.pr_info.action) {
8860	case CTL_PR_REG_KEY:
8861		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8862			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8863			lun->pr_key_count++;
8864		}
8865		lun->PRGeneration++;
8866		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8867		       msg->pr.pr_info.sa_res_key,
8868		       sizeof(struct scsi_per_res_key));
8869		break;
8870
8871	case CTL_PR_UNREG_KEY:
8872		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8873		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8874		       0, sizeof(struct scsi_per_res_key));
8875		lun->pr_key_count--;
8876
8877		/* XXX Need to see if the reservation has been released */
8878		/* if so do we need to generate UA? */
8879		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8880			lun->flags &= ~CTL_LUN_PR_RESERVED;
8881			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8882
8883			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8884			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8885			 && lun->pr_key_count) {
8886				/*
8887				 * If the reservation is a registrants
8888				 * only type we need to generate a UA
8889				 * for other registered inits.  The
8890				 * sense code should be RESERVATIONS
8891				 * RELEASED
8892				 */
8893
8894				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8895					if (lun->per_res[i+
8896					    persis_offset].registered == 0)
8897						continue;
8898
8899					lun->pending_ua[i] |=
8900						CTL_UA_RES_RELEASE;
8901				}
8902			}
8903			lun->res_type = 0;
8904		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8905			if (lun->pr_key_count==0) {
8906				lun->flags &= ~CTL_LUN_PR_RESERVED;
8907				lun->res_type = 0;
8908				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8909			}
8910		}
8911		lun->PRGeneration++;
8912		break;
8913
8914	case CTL_PR_RESERVE:
8915		lun->flags |= CTL_LUN_PR_RESERVED;
8916		lun->res_type = msg->pr.pr_info.res_type;
8917		lun->pr_res_idx = msg->pr.pr_info.residx;
8918
8919		break;
8920
8921	case CTL_PR_RELEASE:
8922		/*
8923		 * if this isn't an exclusive access res generate UA for all
8924		 * other registrants.
8925		 */
8926		if (lun->res_type != SPR_TYPE_EX_AC
8927		 && lun->res_type != SPR_TYPE_WR_EX) {
8928			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8929				if (lun->per_res[i+persis_offset].registered)
8930					lun->pending_ua[i] |=
8931						CTL_UA_RES_RELEASE;
8932		}
8933
8934		lun->flags &= ~CTL_LUN_PR_RESERVED;
8935		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8936		lun->res_type = 0;
8937		break;
8938
8939	case CTL_PR_PREEMPT:
8940		ctl_pro_preempt_other(lun, msg);
8941		break;
8942	case CTL_PR_CLEAR:
8943		lun->flags &= ~CTL_LUN_PR_RESERVED;
8944		lun->res_type = 0;
8945		lun->pr_key_count = 0;
8946		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8947
8948		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8949			if (lun->per_res[i].registered == 0)
8950				continue;
8951			if (!persis_offset
8952			 && i < CTL_MAX_INITIATORS)
8953				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8954			else if (persis_offset
8955			      && i >= persis_offset)
8956				lun->pending_ua[i-persis_offset] |=
8957					CTL_UA_RES_PREEMPT;
8958			memset(&lun->per_res[i].res_key, 0,
8959			       sizeof(struct scsi_per_res_key));
8960			lun->per_res[i].registered = 0;
8961		}
8962		lun->PRGeneration++;
8963		break;
8964	}
8965
8966	mtx_unlock(&lun->lun_lock);
8967}
8968
8969int
8970ctl_read_write(struct ctl_scsiio *ctsio)
8971{
8972	struct ctl_lun *lun;
8973	struct ctl_lba_len_flags *lbalen;
8974	uint64_t lba;
8975	uint32_t num_blocks;
8976	int fua, dpo;
8977	int retval;
8978	int isread;
8979
8980	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8981
8982	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8983
8984	fua = 0;
8985	dpo = 0;
8986
8987	retval = CTL_RETVAL_COMPLETE;
8988
8989	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8990	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8991	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8992		uint32_t residx;
8993
8994		/*
8995		 * XXX KDM need a lock here.
8996		 */
8997		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8998		if ((lun->res_type == SPR_TYPE_EX_AC
8999		  && residx != lun->pr_res_idx)
9000		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9001		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9002		  && !lun->per_res[residx].registered)) {
9003			ctl_set_reservation_conflict(ctsio);
9004			ctl_done((union ctl_io *)ctsio);
9005			return (CTL_RETVAL_COMPLETE);
9006	        }
9007	}
9008
9009	switch (ctsio->cdb[0]) {
9010	case READ_6:
9011	case WRITE_6: {
9012		struct scsi_rw_6 *cdb;
9013
9014		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9015
9016		lba = scsi_3btoul(cdb->addr);
9017		/* only 5 bits are valid in the most significant address byte */
9018		lba &= 0x1fffff;
9019		num_blocks = cdb->length;
9020		/*
9021		 * This is correct according to SBC-2.
9022		 */
9023		if (num_blocks == 0)
9024			num_blocks = 256;
9025		break;
9026	}
9027	case READ_10:
9028	case WRITE_10: {
9029		struct scsi_rw_10 *cdb;
9030
9031		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9032
9033		if (cdb->byte2 & SRW10_FUA)
9034			fua = 1;
9035		if (cdb->byte2 & SRW10_DPO)
9036			dpo = 1;
9037
9038		lba = scsi_4btoul(cdb->addr);
9039		num_blocks = scsi_2btoul(cdb->length);
9040		break;
9041	}
9042	case WRITE_VERIFY_10: {
9043		struct scsi_write_verify_10 *cdb;
9044
9045		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9046
9047		/*
9048		 * XXX KDM we should do actual write verify support at some
9049		 * point.  This is obviously fake, we're just translating
9050		 * things to a write.  So we don't even bother checking the
9051		 * BYTCHK field, since we don't do any verification.  If
9052		 * the user asks for it, we'll just pretend we did it.
9053		 */
9054		if (cdb->byte2 & SWV_DPO)
9055			dpo = 1;
9056
9057		lba = scsi_4btoul(cdb->addr);
9058		num_blocks = scsi_2btoul(cdb->length);
9059		break;
9060	}
9061	case READ_12:
9062	case WRITE_12: {
9063		struct scsi_rw_12 *cdb;
9064
9065		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9066
9067		if (cdb->byte2 & SRW12_FUA)
9068			fua = 1;
9069		if (cdb->byte2 & SRW12_DPO)
9070			dpo = 1;
9071		lba = scsi_4btoul(cdb->addr);
9072		num_blocks = scsi_4btoul(cdb->length);
9073		break;
9074	}
9075	case WRITE_VERIFY_12: {
9076		struct scsi_write_verify_12 *cdb;
9077
9078		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9079
9080		if (cdb->byte2 & SWV_DPO)
9081			dpo = 1;
9082
9083		lba = scsi_4btoul(cdb->addr);
9084		num_blocks = scsi_4btoul(cdb->length);
9085
9086		break;
9087	}
9088	case READ_16:
9089	case WRITE_16: {
9090		struct scsi_rw_16 *cdb;
9091
9092		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9093
9094		if (cdb->byte2 & SRW12_FUA)
9095			fua = 1;
9096		if (cdb->byte2 & SRW12_DPO)
9097			dpo = 1;
9098
9099		lba = scsi_8btou64(cdb->addr);
9100		num_blocks = scsi_4btoul(cdb->length);
9101		break;
9102	}
9103	case WRITE_VERIFY_16: {
9104		struct scsi_write_verify_16 *cdb;
9105
9106		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9107
9108		if (cdb->byte2 & SWV_DPO)
9109			dpo = 1;
9110
9111		lba = scsi_8btou64(cdb->addr);
9112		num_blocks = scsi_4btoul(cdb->length);
9113		break;
9114	}
9115	default:
9116		/*
9117		 * We got a command we don't support.  This shouldn't
9118		 * happen, commands should be filtered out above us.
9119		 */
9120		ctl_set_invalid_opcode(ctsio);
9121		ctl_done((union ctl_io *)ctsio);
9122
9123		return (CTL_RETVAL_COMPLETE);
9124		break; /* NOTREACHED */
9125	}
9126
9127	/*
9128	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9129	 * interesting for us, but if RAIDCore is in write-back mode,
9130	 * getting it to do write-through for a particular transaction may
9131	 * not be possible.
9132	 */
9133
9134	/*
9135	 * The first check is to make sure we're in bounds, the second
9136	 * check is to catch wrap-around problems.  If the lba + num blocks
9137	 * is less than the lba, then we've wrapped around and the block
9138	 * range is invalid anyway.
9139	 */
9140	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9141	 || ((lba + num_blocks) < lba)) {
9142		ctl_set_lba_out_of_range(ctsio);
9143		ctl_done((union ctl_io *)ctsio);
9144		return (CTL_RETVAL_COMPLETE);
9145	}
9146
9147	/*
9148	 * According to SBC-3, a transfer length of 0 is not an error.
9149	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9150	 * translates to 256 blocks for those commands.
9151	 */
9152	if (num_blocks == 0) {
9153		ctl_set_success(ctsio);
9154		ctl_done((union ctl_io *)ctsio);
9155		return (CTL_RETVAL_COMPLETE);
9156	}
9157
9158	lbalen = (struct ctl_lba_len_flags *)
9159	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9160	lbalen->lba = lba;
9161	lbalen->len = num_blocks;
9162	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9163
9164	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9165	ctsio->kern_rel_offset = 0;
9166
9167	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9168
9169	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9170
9171	return (retval);
9172}
9173
9174static int
9175ctl_cnw_cont(union ctl_io *io)
9176{
9177	struct ctl_scsiio *ctsio;
9178	struct ctl_lun *lun;
9179	struct ctl_lba_len_flags *lbalen;
9180	int retval;
9181
9182	ctsio = &io->scsiio;
9183	ctsio->io_hdr.status = CTL_STATUS_NONE;
9184	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9185	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9186	lbalen = (struct ctl_lba_len_flags *)
9187	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9188	lbalen->flags = CTL_LLF_WRITE;
9189
9190	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9191	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9192	return (retval);
9193}
9194
9195int
9196ctl_cnw(struct ctl_scsiio *ctsio)
9197{
9198	struct ctl_lun *lun;
9199	struct ctl_lba_len_flags *lbalen;
9200	uint64_t lba;
9201	uint32_t num_blocks;
9202	int fua, dpo;
9203	int retval;
9204
9205	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9206
9207	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9208
9209	fua = 0;
9210	dpo = 0;
9211
9212	retval = CTL_RETVAL_COMPLETE;
9213
9214	switch (ctsio->cdb[0]) {
9215	case COMPARE_AND_WRITE: {
9216		struct scsi_compare_and_write *cdb;
9217
9218		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9219
9220		if (cdb->byte2 & SRW10_FUA)
9221			fua = 1;
9222		if (cdb->byte2 & SRW10_DPO)
9223			dpo = 1;
9224		lba = scsi_8btou64(cdb->addr);
9225		num_blocks = cdb->length;
9226		break;
9227	}
9228	default:
9229		/*
9230		 * We got a command we don't support.  This shouldn't
9231		 * happen, commands should be filtered out above us.
9232		 */
9233		ctl_set_invalid_opcode(ctsio);
9234		ctl_done((union ctl_io *)ctsio);
9235
9236		return (CTL_RETVAL_COMPLETE);
9237		break; /* NOTREACHED */
9238	}
9239
9240	/*
9241	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9242	 * interesting for us, but if RAIDCore is in write-back mode,
9243	 * getting it to do write-through for a particular transaction may
9244	 * not be possible.
9245	 */
9246
9247	/*
9248	 * The first check is to make sure we're in bounds, the second
9249	 * check is to catch wrap-around problems.  If the lba + num blocks
9250	 * is less than the lba, then we've wrapped around and the block
9251	 * range is invalid anyway.
9252	 */
9253	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9254	 || ((lba + num_blocks) < lba)) {
9255		ctl_set_lba_out_of_range(ctsio);
9256		ctl_done((union ctl_io *)ctsio);
9257		return (CTL_RETVAL_COMPLETE);
9258	}
9259
9260	/*
9261	 * According to SBC-3, a transfer length of 0 is not an error.
9262	 */
9263	if (num_blocks == 0) {
9264		ctl_set_success(ctsio);
9265		ctl_done((union ctl_io *)ctsio);
9266		return (CTL_RETVAL_COMPLETE);
9267	}
9268
9269	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9270	ctsio->kern_rel_offset = 0;
9271
9272	/*
9273	 * Set the IO_CONT flag, so that if this I/O gets passed to
9274	 * ctl_data_submit_done(), it'll get passed back to
9275	 * ctl_ctl_cnw_cont() for further processing.
9276	 */
9277	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9278	ctsio->io_cont = ctl_cnw_cont;
9279
9280	lbalen = (struct ctl_lba_len_flags *)
9281	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9282	lbalen->lba = lba;
9283	lbalen->len = num_blocks;
9284	lbalen->flags = CTL_LLF_COMPARE;
9285
9286	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9287	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9288	return (retval);
9289}
9290
9291int
9292ctl_verify(struct ctl_scsiio *ctsio)
9293{
9294	struct ctl_lun *lun;
9295	struct ctl_lba_len_flags *lbalen;
9296	uint64_t lba;
9297	uint32_t num_blocks;
9298	int bytchk, dpo;
9299	int retval;
9300
9301	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9302
9303	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9304
9305	bytchk = 0;
9306	dpo = 0;
9307	retval = CTL_RETVAL_COMPLETE;
9308
9309	switch (ctsio->cdb[0]) {
9310	case VERIFY_10: {
9311		struct scsi_verify_10 *cdb;
9312
9313		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9314		if (cdb->byte2 & SVFY_BYTCHK)
9315			bytchk = 1;
9316		if (cdb->byte2 & SVFY_DPO)
9317			dpo = 1;
9318		lba = scsi_4btoul(cdb->addr);
9319		num_blocks = scsi_2btoul(cdb->length);
9320		break;
9321	}
9322	case VERIFY_12: {
9323		struct scsi_verify_12 *cdb;
9324
9325		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9326		if (cdb->byte2 & SVFY_BYTCHK)
9327			bytchk = 1;
9328		if (cdb->byte2 & SVFY_DPO)
9329			dpo = 1;
9330		lba = scsi_4btoul(cdb->addr);
9331		num_blocks = scsi_4btoul(cdb->length);
9332		break;
9333	}
9334	case VERIFY_16: {
9335		struct scsi_rw_16 *cdb;
9336
9337		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9338		if (cdb->byte2 & SVFY_BYTCHK)
9339			bytchk = 1;
9340		if (cdb->byte2 & SVFY_DPO)
9341			dpo = 1;
9342		lba = scsi_8btou64(cdb->addr);
9343		num_blocks = scsi_4btoul(cdb->length);
9344		break;
9345	}
9346	default:
9347		/*
9348		 * We got a command we don't support.  This shouldn't
9349		 * happen, commands should be filtered out above us.
9350		 */
9351		ctl_set_invalid_opcode(ctsio);
9352		ctl_done((union ctl_io *)ctsio);
9353		return (CTL_RETVAL_COMPLETE);
9354	}
9355
9356	/*
9357	 * The first check is to make sure we're in bounds, the second
9358	 * check is to catch wrap-around problems.  If the lba + num blocks
9359	 * is less than the lba, then we've wrapped around and the block
9360	 * range is invalid anyway.
9361	 */
9362	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9363	 || ((lba + num_blocks) < lba)) {
9364		ctl_set_lba_out_of_range(ctsio);
9365		ctl_done((union ctl_io *)ctsio);
9366		return (CTL_RETVAL_COMPLETE);
9367	}
9368
9369	/*
9370	 * According to SBC-3, a transfer length of 0 is not an error.
9371	 */
9372	if (num_blocks == 0) {
9373		ctl_set_success(ctsio);
9374		ctl_done((union ctl_io *)ctsio);
9375		return (CTL_RETVAL_COMPLETE);
9376	}
9377
9378	lbalen = (struct ctl_lba_len_flags *)
9379	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9380	lbalen->lba = lba;
9381	lbalen->len = num_blocks;
9382	if (bytchk) {
9383		lbalen->flags = CTL_LLF_COMPARE;
9384		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9385	} else {
9386		lbalen->flags = CTL_LLF_VERIFY;
9387		ctsio->kern_total_len = 0;
9388	}
9389	ctsio->kern_rel_offset = 0;
9390
9391	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9392	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9393	return (retval);
9394}
9395
9396int
9397ctl_report_luns(struct ctl_scsiio *ctsio)
9398{
9399	struct scsi_report_luns *cdb;
9400	struct scsi_report_luns_data *lun_data;
9401	struct ctl_lun *lun, *request_lun;
9402	int num_luns, retval;
9403	uint32_t alloc_len, lun_datalen;
9404	int num_filled, well_known;
9405	uint32_t initidx, targ_lun_id, lun_id;
9406
9407	retval = CTL_RETVAL_COMPLETE;
9408	well_known = 0;
9409
9410	cdb = (struct scsi_report_luns *)ctsio->cdb;
9411
9412	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9413
9414	mtx_lock(&control_softc->ctl_lock);
9415	num_luns = control_softc->num_luns;
9416	mtx_unlock(&control_softc->ctl_lock);
9417
9418	switch (cdb->select_report) {
9419	case RPL_REPORT_DEFAULT:
9420	case RPL_REPORT_ALL:
9421		break;
9422	case RPL_REPORT_WELLKNOWN:
9423		well_known = 1;
9424		num_luns = 0;
9425		break;
9426	default:
9427		ctl_set_invalid_field(ctsio,
9428				      /*sks_valid*/ 1,
9429				      /*command*/ 1,
9430				      /*field*/ 2,
9431				      /*bit_valid*/ 0,
9432				      /*bit*/ 0);
9433		ctl_done((union ctl_io *)ctsio);
9434		return (retval);
9435		break; /* NOTREACHED */
9436	}
9437
9438	alloc_len = scsi_4btoul(cdb->length);
9439	/*
9440	 * The initiator has to allocate at least 16 bytes for this request,
9441	 * so he can at least get the header and the first LUN.  Otherwise
9442	 * we reject the request (per SPC-3 rev 14, section 6.21).
9443	 */
9444	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9445	    sizeof(struct scsi_report_luns_lundata))) {
9446		ctl_set_invalid_field(ctsio,
9447				      /*sks_valid*/ 1,
9448				      /*command*/ 1,
9449				      /*field*/ 6,
9450				      /*bit_valid*/ 0,
9451				      /*bit*/ 0);
9452		ctl_done((union ctl_io *)ctsio);
9453		return (retval);
9454	}
9455
9456	request_lun = (struct ctl_lun *)
9457		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9458
9459	lun_datalen = sizeof(*lun_data) +
9460		(num_luns * sizeof(struct scsi_report_luns_lundata));
9461
9462	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9463	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9464	ctsio->kern_sg_entries = 0;
9465
9466	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9467
9468	mtx_lock(&control_softc->ctl_lock);
9469	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9470		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9471		if (lun_id >= CTL_MAX_LUNS)
9472			continue;
9473		lun = control_softc->ctl_luns[lun_id];
9474		if (lun == NULL)
9475			continue;
9476
9477		if (targ_lun_id <= 0xff) {
9478			/*
9479			 * Peripheral addressing method, bus number 0.
9480			 */
9481			lun_data->luns[num_filled].lundata[0] =
9482				RPL_LUNDATA_ATYP_PERIPH;
9483			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9484			num_filled++;
9485		} else if (targ_lun_id <= 0x3fff) {
9486			/*
9487			 * Flat addressing method.
9488			 */
9489			lun_data->luns[num_filled].lundata[0] =
9490				RPL_LUNDATA_ATYP_FLAT |
9491				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9492#ifdef OLDCTLHEADERS
9493				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9494				(targ_lun_id & SRLD_BUS_LUN_MASK);
9495#endif
9496			lun_data->luns[num_filled].lundata[1] =
9497#ifdef OLDCTLHEADERS
9498				targ_lun_id >> SRLD_BUS_LUN_BITS;
9499#endif
9500				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9501			num_filled++;
9502		} else {
9503			printf("ctl_report_luns: bogus LUN number %jd, "
9504			       "skipping\n", (intmax_t)targ_lun_id);
9505		}
9506		/*
9507		 * According to SPC-3, rev 14 section 6.21:
9508		 *
9509		 * "The execution of a REPORT LUNS command to any valid and
9510		 * installed logical unit shall clear the REPORTED LUNS DATA
9511		 * HAS CHANGED unit attention condition for all logical
9512		 * units of that target with respect to the requesting
9513		 * initiator. A valid and installed logical unit is one
9514		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9515		 * INQUIRY data (see 6.4.2)."
9516		 *
9517		 * If request_lun is NULL, the LUN this report luns command
9518		 * was issued to is either disabled or doesn't exist. In that
9519		 * case, we shouldn't clear any pending lun change unit
9520		 * attention.
9521		 */
9522		if (request_lun != NULL) {
9523			mtx_lock(&lun->lun_lock);
9524			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9525			mtx_unlock(&lun->lun_lock);
9526		}
9527	}
9528	mtx_unlock(&control_softc->ctl_lock);
9529
9530	/*
9531	 * It's quite possible that we've returned fewer LUNs than we allocated
9532	 * space for.  Trim it.
9533	 */
9534	lun_datalen = sizeof(*lun_data) +
9535		(num_filled * sizeof(struct scsi_report_luns_lundata));
9536
9537	if (lun_datalen < alloc_len) {
9538		ctsio->residual = alloc_len - lun_datalen;
9539		ctsio->kern_data_len = lun_datalen;
9540		ctsio->kern_total_len = lun_datalen;
9541	} else {
9542		ctsio->residual = 0;
9543		ctsio->kern_data_len = alloc_len;
9544		ctsio->kern_total_len = alloc_len;
9545	}
9546	ctsio->kern_data_resid = 0;
9547	ctsio->kern_rel_offset = 0;
9548	ctsio->kern_sg_entries = 0;
9549
9550	/*
9551	 * We set this to the actual data length, regardless of how much
9552	 * space we actually have to return results.  If the user looks at
9553	 * this value, he'll know whether or not he allocated enough space
9554	 * and reissue the command if necessary.  We don't support well
9555	 * known logical units, so if the user asks for that, return none.
9556	 */
9557	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9558
9559	/*
9560	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9561	 * this request.
9562	 */
9563	ctsio->scsi_status = SCSI_STATUS_OK;
9564
9565	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9566	ctsio->be_move_done = ctl_config_move_done;
9567	ctl_datamove((union ctl_io *)ctsio);
9568
9569	return (retval);
9570}
9571
9572int
9573ctl_request_sense(struct ctl_scsiio *ctsio)
9574{
9575	struct scsi_request_sense *cdb;
9576	struct scsi_sense_data *sense_ptr;
9577	struct ctl_lun *lun;
9578	uint32_t initidx;
9579	int have_error;
9580	scsi_sense_data_type sense_format;
9581
9582	cdb = (struct scsi_request_sense *)ctsio->cdb;
9583
9584	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9585
9586	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9587
9588	/*
9589	 * Determine which sense format the user wants.
9590	 */
9591	if (cdb->byte2 & SRS_DESC)
9592		sense_format = SSD_TYPE_DESC;
9593	else
9594		sense_format = SSD_TYPE_FIXED;
9595
9596	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9597	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9598	ctsio->kern_sg_entries = 0;
9599
9600	/*
9601	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9602	 * larger than the largest allowed value for the length field in the
9603	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9604	 */
9605	ctsio->residual = 0;
9606	ctsio->kern_data_len = cdb->length;
9607	ctsio->kern_total_len = cdb->length;
9608
9609	ctsio->kern_data_resid = 0;
9610	ctsio->kern_rel_offset = 0;
9611	ctsio->kern_sg_entries = 0;
9612
9613	/*
9614	 * If we don't have a LUN, we don't have any pending sense.
9615	 */
9616	if (lun == NULL)
9617		goto no_sense;
9618
9619	have_error = 0;
9620	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9621	/*
9622	 * Check for pending sense, and then for pending unit attentions.
9623	 * Pending sense gets returned first, then pending unit attentions.
9624	 */
9625	mtx_lock(&lun->lun_lock);
9626#ifdef CTL_WITH_CA
9627	if (ctl_is_set(lun->have_ca, initidx)) {
9628		scsi_sense_data_type stored_format;
9629
9630		/*
9631		 * Check to see which sense format was used for the stored
9632		 * sense data.
9633		 */
9634		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9635
9636		/*
9637		 * If the user requested a different sense format than the
9638		 * one we stored, then we need to convert it to the other
9639		 * format.  If we're going from descriptor to fixed format
9640		 * sense data, we may lose things in translation, depending
9641		 * on what options were used.
9642		 *
9643		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9644		 * for some reason we'll just copy it out as-is.
9645		 */
9646		if ((stored_format == SSD_TYPE_FIXED)
9647		 && (sense_format == SSD_TYPE_DESC))
9648			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9649			    &lun->pending_sense[initidx],
9650			    (struct scsi_sense_data_desc *)sense_ptr);
9651		else if ((stored_format == SSD_TYPE_DESC)
9652		      && (sense_format == SSD_TYPE_FIXED))
9653			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9654			    &lun->pending_sense[initidx],
9655			    (struct scsi_sense_data_fixed *)sense_ptr);
9656		else
9657			memcpy(sense_ptr, &lun->pending_sense[initidx],
9658			       ctl_min(sizeof(*sense_ptr),
9659			       sizeof(lun->pending_sense[initidx])));
9660
9661		ctl_clear_mask(lun->have_ca, initidx);
9662		have_error = 1;
9663	} else
9664#endif
9665	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9666		ctl_ua_type ua_type;
9667
9668		ua_type = ctl_build_ua(lun->pending_ua[initidx],
9669				       sense_ptr, sense_format);
9670		if (ua_type != CTL_UA_NONE) {
9671			have_error = 1;
9672			/* We're reporting this UA, so clear it */
9673			lun->pending_ua[initidx] &= ~ua_type;
9674		}
9675	}
9676	mtx_unlock(&lun->lun_lock);
9677
9678	/*
9679	 * We already have a pending error, return it.
9680	 */
9681	if (have_error != 0) {
9682		/*
9683		 * We report the SCSI status as OK, since the status of the
9684		 * request sense command itself is OK.
9685		 */
9686		ctsio->scsi_status = SCSI_STATUS_OK;
9687
9688		/*
9689		 * We report 0 for the sense length, because we aren't doing
9690		 * autosense in this case.  We're reporting sense as
9691		 * parameter data.
9692		 */
9693		ctsio->sense_len = 0;
9694		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9695		ctsio->be_move_done = ctl_config_move_done;
9696		ctl_datamove((union ctl_io *)ctsio);
9697
9698		return (CTL_RETVAL_COMPLETE);
9699	}
9700
9701no_sense:
9702
9703	/*
9704	 * No sense information to report, so we report that everything is
9705	 * okay.
9706	 */
9707	ctl_set_sense_data(sense_ptr,
9708			   lun,
9709			   sense_format,
9710			   /*current_error*/ 1,
9711			   /*sense_key*/ SSD_KEY_NO_SENSE,
9712			   /*asc*/ 0x00,
9713			   /*ascq*/ 0x00,
9714			   SSD_ELEM_NONE);
9715
9716	ctsio->scsi_status = SCSI_STATUS_OK;
9717
9718	/*
9719	 * We report 0 for the sense length, because we aren't doing
9720	 * autosense in this case.  We're reporting sense as parameter data.
9721	 */
9722	ctsio->sense_len = 0;
9723	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9724	ctsio->be_move_done = ctl_config_move_done;
9725	ctl_datamove((union ctl_io *)ctsio);
9726
9727	return (CTL_RETVAL_COMPLETE);
9728}
9729
9730int
9731ctl_tur(struct ctl_scsiio *ctsio)
9732{
9733	struct ctl_lun *lun;
9734
9735	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9736
9737	CTL_DEBUG_PRINT(("ctl_tur\n"));
9738
9739	if (lun == NULL)
9740		return (EINVAL);
9741
9742	ctsio->scsi_status = SCSI_STATUS_OK;
9743	ctsio->io_hdr.status = CTL_SUCCESS;
9744
9745	ctl_done((union ctl_io *)ctsio);
9746
9747	return (CTL_RETVAL_COMPLETE);
9748}
9749
9750#ifdef notyet
9751static int
9752ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9753{
9754
9755}
9756#endif
9757
9758static int
9759ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9760{
9761	struct scsi_vpd_supported_pages *pages;
9762	int sup_page_size;
9763	struct ctl_lun *lun;
9764
9765	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9766
9767	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9768	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9769	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9770	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9771	ctsio->kern_sg_entries = 0;
9772
9773	if (sup_page_size < alloc_len) {
9774		ctsio->residual = alloc_len - sup_page_size;
9775		ctsio->kern_data_len = sup_page_size;
9776		ctsio->kern_total_len = sup_page_size;
9777	} else {
9778		ctsio->residual = 0;
9779		ctsio->kern_data_len = alloc_len;
9780		ctsio->kern_total_len = alloc_len;
9781	}
9782	ctsio->kern_data_resid = 0;
9783	ctsio->kern_rel_offset = 0;
9784	ctsio->kern_sg_entries = 0;
9785
9786	/*
9787	 * The control device is always connected.  The disk device, on the
9788	 * other hand, may not be online all the time.  Need to change this
9789	 * to figure out whether the disk device is actually online or not.
9790	 */
9791	if (lun != NULL)
9792		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9793				lun->be_lun->lun_type;
9794	else
9795		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9796
9797	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9798	/* Supported VPD pages */
9799	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9800	/* Serial Number */
9801	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9802	/* Device Identification */
9803	pages->page_list[2] = SVPD_DEVICE_ID;
9804	/* SCSI Ports */
9805	pages->page_list[3] = SVPD_SCSI_PORTS;
9806	/* Third-party Copy */
9807	pages->page_list[4] = SVPD_SCSI_TPC;
9808	/* Block limits */
9809	pages->page_list[5] = SVPD_BLOCK_LIMITS;
9810	/* Logical Block Provisioning */
9811	pages->page_list[6] = SVPD_LBP;
9812
9813	ctsio->scsi_status = SCSI_STATUS_OK;
9814
9815	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9816	ctsio->be_move_done = ctl_config_move_done;
9817	ctl_datamove((union ctl_io *)ctsio);
9818
9819	return (CTL_RETVAL_COMPLETE);
9820}
9821
9822static int
9823ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9824{
9825	struct scsi_vpd_unit_serial_number *sn_ptr;
9826	struct ctl_lun *lun;
9827
9828	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9829
9830	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9831	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9832	ctsio->kern_sg_entries = 0;
9833
9834	if (sizeof(*sn_ptr) < alloc_len) {
9835		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9836		ctsio->kern_data_len = sizeof(*sn_ptr);
9837		ctsio->kern_total_len = sizeof(*sn_ptr);
9838	} else {
9839		ctsio->residual = 0;
9840		ctsio->kern_data_len = alloc_len;
9841		ctsio->kern_total_len = alloc_len;
9842	}
9843	ctsio->kern_data_resid = 0;
9844	ctsio->kern_rel_offset = 0;
9845	ctsio->kern_sg_entries = 0;
9846
9847	/*
9848	 * The control device is always connected.  The disk device, on the
9849	 * other hand, may not be online all the time.  Need to change this
9850	 * to figure out whether the disk device is actually online or not.
9851	 */
9852	if (lun != NULL)
9853		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9854				  lun->be_lun->lun_type;
9855	else
9856		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9857
9858	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9859	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9860	/*
9861	 * If we don't have a LUN, we just leave the serial number as
9862	 * all spaces.
9863	 */
9864	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9865	if (lun != NULL) {
9866		strncpy((char *)sn_ptr->serial_num,
9867			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9868	}
9869	ctsio->scsi_status = SCSI_STATUS_OK;
9870
9871	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9872	ctsio->be_move_done = ctl_config_move_done;
9873	ctl_datamove((union ctl_io *)ctsio);
9874
9875	return (CTL_RETVAL_COMPLETE);
9876}
9877
9878
9879static int
9880ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9881{
9882	struct scsi_vpd_device_id *devid_ptr;
9883	struct scsi_vpd_id_descriptor *desc;
9884	struct ctl_softc *ctl_softc;
9885	struct ctl_lun *lun;
9886	struct ctl_port *port;
9887	int data_len;
9888	uint8_t proto;
9889
9890	ctl_softc = control_softc;
9891
9892	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9893	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9894
9895	data_len = sizeof(struct scsi_vpd_device_id) +
9896	    sizeof(struct scsi_vpd_id_descriptor) +
9897		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9898	    sizeof(struct scsi_vpd_id_descriptor) +
9899		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9900	if (lun && lun->lun_devid)
9901		data_len += lun->lun_devid->len;
9902	if (port->port_devid)
9903		data_len += port->port_devid->len;
9904	if (port->target_devid)
9905		data_len += port->target_devid->len;
9906
9907	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9908	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9909	ctsio->kern_sg_entries = 0;
9910
9911	if (data_len < alloc_len) {
9912		ctsio->residual = alloc_len - data_len;
9913		ctsio->kern_data_len = data_len;
9914		ctsio->kern_total_len = data_len;
9915	} else {
9916		ctsio->residual = 0;
9917		ctsio->kern_data_len = alloc_len;
9918		ctsio->kern_total_len = alloc_len;
9919	}
9920	ctsio->kern_data_resid = 0;
9921	ctsio->kern_rel_offset = 0;
9922	ctsio->kern_sg_entries = 0;
9923
9924	/*
9925	 * The control device is always connected.  The disk device, on the
9926	 * other hand, may not be online all the time.
9927	 */
9928	if (lun != NULL)
9929		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9930				     lun->be_lun->lun_type;
9931	else
9932		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9933	devid_ptr->page_code = SVPD_DEVICE_ID;
9934	scsi_ulto2b(data_len - 4, devid_ptr->length);
9935
9936	if (port->port_type == CTL_PORT_FC)
9937		proto = SCSI_PROTO_FC << 4;
9938	else if (port->port_type == CTL_PORT_ISCSI)
9939		proto = SCSI_PROTO_ISCSI << 4;
9940	else
9941		proto = SCSI_PROTO_SPI << 4;
9942	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9943
9944	/*
9945	 * We're using a LUN association here.  i.e., this device ID is a
9946	 * per-LUN identifier.
9947	 */
9948	if (lun && lun->lun_devid) {
9949		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9950		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9951		    lun->lun_devid->len);
9952	}
9953
9954	/*
9955	 * This is for the WWPN which is a port association.
9956	 */
9957	if (port->port_devid) {
9958		memcpy(desc, port->port_devid->data, port->port_devid->len);
9959		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9960		    port->port_devid->len);
9961	}
9962
9963	/*
9964	 * This is for the Relative Target Port(type 4h) identifier
9965	 */
9966	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9967	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9968	    SVPD_ID_TYPE_RELTARG;
9969	desc->length = 4;
9970	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9971	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9972	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9973
9974	/*
9975	 * This is for the Target Port Group(type 5h) identifier
9976	 */
9977	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9978	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9979	    SVPD_ID_TYPE_TPORTGRP;
9980	desc->length = 4;
9981	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9982	    &desc->identifier[2]);
9983	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9984	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9985
9986	/*
9987	 * This is for the Target identifier
9988	 */
9989	if (port->target_devid) {
9990		memcpy(desc, port->target_devid->data, port->target_devid->len);
9991	}
9992
9993	ctsio->scsi_status = SCSI_STATUS_OK;
9994	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9995	ctsio->be_move_done = ctl_config_move_done;
9996	ctl_datamove((union ctl_io *)ctsio);
9997
9998	return (CTL_RETVAL_COMPLETE);
9999}
10000
10001static int
10002ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10003{
10004	struct ctl_softc *softc = control_softc;
10005	struct scsi_vpd_scsi_ports *sp;
10006	struct scsi_vpd_port_designation *pd;
10007	struct scsi_vpd_port_designation_cont *pdc;
10008	struct ctl_lun *lun;
10009	struct ctl_port *port;
10010	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10011	int num_target_port_groups, single;
10012
10013	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10014
10015	single = ctl_is_single;
10016	if (single)
10017		num_target_port_groups = 1;
10018	else
10019		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10020	num_target_ports = 0;
10021	iid_len = 0;
10022	id_len = 0;
10023	mtx_lock(&softc->ctl_lock);
10024	STAILQ_FOREACH(port, &softc->port_list, links) {
10025		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10026			continue;
10027		if (lun != NULL &&
10028		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10029		    CTL_MAX_LUNS)
10030			continue;
10031		num_target_ports++;
10032		if (port->init_devid)
10033			iid_len += port->init_devid->len;
10034		if (port->port_devid)
10035			id_len += port->port_devid->len;
10036	}
10037	mtx_unlock(&softc->ctl_lock);
10038
10039	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10040	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10041	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10042	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10043	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10044	ctsio->kern_sg_entries = 0;
10045
10046	if (data_len < alloc_len) {
10047		ctsio->residual = alloc_len - data_len;
10048		ctsio->kern_data_len = data_len;
10049		ctsio->kern_total_len = data_len;
10050	} else {
10051		ctsio->residual = 0;
10052		ctsio->kern_data_len = alloc_len;
10053		ctsio->kern_total_len = alloc_len;
10054	}
10055	ctsio->kern_data_resid = 0;
10056	ctsio->kern_rel_offset = 0;
10057	ctsio->kern_sg_entries = 0;
10058
10059	/*
10060	 * The control device is always connected.  The disk device, on the
10061	 * other hand, may not be online all the time.  Need to change this
10062	 * to figure out whether the disk device is actually online or not.
10063	 */
10064	if (lun != NULL)
10065		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10066				  lun->be_lun->lun_type;
10067	else
10068		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10069
10070	sp->page_code = SVPD_SCSI_PORTS;
10071	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10072	    sp->page_length);
10073	pd = &sp->design[0];
10074
10075	mtx_lock(&softc->ctl_lock);
10076	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10077		pg = 0;
10078	else
10079		pg = 1;
10080	for (g = 0; g < num_target_port_groups; g++) {
10081		STAILQ_FOREACH(port, &softc->port_list, links) {
10082			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10083				continue;
10084			if (lun != NULL &&
10085			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10086			    CTL_MAX_LUNS)
10087				continue;
10088			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10089			scsi_ulto2b(p, pd->relative_port_id);
10090			if (port->init_devid && g == pg) {
10091				iid_len = port->init_devid->len;
10092				memcpy(pd->initiator_transportid,
10093				    port->init_devid->data, port->init_devid->len);
10094			} else
10095				iid_len = 0;
10096			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10097			pdc = (struct scsi_vpd_port_designation_cont *)
10098			    (&pd->initiator_transportid[iid_len]);
10099			if (port->port_devid && g == pg) {
10100				id_len = port->port_devid->len;
10101				memcpy(pdc->target_port_descriptors,
10102				    port->port_devid->data, port->port_devid->len);
10103			} else
10104				id_len = 0;
10105			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10106			pd = (struct scsi_vpd_port_designation *)
10107			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10108		}
10109	}
10110	mtx_unlock(&softc->ctl_lock);
10111
10112	ctsio->scsi_status = SCSI_STATUS_OK;
10113	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10114	ctsio->be_move_done = ctl_config_move_done;
10115	ctl_datamove((union ctl_io *)ctsio);
10116
10117	return (CTL_RETVAL_COMPLETE);
10118}
10119
10120static int
10121ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10122{
10123	struct scsi_vpd_block_limits *bl_ptr;
10124	struct ctl_lun *lun;
10125	int bs;
10126
10127	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10128
10129	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10130	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10131	ctsio->kern_sg_entries = 0;
10132
10133	if (sizeof(*bl_ptr) < alloc_len) {
10134		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10135		ctsio->kern_data_len = sizeof(*bl_ptr);
10136		ctsio->kern_total_len = sizeof(*bl_ptr);
10137	} else {
10138		ctsio->residual = 0;
10139		ctsio->kern_data_len = alloc_len;
10140		ctsio->kern_total_len = alloc_len;
10141	}
10142	ctsio->kern_data_resid = 0;
10143	ctsio->kern_rel_offset = 0;
10144	ctsio->kern_sg_entries = 0;
10145
10146	/*
10147	 * The control device is always connected.  The disk device, on the
10148	 * other hand, may not be online all the time.  Need to change this
10149	 * to figure out whether the disk device is actually online or not.
10150	 */
10151	if (lun != NULL)
10152		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10153				  lun->be_lun->lun_type;
10154	else
10155		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10156
10157	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10158	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10159	bl_ptr->max_cmp_write_len = 0xff;
10160	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10161	if (lun != NULL) {
10162		bs = lun->be_lun->blocksize;
10163		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10164		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10165			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10166			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10167		}
10168	}
10169	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10170
10171	ctsio->scsi_status = SCSI_STATUS_OK;
10172	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10173	ctsio->be_move_done = ctl_config_move_done;
10174	ctl_datamove((union ctl_io *)ctsio);
10175
10176	return (CTL_RETVAL_COMPLETE);
10177}
10178
10179static int
10180ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10181{
10182	struct scsi_vpd_logical_block_prov *lbp_ptr;
10183	struct ctl_lun *lun;
10184
10185	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10186
10187	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10188	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10189	ctsio->kern_sg_entries = 0;
10190
10191	if (sizeof(*lbp_ptr) < alloc_len) {
10192		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10193		ctsio->kern_data_len = sizeof(*lbp_ptr);
10194		ctsio->kern_total_len = sizeof(*lbp_ptr);
10195	} else {
10196		ctsio->residual = 0;
10197		ctsio->kern_data_len = alloc_len;
10198		ctsio->kern_total_len = alloc_len;
10199	}
10200	ctsio->kern_data_resid = 0;
10201	ctsio->kern_rel_offset = 0;
10202	ctsio->kern_sg_entries = 0;
10203
10204	/*
10205	 * The control device is always connected.  The disk device, on the
10206	 * other hand, may not be online all the time.  Need to change this
10207	 * to figure out whether the disk device is actually online or not.
10208	 */
10209	if (lun != NULL)
10210		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10211				  lun->be_lun->lun_type;
10212	else
10213		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10214
10215	lbp_ptr->page_code = SVPD_LBP;
10216	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10217		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10218
10219	ctsio->scsi_status = SCSI_STATUS_OK;
10220	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10221	ctsio->be_move_done = ctl_config_move_done;
10222	ctl_datamove((union ctl_io *)ctsio);
10223
10224	return (CTL_RETVAL_COMPLETE);
10225}
10226
10227static int
10228ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10229{
10230	struct scsi_inquiry *cdb;
10231	struct ctl_lun *lun;
10232	int alloc_len, retval;
10233
10234	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10235	cdb = (struct scsi_inquiry *)ctsio->cdb;
10236
10237	retval = CTL_RETVAL_COMPLETE;
10238
10239	alloc_len = scsi_2btoul(cdb->length);
10240
10241	switch (cdb->page_code) {
10242	case SVPD_SUPPORTED_PAGES:
10243		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10244		break;
10245	case SVPD_UNIT_SERIAL_NUMBER:
10246		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10247		break;
10248	case SVPD_DEVICE_ID:
10249		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10250		break;
10251	case SVPD_SCSI_PORTS:
10252		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10253		break;
10254	case SVPD_SCSI_TPC:
10255		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10256		break;
10257	case SVPD_BLOCK_LIMITS:
10258		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10259		break;
10260	case SVPD_LBP:
10261		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10262		break;
10263	default:
10264		ctl_set_invalid_field(ctsio,
10265				      /*sks_valid*/ 1,
10266				      /*command*/ 1,
10267				      /*field*/ 2,
10268				      /*bit_valid*/ 0,
10269				      /*bit*/ 0);
10270		ctl_done((union ctl_io *)ctsio);
10271		retval = CTL_RETVAL_COMPLETE;
10272		break;
10273	}
10274
10275	return (retval);
10276}
10277
10278static int
10279ctl_inquiry_std(struct ctl_scsiio *ctsio)
10280{
10281	struct scsi_inquiry_data *inq_ptr;
10282	struct scsi_inquiry *cdb;
10283	struct ctl_softc *ctl_softc;
10284	struct ctl_lun *lun;
10285	char *val;
10286	uint32_t alloc_len;
10287	ctl_port_type port_type;
10288
10289	ctl_softc = control_softc;
10290
10291	/*
10292	 * Figure out whether we're talking to a Fibre Channel port or not.
10293	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10294	 * SCSI front ends.
10295	 */
10296	port_type = ctl_softc->ctl_ports[
10297	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10298	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10299		port_type = CTL_PORT_SCSI;
10300
10301	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10302	cdb = (struct scsi_inquiry *)ctsio->cdb;
10303	alloc_len = scsi_2btoul(cdb->length);
10304
10305	/*
10306	 * We malloc the full inquiry data size here and fill it
10307	 * in.  If the user only asks for less, we'll give him
10308	 * that much.
10309	 */
10310	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10311	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10312	ctsio->kern_sg_entries = 0;
10313	ctsio->kern_data_resid = 0;
10314	ctsio->kern_rel_offset = 0;
10315
10316	if (sizeof(*inq_ptr) < alloc_len) {
10317		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10318		ctsio->kern_data_len = sizeof(*inq_ptr);
10319		ctsio->kern_total_len = sizeof(*inq_ptr);
10320	} else {
10321		ctsio->residual = 0;
10322		ctsio->kern_data_len = alloc_len;
10323		ctsio->kern_total_len = alloc_len;
10324	}
10325
10326	/*
10327	 * If we have a LUN configured, report it as connected.  Otherwise,
10328	 * report that it is offline or no device is supported, depending
10329	 * on the value of inquiry_pq_no_lun.
10330	 *
10331	 * According to the spec (SPC-4 r34), the peripheral qualifier
10332	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10333	 *
10334	 * "A peripheral device having the specified peripheral device type
10335	 * is not connected to this logical unit. However, the device
10336	 * server is capable of supporting the specified peripheral device
10337	 * type on this logical unit."
10338	 *
10339	 * According to the same spec, the peripheral qualifier
10340	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10341	 *
10342	 * "The device server is not capable of supporting a peripheral
10343	 * device on this logical unit. For this peripheral qualifier the
10344	 * peripheral device type shall be set to 1Fh. All other peripheral
10345	 * device type values are reserved for this peripheral qualifier."
10346	 *
10347	 * Given the text, it would seem that we probably want to report that
10348	 * the LUN is offline here.  There is no LUN connected, but we can
10349	 * support a LUN at the given LUN number.
10350	 *
10351	 * In the real world, though, it sounds like things are a little
10352	 * different:
10353	 *
10354	 * - Linux, when presented with a LUN with the offline peripheral
10355	 *   qualifier, will create an sg driver instance for it.  So when
10356	 *   you attach it to CTL, you wind up with a ton of sg driver
10357	 *   instances.  (One for every LUN that Linux bothered to probe.)
10358	 *   Linux does this despite the fact that it issues a REPORT LUNs
10359	 *   to LUN 0 to get the inventory of supported LUNs.
10360	 *
10361	 * - There is other anecdotal evidence (from Emulex folks) about
10362	 *   arrays that use the offline peripheral qualifier for LUNs that
10363	 *   are on the "passive" path in an active/passive array.
10364	 *
10365	 * So the solution is provide a hopefully reasonable default
10366	 * (return bad/no LUN) and allow the user to change the behavior
10367	 * with a tunable/sysctl variable.
10368	 */
10369	if (lun != NULL)
10370		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10371				  lun->be_lun->lun_type;
10372	else if (ctl_softc->inquiry_pq_no_lun == 0)
10373		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10374	else
10375		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10376
10377	/* RMB in byte 2 is 0 */
10378	inq_ptr->version = SCSI_REV_SPC4;
10379
10380	/*
10381	 * According to SAM-3, even if a device only supports a single
10382	 * level of LUN addressing, it should still set the HISUP bit:
10383	 *
10384	 * 4.9.1 Logical unit numbers overview
10385	 *
10386	 * All logical unit number formats described in this standard are
10387	 * hierarchical in structure even when only a single level in that
10388	 * hierarchy is used. The HISUP bit shall be set to one in the
10389	 * standard INQUIRY data (see SPC-2) when any logical unit number
10390	 * format described in this standard is used.  Non-hierarchical
10391	 * formats are outside the scope of this standard.
10392	 *
10393	 * Therefore we set the HiSup bit here.
10394	 *
10395	 * The reponse format is 2, per SPC-3.
10396	 */
10397	inq_ptr->response_format = SID_HiSup | 2;
10398
10399	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10400	CTL_DEBUG_PRINT(("additional_length = %d\n",
10401			 inq_ptr->additional_length));
10402
10403	inq_ptr->spc3_flags = SPC3_SID_3PC;
10404	if (!ctl_is_single)
10405		inq_ptr->spc3_flags |= SPC3_SID_TPGS_IMPLICIT;
10406	/* 16 bit addressing */
10407	if (port_type == CTL_PORT_SCSI)
10408		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10409	/* XXX set the SID_MultiP bit here if we're actually going to
10410	   respond on multiple ports */
10411	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10412
10413	/* 16 bit data bus, synchronous transfers */
10414	if (port_type == CTL_PORT_SCSI)
10415		inq_ptr->flags = SID_WBus16 | SID_Sync;
10416	/*
10417	 * XXX KDM do we want to support tagged queueing on the control
10418	 * device at all?
10419	 */
10420	if ((lun == NULL)
10421	 || (lun->be_lun->lun_type != T_PROCESSOR))
10422		inq_ptr->flags |= SID_CmdQue;
10423	/*
10424	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10425	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10426	 * name and 4 bytes for the revision.
10427	 */
10428	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10429	    "vendor")) == NULL) {
10430		strcpy(inq_ptr->vendor, CTL_VENDOR);
10431	} else {
10432		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10433		strncpy(inq_ptr->vendor, val,
10434		    min(sizeof(inq_ptr->vendor), strlen(val)));
10435	}
10436	if (lun == NULL) {
10437		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10438	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10439		switch (lun->be_lun->lun_type) {
10440		case T_DIRECT:
10441			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10442			break;
10443		case T_PROCESSOR:
10444			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10445			break;
10446		default:
10447			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10448			break;
10449		}
10450	} else {
10451		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10452		strncpy(inq_ptr->product, val,
10453		    min(sizeof(inq_ptr->product), strlen(val)));
10454	}
10455
10456	/*
10457	 * XXX make this a macro somewhere so it automatically gets
10458	 * incremented when we make changes.
10459	 */
10460	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10461	    "revision")) == NULL) {
10462		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10463	} else {
10464		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10465		strncpy(inq_ptr->revision, val,
10466		    min(sizeof(inq_ptr->revision), strlen(val)));
10467	}
10468
10469	/*
10470	 * For parallel SCSI, we support double transition and single
10471	 * transition clocking.  We also support QAS (Quick Arbitration
10472	 * and Selection) and Information Unit transfers on both the
10473	 * control and array devices.
10474	 */
10475	if (port_type == CTL_PORT_SCSI)
10476		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10477				    SID_SPI_IUS;
10478
10479	/* SAM-5 (no version claimed) */
10480	scsi_ulto2b(0x00A0, inq_ptr->version1);
10481	/* SPC-4 (no version claimed) */
10482	scsi_ulto2b(0x0460, inq_ptr->version2);
10483	if (port_type == CTL_PORT_FC) {
10484		/* FCP-2 ANSI INCITS.350:2003 */
10485		scsi_ulto2b(0x0917, inq_ptr->version3);
10486	} else if (port_type == CTL_PORT_SCSI) {
10487		/* SPI-4 ANSI INCITS.362:200x */
10488		scsi_ulto2b(0x0B56, inq_ptr->version3);
10489	} else if (port_type == CTL_PORT_ISCSI) {
10490		/* iSCSI (no version claimed) */
10491		scsi_ulto2b(0x0960, inq_ptr->version3);
10492	} else if (port_type == CTL_PORT_SAS) {
10493		/* SAS (no version claimed) */
10494		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10495	}
10496
10497	if (lun == NULL) {
10498		/* SBC-3 (no version claimed) */
10499		scsi_ulto2b(0x04C0, inq_ptr->version4);
10500	} else {
10501		switch (lun->be_lun->lun_type) {
10502		case T_DIRECT:
10503			/* SBC-3 (no version claimed) */
10504			scsi_ulto2b(0x04C0, inq_ptr->version4);
10505			break;
10506		case T_PROCESSOR:
10507		default:
10508			break;
10509		}
10510	}
10511
10512	ctsio->scsi_status = SCSI_STATUS_OK;
10513	if (ctsio->kern_data_len > 0) {
10514		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10515		ctsio->be_move_done = ctl_config_move_done;
10516		ctl_datamove((union ctl_io *)ctsio);
10517	} else {
10518		ctsio->io_hdr.status = CTL_SUCCESS;
10519		ctl_done((union ctl_io *)ctsio);
10520	}
10521
10522	return (CTL_RETVAL_COMPLETE);
10523}
10524
10525int
10526ctl_inquiry(struct ctl_scsiio *ctsio)
10527{
10528	struct scsi_inquiry *cdb;
10529	int retval;
10530
10531	cdb = (struct scsi_inquiry *)ctsio->cdb;
10532
10533	retval = 0;
10534
10535	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10536
10537	/*
10538	 * Right now, we don't support the CmdDt inquiry information.
10539	 * This would be nice to support in the future.  When we do
10540	 * support it, we should change this test so that it checks to make
10541	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10542	 */
10543#ifdef notyet
10544	if (((cdb->byte2 & SI_EVPD)
10545	 && (cdb->byte2 & SI_CMDDT)))
10546#endif
10547	if (cdb->byte2 & SI_CMDDT) {
10548		/*
10549		 * Point to the SI_CMDDT bit.  We might change this
10550		 * when we support SI_CMDDT, but since both bits would be
10551		 * "wrong", this should probably just stay as-is then.
10552		 */
10553		ctl_set_invalid_field(ctsio,
10554				      /*sks_valid*/ 1,
10555				      /*command*/ 1,
10556				      /*field*/ 1,
10557				      /*bit_valid*/ 1,
10558				      /*bit*/ 1);
10559		ctl_done((union ctl_io *)ctsio);
10560		return (CTL_RETVAL_COMPLETE);
10561	}
10562	if (cdb->byte2 & SI_EVPD)
10563		retval = ctl_inquiry_evpd(ctsio);
10564#ifdef notyet
10565	else if (cdb->byte2 & SI_CMDDT)
10566		retval = ctl_inquiry_cmddt(ctsio);
10567#endif
10568	else
10569		retval = ctl_inquiry_std(ctsio);
10570
10571	return (retval);
10572}
10573
10574/*
10575 * For known CDB types, parse the LBA and length.
10576 */
10577static int
10578ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10579{
10580	if (io->io_hdr.io_type != CTL_IO_SCSI)
10581		return (1);
10582
10583	switch (io->scsiio.cdb[0]) {
10584	case COMPARE_AND_WRITE: {
10585		struct scsi_compare_and_write *cdb;
10586
10587		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10588
10589		*lba = scsi_8btou64(cdb->addr);
10590		*len = cdb->length;
10591		break;
10592	}
10593	case READ_6:
10594	case WRITE_6: {
10595		struct scsi_rw_6 *cdb;
10596
10597		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10598
10599		*lba = scsi_3btoul(cdb->addr);
10600		/* only 5 bits are valid in the most significant address byte */
10601		*lba &= 0x1fffff;
10602		*len = cdb->length;
10603		break;
10604	}
10605	case READ_10:
10606	case WRITE_10: {
10607		struct scsi_rw_10 *cdb;
10608
10609		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10610
10611		*lba = scsi_4btoul(cdb->addr);
10612		*len = scsi_2btoul(cdb->length);
10613		break;
10614	}
10615	case WRITE_VERIFY_10: {
10616		struct scsi_write_verify_10 *cdb;
10617
10618		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10619
10620		*lba = scsi_4btoul(cdb->addr);
10621		*len = scsi_2btoul(cdb->length);
10622		break;
10623	}
10624	case READ_12:
10625	case WRITE_12: {
10626		struct scsi_rw_12 *cdb;
10627
10628		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10629
10630		*lba = scsi_4btoul(cdb->addr);
10631		*len = scsi_4btoul(cdb->length);
10632		break;
10633	}
10634	case WRITE_VERIFY_12: {
10635		struct scsi_write_verify_12 *cdb;
10636
10637		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10638
10639		*lba = scsi_4btoul(cdb->addr);
10640		*len = scsi_4btoul(cdb->length);
10641		break;
10642	}
10643	case READ_16:
10644	case WRITE_16: {
10645		struct scsi_rw_16 *cdb;
10646
10647		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10648
10649		*lba = scsi_8btou64(cdb->addr);
10650		*len = scsi_4btoul(cdb->length);
10651		break;
10652	}
10653	case WRITE_VERIFY_16: {
10654		struct scsi_write_verify_16 *cdb;
10655
10656		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10657
10658
10659		*lba = scsi_8btou64(cdb->addr);
10660		*len = scsi_4btoul(cdb->length);
10661		break;
10662	}
10663	case WRITE_SAME_10: {
10664		struct scsi_write_same_10 *cdb;
10665
10666		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10667
10668		*lba = scsi_4btoul(cdb->addr);
10669		*len = scsi_2btoul(cdb->length);
10670		break;
10671	}
10672	case WRITE_SAME_16: {
10673		struct scsi_write_same_16 *cdb;
10674
10675		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10676
10677		*lba = scsi_8btou64(cdb->addr);
10678		*len = scsi_4btoul(cdb->length);
10679		break;
10680	}
10681	case VERIFY_10: {
10682		struct scsi_verify_10 *cdb;
10683
10684		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10685
10686		*lba = scsi_4btoul(cdb->addr);
10687		*len = scsi_2btoul(cdb->length);
10688		break;
10689	}
10690	case VERIFY_12: {
10691		struct scsi_verify_12 *cdb;
10692
10693		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10694
10695		*lba = scsi_4btoul(cdb->addr);
10696		*len = scsi_4btoul(cdb->length);
10697		break;
10698	}
10699	case VERIFY_16: {
10700		struct scsi_verify_16 *cdb;
10701
10702		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10703
10704		*lba = scsi_8btou64(cdb->addr);
10705		*len = scsi_4btoul(cdb->length);
10706		break;
10707	}
10708	default:
10709		return (1);
10710		break; /* NOTREACHED */
10711	}
10712
10713	return (0);
10714}
10715
10716static ctl_action
10717ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10718{
10719	uint64_t endlba1, endlba2;
10720
10721	endlba1 = lba1 + len1 - 1;
10722	endlba2 = lba2 + len2 - 1;
10723
10724	if ((endlba1 < lba2)
10725	 || (endlba2 < lba1))
10726		return (CTL_ACTION_PASS);
10727	else
10728		return (CTL_ACTION_BLOCK);
10729}
10730
10731static ctl_action
10732ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10733{
10734	uint64_t lba1, lba2;
10735	uint32_t len1, len2;
10736	int retval;
10737
10738	retval = ctl_get_lba_len(io1, &lba1, &len1);
10739	if (retval != 0)
10740		return (CTL_ACTION_ERROR);
10741
10742	retval = ctl_get_lba_len(io2, &lba2, &len2);
10743	if (retval != 0)
10744		return (CTL_ACTION_ERROR);
10745
10746	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10747}
10748
10749static ctl_action
10750ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10751{
10752	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10753	ctl_serialize_action *serialize_row;
10754
10755	/*
10756	 * The initiator attempted multiple untagged commands at the same
10757	 * time.  Can't do that.
10758	 */
10759	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10760	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10761	 && ((pending_io->io_hdr.nexus.targ_port ==
10762	      ooa_io->io_hdr.nexus.targ_port)
10763	  && (pending_io->io_hdr.nexus.initid.id ==
10764	      ooa_io->io_hdr.nexus.initid.id))
10765	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10766		return (CTL_ACTION_OVERLAP);
10767
10768	/*
10769	 * The initiator attempted to send multiple tagged commands with
10770	 * the same ID.  (It's fine if different initiators have the same
10771	 * tag ID.)
10772	 *
10773	 * Even if all of those conditions are true, we don't kill the I/O
10774	 * if the command ahead of us has been aborted.  We won't end up
10775	 * sending it to the FETD, and it's perfectly legal to resend a
10776	 * command with the same tag number as long as the previous
10777	 * instance of this tag number has been aborted somehow.
10778	 */
10779	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10780	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10781	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10782	 && ((pending_io->io_hdr.nexus.targ_port ==
10783	      ooa_io->io_hdr.nexus.targ_port)
10784	  && (pending_io->io_hdr.nexus.initid.id ==
10785	      ooa_io->io_hdr.nexus.initid.id))
10786	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10787		return (CTL_ACTION_OVERLAP_TAG);
10788
10789	/*
10790	 * If we get a head of queue tag, SAM-3 says that we should
10791	 * immediately execute it.
10792	 *
10793	 * What happens if this command would normally block for some other
10794	 * reason?  e.g. a request sense with a head of queue tag
10795	 * immediately after a write.  Normally that would block, but this
10796	 * will result in its getting executed immediately...
10797	 *
10798	 * We currently return "pass" instead of "skip", so we'll end up
10799	 * going through the rest of the queue to check for overlapped tags.
10800	 *
10801	 * XXX KDM check for other types of blockage first??
10802	 */
10803	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10804		return (CTL_ACTION_PASS);
10805
10806	/*
10807	 * Ordered tags have to block until all items ahead of them
10808	 * have completed.  If we get called with an ordered tag, we always
10809	 * block, if something else is ahead of us in the queue.
10810	 */
10811	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10812		return (CTL_ACTION_BLOCK);
10813
10814	/*
10815	 * Simple tags get blocked until all head of queue and ordered tags
10816	 * ahead of them have completed.  I'm lumping untagged commands in
10817	 * with simple tags here.  XXX KDM is that the right thing to do?
10818	 */
10819	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10820	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10821	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10822	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10823		return (CTL_ACTION_BLOCK);
10824
10825	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10826	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10827
10828	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10829
10830	switch (serialize_row[pending_entry->seridx]) {
10831	case CTL_SER_BLOCK:
10832		return (CTL_ACTION_BLOCK);
10833		break; /* NOTREACHED */
10834	case CTL_SER_EXTENT:
10835		return (ctl_extent_check(pending_io, ooa_io));
10836		break; /* NOTREACHED */
10837	case CTL_SER_PASS:
10838		return (CTL_ACTION_PASS);
10839		break; /* NOTREACHED */
10840	case CTL_SER_SKIP:
10841		return (CTL_ACTION_SKIP);
10842		break;
10843	default:
10844		panic("invalid serialization value %d",
10845		      serialize_row[pending_entry->seridx]);
10846		break; /* NOTREACHED */
10847	}
10848
10849	return (CTL_ACTION_ERROR);
10850}
10851
10852/*
10853 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10854 * Assumptions:
10855 * - pending_io is generally either incoming, or on the blocked queue
10856 * - starting I/O is the I/O we want to start the check with.
10857 */
10858static ctl_action
10859ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10860	      union ctl_io *starting_io)
10861{
10862	union ctl_io *ooa_io;
10863	ctl_action action;
10864
10865	mtx_assert(&lun->lun_lock, MA_OWNED);
10866
10867	/*
10868	 * Run back along the OOA queue, starting with the current
10869	 * blocked I/O and going through every I/O before it on the
10870	 * queue.  If starting_io is NULL, we'll just end up returning
10871	 * CTL_ACTION_PASS.
10872	 */
10873	for (ooa_io = starting_io; ooa_io != NULL;
10874	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10875	     ooa_links)){
10876
10877		/*
10878		 * This routine just checks to see whether
10879		 * cur_blocked is blocked by ooa_io, which is ahead
10880		 * of it in the queue.  It doesn't queue/dequeue
10881		 * cur_blocked.
10882		 */
10883		action = ctl_check_for_blockage(pending_io, ooa_io);
10884		switch (action) {
10885		case CTL_ACTION_BLOCK:
10886		case CTL_ACTION_OVERLAP:
10887		case CTL_ACTION_OVERLAP_TAG:
10888		case CTL_ACTION_SKIP:
10889		case CTL_ACTION_ERROR:
10890			return (action);
10891			break; /* NOTREACHED */
10892		case CTL_ACTION_PASS:
10893			break;
10894		default:
10895			panic("invalid action %d", action);
10896			break;  /* NOTREACHED */
10897		}
10898	}
10899
10900	return (CTL_ACTION_PASS);
10901}
10902
10903/*
10904 * Assumptions:
10905 * - An I/O has just completed, and has been removed from the per-LUN OOA
10906 *   queue, so some items on the blocked queue may now be unblocked.
10907 */
10908static int
10909ctl_check_blocked(struct ctl_lun *lun)
10910{
10911	union ctl_io *cur_blocked, *next_blocked;
10912
10913	mtx_assert(&lun->lun_lock, MA_OWNED);
10914
10915	/*
10916	 * Run forward from the head of the blocked queue, checking each
10917	 * entry against the I/Os prior to it on the OOA queue to see if
10918	 * there is still any blockage.
10919	 *
10920	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10921	 * with our removing a variable on it while it is traversing the
10922	 * list.
10923	 */
10924	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10925	     cur_blocked != NULL; cur_blocked = next_blocked) {
10926		union ctl_io *prev_ooa;
10927		ctl_action action;
10928
10929		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10930							  blocked_links);
10931
10932		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10933						      ctl_ooaq, ooa_links);
10934
10935		/*
10936		 * If cur_blocked happens to be the first item in the OOA
10937		 * queue now, prev_ooa will be NULL, and the action
10938		 * returned will just be CTL_ACTION_PASS.
10939		 */
10940		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10941
10942		switch (action) {
10943		case CTL_ACTION_BLOCK:
10944			/* Nothing to do here, still blocked */
10945			break;
10946		case CTL_ACTION_OVERLAP:
10947		case CTL_ACTION_OVERLAP_TAG:
10948			/*
10949			 * This shouldn't happen!  In theory we've already
10950			 * checked this command for overlap...
10951			 */
10952			break;
10953		case CTL_ACTION_PASS:
10954		case CTL_ACTION_SKIP: {
10955			struct ctl_softc *softc;
10956			const struct ctl_cmd_entry *entry;
10957			uint32_t initidx;
10958			int isc_retval;
10959
10960			/*
10961			 * The skip case shouldn't happen, this transaction
10962			 * should have never made it onto the blocked queue.
10963			 */
10964			/*
10965			 * This I/O is no longer blocked, we can remove it
10966			 * from the blocked queue.  Since this is a TAILQ
10967			 * (doubly linked list), we can do O(1) removals
10968			 * from any place on the list.
10969			 */
10970			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10971				     blocked_links);
10972			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10973
10974			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10975				/*
10976				 * Need to send IO back to original side to
10977				 * run
10978				 */
10979				union ctl_ha_msg msg_info;
10980
10981				msg_info.hdr.original_sc =
10982					cur_blocked->io_hdr.original_sc;
10983				msg_info.hdr.serializing_sc = cur_blocked;
10984				msg_info.hdr.msg_type = CTL_MSG_R2R;
10985				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10986				     &msg_info, sizeof(msg_info), 0)) >
10987				     CTL_HA_STATUS_SUCCESS) {
10988					printf("CTL:Check Blocked error from "
10989					       "ctl_ha_msg_send %d\n",
10990					       isc_retval);
10991				}
10992				break;
10993			}
10994			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10995			softc = control_softc;
10996
10997			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10998
10999			/*
11000			 * Check this I/O for LUN state changes that may
11001			 * have happened while this command was blocked.
11002			 * The LUN state may have been changed by a command
11003			 * ahead of us in the queue, so we need to re-check
11004			 * for any states that can be caused by SCSI
11005			 * commands.
11006			 */
11007			if (ctl_scsiio_lun_check(softc, lun, entry,
11008						 &cur_blocked->scsiio) == 0) {
11009				cur_blocked->io_hdr.flags |=
11010				                      CTL_FLAG_IS_WAS_ON_RTR;
11011				ctl_enqueue_rtr(cur_blocked);
11012			} else
11013				ctl_done(cur_blocked);
11014			break;
11015		}
11016		default:
11017			/*
11018			 * This probably shouldn't happen -- we shouldn't
11019			 * get CTL_ACTION_ERROR, or anything else.
11020			 */
11021			break;
11022		}
11023	}
11024
11025	return (CTL_RETVAL_COMPLETE);
11026}
11027
11028/*
11029 * This routine (with one exception) checks LUN flags that can be set by
11030 * commands ahead of us in the OOA queue.  These flags have to be checked
11031 * when a command initially comes in, and when we pull a command off the
11032 * blocked queue and are preparing to execute it.  The reason we have to
11033 * check these flags for commands on the blocked queue is that the LUN
11034 * state may have been changed by a command ahead of us while we're on the
11035 * blocked queue.
11036 *
11037 * Ordering is somewhat important with these checks, so please pay
11038 * careful attention to the placement of any new checks.
11039 */
11040static int
11041ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11042    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11043{
11044	int retval;
11045
11046	retval = 0;
11047
11048	mtx_assert(&lun->lun_lock, MA_OWNED);
11049
11050	/*
11051	 * If this shelf is a secondary shelf controller, we have to reject
11052	 * any media access commands.
11053	 */
11054#if 0
11055	/* No longer needed for HA */
11056	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11057	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11058		ctl_set_lun_standby(ctsio);
11059		retval = 1;
11060		goto bailout;
11061	}
11062#endif
11063
11064	/*
11065	 * Check for a reservation conflict.  If this command isn't allowed
11066	 * even on reserved LUNs, and if this initiator isn't the one who
11067	 * reserved us, reject the command with a reservation conflict.
11068	 */
11069	if ((lun->flags & CTL_LUN_RESERVED)
11070	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11071		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11072		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11073		 || (ctsio->io_hdr.nexus.targ_target.id !=
11074		     lun->rsv_nexus.targ_target.id)) {
11075			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11076			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11077			retval = 1;
11078			goto bailout;
11079		}
11080	}
11081
11082	if ( (lun->flags & CTL_LUN_PR_RESERVED)
11083	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11084		uint32_t residx;
11085
11086		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11087		/*
11088		 * if we aren't registered or it's a res holder type
11089		 * reservation and this isn't the res holder then set a
11090		 * conflict.
11091		 * NOTE: Commands which might be allowed on write exclusive
11092		 * type reservations are checked in the particular command
11093		 * for a conflict. Read and SSU are the only ones.
11094		 */
11095		if (!lun->per_res[residx].registered
11096		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11097			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11098			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11099			retval = 1;
11100			goto bailout;
11101		}
11102
11103	}
11104
11105	if ((lun->flags & CTL_LUN_OFFLINE)
11106	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11107		ctl_set_lun_not_ready(ctsio);
11108		retval = 1;
11109		goto bailout;
11110	}
11111
11112	/*
11113	 * If the LUN is stopped, see if this particular command is allowed
11114	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11115	 */
11116	if ((lun->flags & CTL_LUN_STOPPED)
11117	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11118		/* "Logical unit not ready, initializing cmd. required" */
11119		ctl_set_lun_stopped(ctsio);
11120		retval = 1;
11121		goto bailout;
11122	}
11123
11124	if ((lun->flags & CTL_LUN_INOPERABLE)
11125	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11126		/* "Medium format corrupted" */
11127		ctl_set_medium_format_corrupted(ctsio);
11128		retval = 1;
11129		goto bailout;
11130	}
11131
11132bailout:
11133	return (retval);
11134
11135}
11136
11137static void
11138ctl_failover_io(union ctl_io *io, int have_lock)
11139{
11140	ctl_set_busy(&io->scsiio);
11141	ctl_done(io);
11142}
11143
11144static void
11145ctl_failover(void)
11146{
11147	struct ctl_lun *lun;
11148	struct ctl_softc *ctl_softc;
11149	union ctl_io *next_io, *pending_io;
11150	union ctl_io *io;
11151	int lun_idx;
11152	int i;
11153
11154	ctl_softc = control_softc;
11155
11156	mtx_lock(&ctl_softc->ctl_lock);
11157	/*
11158	 * Remove any cmds from the other SC from the rtr queue.  These
11159	 * will obviously only be for LUNs for which we're the primary.
11160	 * We can't send status or get/send data for these commands.
11161	 * Since they haven't been executed yet, we can just remove them.
11162	 * We'll either abort them or delete them below, depending on
11163	 * which HA mode we're in.
11164	 */
11165#ifdef notyet
11166	mtx_lock(&ctl_softc->queue_lock);
11167	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11168	     io != NULL; io = next_io) {
11169		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11170		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11171			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11172				      ctl_io_hdr, links);
11173	}
11174	mtx_unlock(&ctl_softc->queue_lock);
11175#endif
11176
11177	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11178		lun = ctl_softc->ctl_luns[lun_idx];
11179		if (lun==NULL)
11180			continue;
11181
11182		/*
11183		 * Processor LUNs are primary on both sides.
11184		 * XXX will this always be true?
11185		 */
11186		if (lun->be_lun->lun_type == T_PROCESSOR)
11187			continue;
11188
11189		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11190		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11191			printf("FAILOVER: primary lun %d\n", lun_idx);
11192		        /*
11193			 * Remove all commands from the other SC. First from the
11194			 * blocked queue then from the ooa queue. Once we have
11195			 * removed them. Call ctl_check_blocked to see if there
11196			 * is anything that can run.
11197			 */
11198			for (io = (union ctl_io *)TAILQ_FIRST(
11199			     &lun->blocked_queue); io != NULL; io = next_io) {
11200
11201		        	next_io = (union ctl_io *)TAILQ_NEXT(
11202				    &io->io_hdr, blocked_links);
11203
11204				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11205					TAILQ_REMOVE(&lun->blocked_queue,
11206						     &io->io_hdr,blocked_links);
11207					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11208					TAILQ_REMOVE(&lun->ooa_queue,
11209						     &io->io_hdr, ooa_links);
11210
11211					ctl_free_io(io);
11212				}
11213			}
11214
11215			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11216	     		     io != NULL; io = next_io) {
11217
11218		        	next_io = (union ctl_io *)TAILQ_NEXT(
11219				    &io->io_hdr, ooa_links);
11220
11221				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11222
11223					TAILQ_REMOVE(&lun->ooa_queue,
11224						&io->io_hdr,
11225					     	ooa_links);
11226
11227					ctl_free_io(io);
11228				}
11229			}
11230			ctl_check_blocked(lun);
11231		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11232			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11233
11234			printf("FAILOVER: primary lun %d\n", lun_idx);
11235			/*
11236			 * Abort all commands from the other SC.  We can't
11237			 * send status back for them now.  These should get
11238			 * cleaned up when they are completed or come out
11239			 * for a datamove operation.
11240			 */
11241			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11242	     		     io != NULL; io = next_io) {
11243		        	next_io = (union ctl_io *)TAILQ_NEXT(
11244					&io->io_hdr, ooa_links);
11245
11246				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11247					io->io_hdr.flags |= CTL_FLAG_ABORT;
11248			}
11249		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11250			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11251
11252			printf("FAILOVER: secondary lun %d\n", lun_idx);
11253
11254			lun->flags |= CTL_LUN_PRIMARY_SC;
11255
11256			/*
11257			 * We send all I/O that was sent to this controller
11258			 * and redirected to the other side back with
11259			 * busy status, and have the initiator retry it.
11260			 * Figuring out how much data has been transferred,
11261			 * etc. and picking up where we left off would be
11262			 * very tricky.
11263			 *
11264			 * XXX KDM need to remove I/O from the blocked
11265			 * queue as well!
11266			 */
11267			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11268			     &lun->ooa_queue); pending_io != NULL;
11269			     pending_io = next_io) {
11270
11271				next_io =  (union ctl_io *)TAILQ_NEXT(
11272					&pending_io->io_hdr, ooa_links);
11273
11274				pending_io->io_hdr.flags &=
11275					~CTL_FLAG_SENT_2OTHER_SC;
11276
11277				if (pending_io->io_hdr.flags &
11278				    CTL_FLAG_IO_ACTIVE) {
11279					pending_io->io_hdr.flags |=
11280						CTL_FLAG_FAILOVER;
11281				} else {
11282					ctl_set_busy(&pending_io->scsiio);
11283					ctl_done(pending_io);
11284				}
11285			}
11286
11287			/*
11288			 * Build Unit Attention
11289			 */
11290			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11291				lun->pending_ua[i] |=
11292				                     CTL_UA_ASYM_ACC_CHANGE;
11293			}
11294		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11295			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11296			printf("FAILOVER: secondary lun %d\n", lun_idx);
11297			/*
11298			 * if the first io on the OOA is not on the RtR queue
11299			 * add it.
11300			 */
11301			lun->flags |= CTL_LUN_PRIMARY_SC;
11302
11303			pending_io = (union ctl_io *)TAILQ_FIRST(
11304			    &lun->ooa_queue);
11305			if (pending_io==NULL) {
11306				printf("Nothing on OOA queue\n");
11307				continue;
11308			}
11309
11310			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11311			if ((pending_io->io_hdr.flags &
11312			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11313				pending_io->io_hdr.flags |=
11314				    CTL_FLAG_IS_WAS_ON_RTR;
11315				ctl_enqueue_rtr(pending_io);
11316			}
11317#if 0
11318			else
11319			{
11320				printf("Tag 0x%04x is running\n",
11321				      pending_io->scsiio.tag_num);
11322			}
11323#endif
11324
11325			next_io = (union ctl_io *)TAILQ_NEXT(
11326			    &pending_io->io_hdr, ooa_links);
11327			for (pending_io=next_io; pending_io != NULL;
11328			     pending_io = next_io) {
11329				pending_io->io_hdr.flags &=
11330				    ~CTL_FLAG_SENT_2OTHER_SC;
11331				next_io = (union ctl_io *)TAILQ_NEXT(
11332					&pending_io->io_hdr, ooa_links);
11333				if (pending_io->io_hdr.flags &
11334				    CTL_FLAG_IS_WAS_ON_RTR) {
11335#if 0
11336				        printf("Tag 0x%04x is running\n",
11337				      		pending_io->scsiio.tag_num);
11338#endif
11339					continue;
11340				}
11341
11342				switch (ctl_check_ooa(lun, pending_io,
11343			            (union ctl_io *)TAILQ_PREV(
11344				    &pending_io->io_hdr, ctl_ooaq,
11345				    ooa_links))) {
11346
11347				case CTL_ACTION_BLOCK:
11348					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11349							  &pending_io->io_hdr,
11350							  blocked_links);
11351					pending_io->io_hdr.flags |=
11352					    CTL_FLAG_BLOCKED;
11353					break;
11354				case CTL_ACTION_PASS:
11355				case CTL_ACTION_SKIP:
11356					pending_io->io_hdr.flags |=
11357					    CTL_FLAG_IS_WAS_ON_RTR;
11358					ctl_enqueue_rtr(pending_io);
11359					break;
11360				case CTL_ACTION_OVERLAP:
11361					ctl_set_overlapped_cmd(
11362					    (struct ctl_scsiio *)pending_io);
11363					ctl_done(pending_io);
11364					break;
11365				case CTL_ACTION_OVERLAP_TAG:
11366					ctl_set_overlapped_tag(
11367					    (struct ctl_scsiio *)pending_io,
11368					    pending_io->scsiio.tag_num & 0xff);
11369					ctl_done(pending_io);
11370					break;
11371				case CTL_ACTION_ERROR:
11372				default:
11373					ctl_set_internal_failure(
11374						(struct ctl_scsiio *)pending_io,
11375						0,  // sks_valid
11376						0); //retry count
11377					ctl_done(pending_io);
11378					break;
11379				}
11380			}
11381
11382			/*
11383			 * Build Unit Attention
11384			 */
11385			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11386				lun->pending_ua[i] |=
11387				                     CTL_UA_ASYM_ACC_CHANGE;
11388			}
11389		} else {
11390			panic("Unhandled HA mode failover, LUN flags = %#x, "
11391			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11392		}
11393	}
11394	ctl_pause_rtr = 0;
11395	mtx_unlock(&ctl_softc->ctl_lock);
11396}
11397
11398static int
11399ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11400{
11401	struct ctl_lun *lun;
11402	const struct ctl_cmd_entry *entry;
11403	uint32_t initidx, targ_lun;
11404	int retval;
11405
11406	retval = 0;
11407
11408	lun = NULL;
11409
11410	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11411	if ((targ_lun < CTL_MAX_LUNS)
11412	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11413		lun = ctl_softc->ctl_luns[targ_lun];
11414		/*
11415		 * If the LUN is invalid, pretend that it doesn't exist.
11416		 * It will go away as soon as all pending I/O has been
11417		 * completed.
11418		 */
11419		if (lun->flags & CTL_LUN_DISABLED) {
11420			lun = NULL;
11421		} else {
11422			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11423			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11424				lun->be_lun;
11425			if (lun->be_lun->lun_type == T_PROCESSOR) {
11426				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11427			}
11428
11429			/*
11430			 * Every I/O goes into the OOA queue for a
11431			 * particular LUN, and stays there until completion.
11432			 */
11433			mtx_lock(&lun->lun_lock);
11434			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11435			    ooa_links);
11436		}
11437	} else {
11438		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11439		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11440	}
11441
11442	/* Get command entry and return error if it is unsuppotyed. */
11443	entry = ctl_validate_command(ctsio);
11444	if (entry == NULL) {
11445		if (lun)
11446			mtx_unlock(&lun->lun_lock);
11447		return (retval);
11448	}
11449
11450	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11451	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11452
11453	/*
11454	 * Check to see whether we can send this command to LUNs that don't
11455	 * exist.  This should pretty much only be the case for inquiry
11456	 * and request sense.  Further checks, below, really require having
11457	 * a LUN, so we can't really check the command anymore.  Just put
11458	 * it on the rtr queue.
11459	 */
11460	if (lun == NULL) {
11461		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11462			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11463			ctl_enqueue_rtr((union ctl_io *)ctsio);
11464			return (retval);
11465		}
11466
11467		ctl_set_unsupported_lun(ctsio);
11468		ctl_done((union ctl_io *)ctsio);
11469		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11470		return (retval);
11471	} else {
11472		/*
11473		 * Make sure we support this particular command on this LUN.
11474		 * e.g., we don't support writes to the control LUN.
11475		 */
11476		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11477			mtx_unlock(&lun->lun_lock);
11478			ctl_set_invalid_opcode(ctsio);
11479			ctl_done((union ctl_io *)ctsio);
11480			return (retval);
11481		}
11482	}
11483
11484	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11485
11486#ifdef CTL_WITH_CA
11487	/*
11488	 * If we've got a request sense, it'll clear the contingent
11489	 * allegiance condition.  Otherwise, if we have a CA condition for
11490	 * this initiator, clear it, because it sent down a command other
11491	 * than request sense.
11492	 */
11493	if ((ctsio->cdb[0] != REQUEST_SENSE)
11494	 && (ctl_is_set(lun->have_ca, initidx)))
11495		ctl_clear_mask(lun->have_ca, initidx);
11496#endif
11497
11498	/*
11499	 * If the command has this flag set, it handles its own unit
11500	 * attention reporting, we shouldn't do anything.  Otherwise we
11501	 * check for any pending unit attentions, and send them back to the
11502	 * initiator.  We only do this when a command initially comes in,
11503	 * not when we pull it off the blocked queue.
11504	 *
11505	 * According to SAM-3, section 5.3.2, the order that things get
11506	 * presented back to the host is basically unit attentions caused
11507	 * by some sort of reset event, busy status, reservation conflicts
11508	 * or task set full, and finally any other status.
11509	 *
11510	 * One issue here is that some of the unit attentions we report
11511	 * don't fall into the "reset" category (e.g. "reported luns data
11512	 * has changed").  So reporting it here, before the reservation
11513	 * check, may be technically wrong.  I guess the only thing to do
11514	 * would be to check for and report the reset events here, and then
11515	 * check for the other unit attention types after we check for a
11516	 * reservation conflict.
11517	 *
11518	 * XXX KDM need to fix this
11519	 */
11520	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11521		ctl_ua_type ua_type;
11522
11523		ua_type = lun->pending_ua[initidx];
11524		if (ua_type != CTL_UA_NONE) {
11525			scsi_sense_data_type sense_format;
11526
11527			if (lun != NULL)
11528				sense_format = (lun->flags &
11529				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11530				    SSD_TYPE_FIXED;
11531			else
11532				sense_format = SSD_TYPE_FIXED;
11533
11534			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11535					       sense_format);
11536			if (ua_type != CTL_UA_NONE) {
11537				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11538				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11539						       CTL_AUTOSENSE;
11540				ctsio->sense_len = SSD_FULL_SIZE;
11541				lun->pending_ua[initidx] &= ~ua_type;
11542				mtx_unlock(&lun->lun_lock);
11543				ctl_done((union ctl_io *)ctsio);
11544				return (retval);
11545			}
11546		}
11547	}
11548
11549
11550	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11551		mtx_unlock(&lun->lun_lock);
11552		ctl_done((union ctl_io *)ctsio);
11553		return (retval);
11554	}
11555
11556	/*
11557	 * XXX CHD this is where we want to send IO to other side if
11558	 * this LUN is secondary on this SC. We will need to make a copy
11559	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11560	 * the copy we send as FROM_OTHER.
11561	 * We also need to stuff the address of the original IO so we can
11562	 * find it easily. Something similar will need be done on the other
11563	 * side so when we are done we can find the copy.
11564	 */
11565	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11566		union ctl_ha_msg msg_info;
11567		int isc_retval;
11568
11569		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11570
11571		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11572		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11573#if 0
11574		printf("1. ctsio %p\n", ctsio);
11575#endif
11576		msg_info.hdr.serializing_sc = NULL;
11577		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11578		msg_info.scsi.tag_num = ctsio->tag_num;
11579		msg_info.scsi.tag_type = ctsio->tag_type;
11580		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11581
11582		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11583
11584		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11585		    (void *)&msg_info, sizeof(msg_info), 0)) >
11586		    CTL_HA_STATUS_SUCCESS) {
11587			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11588			       isc_retval);
11589			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11590		} else {
11591#if 0
11592			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11593#endif
11594		}
11595
11596		/*
11597		 * XXX KDM this I/O is off the incoming queue, but hasn't
11598		 * been inserted on any other queue.  We may need to come
11599		 * up with a holding queue while we wait for serialization
11600		 * so that we have an idea of what we're waiting for from
11601		 * the other side.
11602		 */
11603		mtx_unlock(&lun->lun_lock);
11604		return (retval);
11605	}
11606
11607	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11608			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11609			      ctl_ooaq, ooa_links))) {
11610	case CTL_ACTION_BLOCK:
11611		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11612		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11613				  blocked_links);
11614		mtx_unlock(&lun->lun_lock);
11615		return (retval);
11616	case CTL_ACTION_PASS:
11617	case CTL_ACTION_SKIP:
11618		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11619		mtx_unlock(&lun->lun_lock);
11620		ctl_enqueue_rtr((union ctl_io *)ctsio);
11621		break;
11622	case CTL_ACTION_OVERLAP:
11623		mtx_unlock(&lun->lun_lock);
11624		ctl_set_overlapped_cmd(ctsio);
11625		ctl_done((union ctl_io *)ctsio);
11626		break;
11627	case CTL_ACTION_OVERLAP_TAG:
11628		mtx_unlock(&lun->lun_lock);
11629		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11630		ctl_done((union ctl_io *)ctsio);
11631		break;
11632	case CTL_ACTION_ERROR:
11633	default:
11634		mtx_unlock(&lun->lun_lock);
11635		ctl_set_internal_failure(ctsio,
11636					 /*sks_valid*/ 0,
11637					 /*retry_count*/ 0);
11638		ctl_done((union ctl_io *)ctsio);
11639		break;
11640	}
11641	return (retval);
11642}
11643
11644const struct ctl_cmd_entry *
11645ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11646{
11647	const struct ctl_cmd_entry *entry;
11648	int service_action;
11649
11650	entry = &ctl_cmd_table[ctsio->cdb[0]];
11651	if (entry->flags & CTL_CMD_FLAG_SA5) {
11652		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11653		entry = &((const struct ctl_cmd_entry *)
11654		    entry->execute)[service_action];
11655	}
11656	return (entry);
11657}
11658
11659const struct ctl_cmd_entry *
11660ctl_validate_command(struct ctl_scsiio *ctsio)
11661{
11662	const struct ctl_cmd_entry *entry;
11663	int i;
11664	uint8_t diff;
11665
11666	entry = ctl_get_cmd_entry(ctsio);
11667	if (entry->execute == NULL) {
11668		ctl_set_invalid_opcode(ctsio);
11669		ctl_done((union ctl_io *)ctsio);
11670		return (NULL);
11671	}
11672	KASSERT(entry->length > 0,
11673	    ("Not defined length for command 0x%02x/0x%02x",
11674	     ctsio->cdb[0], ctsio->cdb[1]));
11675	for (i = 1; i < entry->length; i++) {
11676		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11677		if (diff == 0)
11678			continue;
11679		ctl_set_invalid_field(ctsio,
11680				      /*sks_valid*/ 1,
11681				      /*command*/ 1,
11682				      /*field*/ i,
11683				      /*bit_valid*/ 1,
11684				      /*bit*/ fls(diff) - 1);
11685		ctl_done((union ctl_io *)ctsio);
11686		return (NULL);
11687	}
11688	return (entry);
11689}
11690
11691static int
11692ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11693{
11694
11695	switch (lun_type) {
11696	case T_PROCESSOR:
11697		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11698		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11699			return (0);
11700		break;
11701	case T_DIRECT:
11702		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11703		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11704			return (0);
11705		break;
11706	default:
11707		return (0);
11708	}
11709	return (1);
11710}
11711
11712static int
11713ctl_scsiio(struct ctl_scsiio *ctsio)
11714{
11715	int retval;
11716	const struct ctl_cmd_entry *entry;
11717
11718	retval = CTL_RETVAL_COMPLETE;
11719
11720	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11721
11722	entry = ctl_get_cmd_entry(ctsio);
11723
11724	/*
11725	 * If this I/O has been aborted, just send it straight to
11726	 * ctl_done() without executing it.
11727	 */
11728	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11729		ctl_done((union ctl_io *)ctsio);
11730		goto bailout;
11731	}
11732
11733	/*
11734	 * All the checks should have been handled by ctl_scsiio_precheck().
11735	 * We should be clear now to just execute the I/O.
11736	 */
11737	retval = entry->execute(ctsio);
11738
11739bailout:
11740	return (retval);
11741}
11742
11743/*
11744 * Since we only implement one target right now, a bus reset simply resets
11745 * our single target.
11746 */
11747static int
11748ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11749{
11750	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11751}
11752
11753static int
11754ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11755		 ctl_ua_type ua_type)
11756{
11757	struct ctl_lun *lun;
11758	int retval;
11759
11760	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11761		union ctl_ha_msg msg_info;
11762
11763		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11764		msg_info.hdr.nexus = io->io_hdr.nexus;
11765		if (ua_type==CTL_UA_TARG_RESET)
11766			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11767		else
11768			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11769		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11770		msg_info.hdr.original_sc = NULL;
11771		msg_info.hdr.serializing_sc = NULL;
11772		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11773		    (void *)&msg_info, sizeof(msg_info), 0)) {
11774		}
11775	}
11776	retval = 0;
11777
11778	mtx_lock(&ctl_softc->ctl_lock);
11779	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11780		retval += ctl_lun_reset(lun, io, ua_type);
11781	mtx_unlock(&ctl_softc->ctl_lock);
11782
11783	return (retval);
11784}
11785
11786/*
11787 * The LUN should always be set.  The I/O is optional, and is used to
11788 * distinguish between I/Os sent by this initiator, and by other
11789 * initiators.  We set unit attention for initiators other than this one.
11790 * SAM-3 is vague on this point.  It does say that a unit attention should
11791 * be established for other initiators when a LUN is reset (see section
11792 * 5.7.3), but it doesn't specifically say that the unit attention should
11793 * be established for this particular initiator when a LUN is reset.  Here
11794 * is the relevant text, from SAM-3 rev 8:
11795 *
11796 * 5.7.2 When a SCSI initiator port aborts its own tasks
11797 *
11798 * When a SCSI initiator port causes its own task(s) to be aborted, no
11799 * notification that the task(s) have been aborted shall be returned to
11800 * the SCSI initiator port other than the completion response for the
11801 * command or task management function action that caused the task(s) to
11802 * be aborted and notification(s) associated with related effects of the
11803 * action (e.g., a reset unit attention condition).
11804 *
11805 * XXX KDM for now, we're setting unit attention for all initiators.
11806 */
11807static int
11808ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11809{
11810	union ctl_io *xio;
11811#if 0
11812	uint32_t initindex;
11813#endif
11814	int i;
11815
11816	mtx_lock(&lun->lun_lock);
11817	/*
11818	 * Run through the OOA queue and abort each I/O.
11819	 */
11820#if 0
11821	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11822#endif
11823	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11824	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11825		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11826	}
11827
11828	/*
11829	 * This version sets unit attention for every
11830	 */
11831#if 0
11832	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11833	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11834		if (initindex == i)
11835			continue;
11836		lun->pending_ua[i] |= ua_type;
11837	}
11838#endif
11839
11840	/*
11841	 * A reset (any kind, really) clears reservations established with
11842	 * RESERVE/RELEASE.  It does not clear reservations established
11843	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11844	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11845	 * reservations made with the RESERVE/RELEASE commands, because
11846	 * those commands are obsolete in SPC-3.
11847	 */
11848	lun->flags &= ~CTL_LUN_RESERVED;
11849
11850	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11851#ifdef CTL_WITH_CA
11852		ctl_clear_mask(lun->have_ca, i);
11853#endif
11854		lun->pending_ua[i] |= ua_type;
11855	}
11856	mtx_unlock(&lun->lun_lock);
11857
11858	return (0);
11859}
11860
11861static int
11862ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11863    int other_sc)
11864{
11865	union ctl_io *xio;
11866	int found;
11867
11868	mtx_assert(&lun->lun_lock, MA_OWNED);
11869
11870	/*
11871	 * Run through the OOA queue and attempt to find the given I/O.
11872	 * The target port, initiator ID, tag type and tag number have to
11873	 * match the values that we got from the initiator.  If we have an
11874	 * untagged command to abort, simply abort the first untagged command
11875	 * we come to.  We only allow one untagged command at a time of course.
11876	 */
11877	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11878	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11879
11880		if ((targ_port == UINT32_MAX ||
11881		     targ_port == xio->io_hdr.nexus.targ_port) &&
11882		    (init_id == UINT32_MAX ||
11883		     init_id == xio->io_hdr.nexus.initid.id)) {
11884			if (targ_port != xio->io_hdr.nexus.targ_port ||
11885			    init_id != xio->io_hdr.nexus.initid.id)
11886				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11887			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11888			found = 1;
11889			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11890				union ctl_ha_msg msg_info;
11891
11892				msg_info.hdr.nexus = xio->io_hdr.nexus;
11893				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11894				msg_info.task.tag_num = xio->scsiio.tag_num;
11895				msg_info.task.tag_type = xio->scsiio.tag_type;
11896				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11897				msg_info.hdr.original_sc = NULL;
11898				msg_info.hdr.serializing_sc = NULL;
11899				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11900				    (void *)&msg_info, sizeof(msg_info), 0);
11901			}
11902		}
11903	}
11904	return (found);
11905}
11906
11907static int
11908ctl_abort_task_set(union ctl_io *io)
11909{
11910	struct ctl_softc *softc = control_softc;
11911	struct ctl_lun *lun;
11912	uint32_t targ_lun;
11913
11914	/*
11915	 * Look up the LUN.
11916	 */
11917	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11918	mtx_lock(&softc->ctl_lock);
11919	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11920		lun = softc->ctl_luns[targ_lun];
11921	else {
11922		mtx_unlock(&softc->ctl_lock);
11923		return (1);
11924	}
11925
11926	mtx_lock(&lun->lun_lock);
11927	mtx_unlock(&softc->ctl_lock);
11928	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11929		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11930		    io->io_hdr.nexus.initid.id,
11931		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11932	} else { /* CTL_TASK_CLEAR_TASK_SET */
11933		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11934		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11935	}
11936	mtx_unlock(&lun->lun_lock);
11937	return (0);
11938}
11939
11940static int
11941ctl_i_t_nexus_reset(union ctl_io *io)
11942{
11943	struct ctl_softc *softc = control_softc;
11944	struct ctl_lun *lun;
11945	uint32_t initindex;
11946
11947	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11948	mtx_lock(&softc->ctl_lock);
11949	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11950		mtx_lock(&lun->lun_lock);
11951		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11952		    io->io_hdr.nexus.initid.id,
11953		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11954#ifdef CTL_WITH_CA
11955		ctl_clear_mask(lun->have_ca, initindex);
11956#endif
11957		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
11958		mtx_unlock(&lun->lun_lock);
11959	}
11960	mtx_unlock(&softc->ctl_lock);
11961	return (0);
11962}
11963
11964static int
11965ctl_abort_task(union ctl_io *io)
11966{
11967	union ctl_io *xio;
11968	struct ctl_lun *lun;
11969	struct ctl_softc *ctl_softc;
11970#if 0
11971	struct sbuf sb;
11972	char printbuf[128];
11973#endif
11974	int found;
11975	uint32_t targ_lun;
11976
11977	ctl_softc = control_softc;
11978	found = 0;
11979
11980	/*
11981	 * Look up the LUN.
11982	 */
11983	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11984	mtx_lock(&ctl_softc->ctl_lock);
11985	if ((targ_lun < CTL_MAX_LUNS)
11986	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11987		lun = ctl_softc->ctl_luns[targ_lun];
11988	else {
11989		mtx_unlock(&ctl_softc->ctl_lock);
11990		return (1);
11991	}
11992
11993#if 0
11994	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11995	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11996#endif
11997
11998	mtx_lock(&lun->lun_lock);
11999	mtx_unlock(&ctl_softc->ctl_lock);
12000	/*
12001	 * Run through the OOA queue and attempt to find the given I/O.
12002	 * The target port, initiator ID, tag type and tag number have to
12003	 * match the values that we got from the initiator.  If we have an
12004	 * untagged command to abort, simply abort the first untagged command
12005	 * we come to.  We only allow one untagged command at a time of course.
12006	 */
12007#if 0
12008	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12009#endif
12010	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12011	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12012#if 0
12013		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12014
12015		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12016			    lun->lun, xio->scsiio.tag_num,
12017			    xio->scsiio.tag_type,
12018			    (xio->io_hdr.blocked_links.tqe_prev
12019			    == NULL) ? "" : " BLOCKED",
12020			    (xio->io_hdr.flags &
12021			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12022			    (xio->io_hdr.flags &
12023			    CTL_FLAG_ABORT) ? " ABORT" : "",
12024			    (xio->io_hdr.flags &
12025			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12026		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12027		sbuf_finish(&sb);
12028		printf("%s\n", sbuf_data(&sb));
12029#endif
12030
12031		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12032		 && (xio->io_hdr.nexus.initid.id ==
12033		     io->io_hdr.nexus.initid.id)) {
12034			/*
12035			 * If the abort says that the task is untagged, the
12036			 * task in the queue must be untagged.  Otherwise,
12037			 * we just check to see whether the tag numbers
12038			 * match.  This is because the QLogic firmware
12039			 * doesn't pass back the tag type in an abort
12040			 * request.
12041			 */
12042#if 0
12043			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12044			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12045			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12046#endif
12047			/*
12048			 * XXX KDM we've got problems with FC, because it
12049			 * doesn't send down a tag type with aborts.  So we
12050			 * can only really go by the tag number...
12051			 * This may cause problems with parallel SCSI.
12052			 * Need to figure that out!!
12053			 */
12054			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12055				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12056				found = 1;
12057				if ((io->io_hdr.flags &
12058				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12059				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12060					union ctl_ha_msg msg_info;
12061
12062					io->io_hdr.flags |=
12063					                CTL_FLAG_SENT_2OTHER_SC;
12064					msg_info.hdr.nexus = io->io_hdr.nexus;
12065					msg_info.task.task_action =
12066						CTL_TASK_ABORT_TASK;
12067					msg_info.task.tag_num =
12068						io->taskio.tag_num;
12069					msg_info.task.tag_type =
12070						io->taskio.tag_type;
12071					msg_info.hdr.msg_type =
12072						CTL_MSG_MANAGE_TASKS;
12073					msg_info.hdr.original_sc = NULL;
12074					msg_info.hdr.serializing_sc = NULL;
12075#if 0
12076					printf("Sent Abort to other side\n");
12077#endif
12078					if (CTL_HA_STATUS_SUCCESS !=
12079					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12080		    				(void *)&msg_info,
12081						sizeof(msg_info), 0)) {
12082					}
12083				}
12084#if 0
12085				printf("ctl_abort_task: found I/O to abort\n");
12086#endif
12087				break;
12088			}
12089		}
12090	}
12091	mtx_unlock(&lun->lun_lock);
12092
12093	if (found == 0) {
12094		/*
12095		 * This isn't really an error.  It's entirely possible for
12096		 * the abort and command completion to cross on the wire.
12097		 * This is more of an informative/diagnostic error.
12098		 */
12099#if 0
12100		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12101		       "%d:%d:%d:%d tag %d type %d\n",
12102		       io->io_hdr.nexus.initid.id,
12103		       io->io_hdr.nexus.targ_port,
12104		       io->io_hdr.nexus.targ_target.id,
12105		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12106		       io->taskio.tag_type);
12107#endif
12108	}
12109	return (0);
12110}
12111
12112static void
12113ctl_run_task(union ctl_io *io)
12114{
12115	struct ctl_softc *ctl_softc = control_softc;
12116	int retval = 1;
12117	const char *task_desc;
12118
12119	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12120
12121	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12122	    ("ctl_run_task: Unextected io_type %d\n",
12123	     io->io_hdr.io_type));
12124
12125	task_desc = ctl_scsi_task_string(&io->taskio);
12126	if (task_desc != NULL) {
12127#ifdef NEEDTOPORT
12128		csevent_log(CSC_CTL | CSC_SHELF_SW |
12129			    CTL_TASK_REPORT,
12130			    csevent_LogType_Trace,
12131			    csevent_Severity_Information,
12132			    csevent_AlertLevel_Green,
12133			    csevent_FRU_Firmware,
12134			    csevent_FRU_Unknown,
12135			    "CTL: received task: %s",task_desc);
12136#endif
12137	} else {
12138#ifdef NEEDTOPORT
12139		csevent_log(CSC_CTL | CSC_SHELF_SW |
12140			    CTL_TASK_REPORT,
12141			    csevent_LogType_Trace,
12142			    csevent_Severity_Information,
12143			    csevent_AlertLevel_Green,
12144			    csevent_FRU_Firmware,
12145			    csevent_FRU_Unknown,
12146			    "CTL: received unknown task "
12147			    "type: %d (%#x)",
12148			    io->taskio.task_action,
12149			    io->taskio.task_action);
12150#endif
12151	}
12152	switch (io->taskio.task_action) {
12153	case CTL_TASK_ABORT_TASK:
12154		retval = ctl_abort_task(io);
12155		break;
12156	case CTL_TASK_ABORT_TASK_SET:
12157	case CTL_TASK_CLEAR_TASK_SET:
12158		retval = ctl_abort_task_set(io);
12159		break;
12160	case CTL_TASK_CLEAR_ACA:
12161		break;
12162	case CTL_TASK_I_T_NEXUS_RESET:
12163		retval = ctl_i_t_nexus_reset(io);
12164		break;
12165	case CTL_TASK_LUN_RESET: {
12166		struct ctl_lun *lun;
12167		uint32_t targ_lun;
12168
12169		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12170		mtx_lock(&ctl_softc->ctl_lock);
12171		if ((targ_lun < CTL_MAX_LUNS)
12172		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12173			lun = ctl_softc->ctl_luns[targ_lun];
12174		else {
12175			mtx_unlock(&ctl_softc->ctl_lock);
12176			retval = 1;
12177			break;
12178		}
12179
12180		if (!(io->io_hdr.flags &
12181		    CTL_FLAG_FROM_OTHER_SC)) {
12182			union ctl_ha_msg msg_info;
12183
12184			io->io_hdr.flags |=
12185				CTL_FLAG_SENT_2OTHER_SC;
12186			msg_info.hdr.msg_type =
12187				CTL_MSG_MANAGE_TASKS;
12188			msg_info.hdr.nexus = io->io_hdr.nexus;
12189			msg_info.task.task_action =
12190				CTL_TASK_LUN_RESET;
12191			msg_info.hdr.original_sc = NULL;
12192			msg_info.hdr.serializing_sc = NULL;
12193			if (CTL_HA_STATUS_SUCCESS !=
12194			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12195			    (void *)&msg_info,
12196			    sizeof(msg_info), 0)) {
12197			}
12198		}
12199
12200		retval = ctl_lun_reset(lun, io,
12201				       CTL_UA_LUN_RESET);
12202		mtx_unlock(&ctl_softc->ctl_lock);
12203		break;
12204	}
12205	case CTL_TASK_TARGET_RESET:
12206		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12207		break;
12208	case CTL_TASK_BUS_RESET:
12209		retval = ctl_bus_reset(ctl_softc, io);
12210		break;
12211	case CTL_TASK_PORT_LOGIN:
12212		break;
12213	case CTL_TASK_PORT_LOGOUT:
12214		break;
12215	default:
12216		printf("ctl_run_task: got unknown task management event %d\n",
12217		       io->taskio.task_action);
12218		break;
12219	}
12220	if (retval == 0)
12221		io->io_hdr.status = CTL_SUCCESS;
12222	else
12223		io->io_hdr.status = CTL_ERROR;
12224	ctl_done(io);
12225}
12226
12227/*
12228 * For HA operation.  Handle commands that come in from the other
12229 * controller.
12230 */
12231static void
12232ctl_handle_isc(union ctl_io *io)
12233{
12234	int free_io;
12235	struct ctl_lun *lun;
12236	struct ctl_softc *ctl_softc;
12237	uint32_t targ_lun;
12238
12239	ctl_softc = control_softc;
12240
12241	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12242	lun = ctl_softc->ctl_luns[targ_lun];
12243
12244	switch (io->io_hdr.msg_type) {
12245	case CTL_MSG_SERIALIZE:
12246		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12247		break;
12248	case CTL_MSG_R2R: {
12249		const struct ctl_cmd_entry *entry;
12250
12251		/*
12252		 * This is only used in SER_ONLY mode.
12253		 */
12254		free_io = 0;
12255		entry = ctl_get_cmd_entry(&io->scsiio);
12256		mtx_lock(&lun->lun_lock);
12257		if (ctl_scsiio_lun_check(ctl_softc, lun,
12258		    entry, (struct ctl_scsiio *)io) != 0) {
12259			mtx_unlock(&lun->lun_lock);
12260			ctl_done(io);
12261			break;
12262		}
12263		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12264		mtx_unlock(&lun->lun_lock);
12265		ctl_enqueue_rtr(io);
12266		break;
12267	}
12268	case CTL_MSG_FINISH_IO:
12269		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12270			free_io = 0;
12271			ctl_done(io);
12272		} else {
12273			free_io = 1;
12274			mtx_lock(&lun->lun_lock);
12275			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12276				     ooa_links);
12277			ctl_check_blocked(lun);
12278			mtx_unlock(&lun->lun_lock);
12279		}
12280		break;
12281	case CTL_MSG_PERS_ACTION:
12282		ctl_hndl_per_res_out_on_other_sc(
12283			(union ctl_ha_msg *)&io->presio.pr_msg);
12284		free_io = 1;
12285		break;
12286	case CTL_MSG_BAD_JUJU:
12287		free_io = 0;
12288		ctl_done(io);
12289		break;
12290	case CTL_MSG_DATAMOVE:
12291		/* Only used in XFER mode */
12292		free_io = 0;
12293		ctl_datamove_remote(io);
12294		break;
12295	case CTL_MSG_DATAMOVE_DONE:
12296		/* Only used in XFER mode */
12297		free_io = 0;
12298		io->scsiio.be_move_done(io);
12299		break;
12300	default:
12301		free_io = 1;
12302		printf("%s: Invalid message type %d\n",
12303		       __func__, io->io_hdr.msg_type);
12304		break;
12305	}
12306	if (free_io)
12307		ctl_free_io(io);
12308
12309}
12310
12311
12312/*
12313 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12314 * there is no match.
12315 */
12316static ctl_lun_error_pattern
12317ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12318{
12319	const struct ctl_cmd_entry *entry;
12320	ctl_lun_error_pattern filtered_pattern, pattern;
12321
12322	pattern = desc->error_pattern;
12323
12324	/*
12325	 * XXX KDM we need more data passed into this function to match a
12326	 * custom pattern, and we actually need to implement custom pattern
12327	 * matching.
12328	 */
12329	if (pattern & CTL_LUN_PAT_CMD)
12330		return (CTL_LUN_PAT_CMD);
12331
12332	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12333		return (CTL_LUN_PAT_ANY);
12334
12335	entry = ctl_get_cmd_entry(ctsio);
12336
12337	filtered_pattern = entry->pattern & pattern;
12338
12339	/*
12340	 * If the user requested specific flags in the pattern (e.g.
12341	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12342	 * flags.
12343	 *
12344	 * If the user did not specify any flags, it doesn't matter whether
12345	 * or not the command supports the flags.
12346	 */
12347	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12348	     (pattern & ~CTL_LUN_PAT_MASK))
12349		return (CTL_LUN_PAT_NONE);
12350
12351	/*
12352	 * If the user asked for a range check, see if the requested LBA
12353	 * range overlaps with this command's LBA range.
12354	 */
12355	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12356		uint64_t lba1;
12357		uint32_t len1;
12358		ctl_action action;
12359		int retval;
12360
12361		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12362		if (retval != 0)
12363			return (CTL_LUN_PAT_NONE);
12364
12365		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12366					      desc->lba_range.len);
12367		/*
12368		 * A "pass" means that the LBA ranges don't overlap, so
12369		 * this doesn't match the user's range criteria.
12370		 */
12371		if (action == CTL_ACTION_PASS)
12372			return (CTL_LUN_PAT_NONE);
12373	}
12374
12375	return (filtered_pattern);
12376}
12377
12378static void
12379ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12380{
12381	struct ctl_error_desc *desc, *desc2;
12382
12383	mtx_assert(&lun->lun_lock, MA_OWNED);
12384
12385	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12386		ctl_lun_error_pattern pattern;
12387		/*
12388		 * Check to see whether this particular command matches
12389		 * the pattern in the descriptor.
12390		 */
12391		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12392		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12393			continue;
12394
12395		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12396		case CTL_LUN_INJ_ABORTED:
12397			ctl_set_aborted(&io->scsiio);
12398			break;
12399		case CTL_LUN_INJ_MEDIUM_ERR:
12400			ctl_set_medium_error(&io->scsiio);
12401			break;
12402		case CTL_LUN_INJ_UA:
12403			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12404			 * OCCURRED */
12405			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12406			break;
12407		case CTL_LUN_INJ_CUSTOM:
12408			/*
12409			 * We're assuming the user knows what he is doing.
12410			 * Just copy the sense information without doing
12411			 * checks.
12412			 */
12413			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12414			      ctl_min(sizeof(desc->custom_sense),
12415				      sizeof(io->scsiio.sense_data)));
12416			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12417			io->scsiio.sense_len = SSD_FULL_SIZE;
12418			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12419			break;
12420		case CTL_LUN_INJ_NONE:
12421		default:
12422			/*
12423			 * If this is an error injection type we don't know
12424			 * about, clear the continuous flag (if it is set)
12425			 * so it will get deleted below.
12426			 */
12427			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12428			break;
12429		}
12430		/*
12431		 * By default, each error injection action is a one-shot
12432		 */
12433		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12434			continue;
12435
12436		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12437
12438		free(desc, M_CTL);
12439	}
12440}
12441
12442#ifdef CTL_IO_DELAY
12443static void
12444ctl_datamove_timer_wakeup(void *arg)
12445{
12446	union ctl_io *io;
12447
12448	io = (union ctl_io *)arg;
12449
12450	ctl_datamove(io);
12451}
12452#endif /* CTL_IO_DELAY */
12453
12454void
12455ctl_datamove(union ctl_io *io)
12456{
12457	void (*fe_datamove)(union ctl_io *io);
12458
12459	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12460
12461	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12462
12463#ifdef CTL_TIME_IO
12464	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12465		char str[256];
12466		char path_str[64];
12467		struct sbuf sb;
12468
12469		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12470		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12471
12472		sbuf_cat(&sb, path_str);
12473		switch (io->io_hdr.io_type) {
12474		case CTL_IO_SCSI:
12475			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12476			sbuf_printf(&sb, "\n");
12477			sbuf_cat(&sb, path_str);
12478			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12479				    io->scsiio.tag_num, io->scsiio.tag_type);
12480			break;
12481		case CTL_IO_TASK:
12482			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12483				    "Tag Type: %d\n", io->taskio.task_action,
12484				    io->taskio.tag_num, io->taskio.tag_type);
12485			break;
12486		default:
12487			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12488			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12489			break;
12490		}
12491		sbuf_cat(&sb, path_str);
12492		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12493			    (intmax_t)time_uptime - io->io_hdr.start_time);
12494		sbuf_finish(&sb);
12495		printf("%s", sbuf_data(&sb));
12496	}
12497#endif /* CTL_TIME_IO */
12498
12499#ifdef CTL_IO_DELAY
12500	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12501		struct ctl_lun *lun;
12502
12503		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12504
12505		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12506	} else {
12507		struct ctl_lun *lun;
12508
12509		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12510		if ((lun != NULL)
12511		 && (lun->delay_info.datamove_delay > 0)) {
12512			struct callout *callout;
12513
12514			callout = (struct callout *)&io->io_hdr.timer_bytes;
12515			callout_init(callout, /*mpsafe*/ 1);
12516			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12517			callout_reset(callout,
12518				      lun->delay_info.datamove_delay * hz,
12519				      ctl_datamove_timer_wakeup, io);
12520			if (lun->delay_info.datamove_type ==
12521			    CTL_DELAY_TYPE_ONESHOT)
12522				lun->delay_info.datamove_delay = 0;
12523			return;
12524		}
12525	}
12526#endif
12527
12528	/*
12529	 * This command has been aborted.  Set the port status, so we fail
12530	 * the data move.
12531	 */
12532	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12533		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12534		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12535		       io->io_hdr.nexus.targ_port,
12536		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12537		       io->io_hdr.nexus.targ_lun);
12538		io->io_hdr.port_status = 31337;
12539		/*
12540		 * Note that the backend, in this case, will get the
12541		 * callback in its context.  In other cases it may get
12542		 * called in the frontend's interrupt thread context.
12543		 */
12544		io->scsiio.be_move_done(io);
12545		return;
12546	}
12547
12548	/*
12549	 * If we're in XFER mode and this I/O is from the other shelf
12550	 * controller, we need to send the DMA to the other side to
12551	 * actually transfer the data to/from the host.  In serialize only
12552	 * mode the transfer happens below CTL and ctl_datamove() is only
12553	 * called on the machine that originally received the I/O.
12554	 */
12555	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12556	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12557		union ctl_ha_msg msg;
12558		uint32_t sg_entries_sent;
12559		int do_sg_copy;
12560		int i;
12561
12562		memset(&msg, 0, sizeof(msg));
12563		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12564		msg.hdr.original_sc = io->io_hdr.original_sc;
12565		msg.hdr.serializing_sc = io;
12566		msg.hdr.nexus = io->io_hdr.nexus;
12567		msg.dt.flags = io->io_hdr.flags;
12568		/*
12569		 * We convert everything into a S/G list here.  We can't
12570		 * pass by reference, only by value between controllers.
12571		 * So we can't pass a pointer to the S/G list, only as many
12572		 * S/G entries as we can fit in here.  If it's possible for
12573		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12574		 * then we need to break this up into multiple transfers.
12575		 */
12576		if (io->scsiio.kern_sg_entries == 0) {
12577			msg.dt.kern_sg_entries = 1;
12578			/*
12579			 * If this is in cached memory, flush the cache
12580			 * before we send the DMA request to the other
12581			 * controller.  We want to do this in either the
12582			 * read or the write case.  The read case is
12583			 * straightforward.  In the write case, we want to
12584			 * make sure nothing is in the local cache that
12585			 * could overwrite the DMAed data.
12586			 */
12587			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12588				/*
12589				 * XXX KDM use bus_dmamap_sync() here.
12590				 */
12591			}
12592
12593			/*
12594			 * Convert to a physical address if this is a
12595			 * virtual address.
12596			 */
12597			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12598				msg.dt.sg_list[0].addr =
12599					io->scsiio.kern_data_ptr;
12600			} else {
12601				/*
12602				 * XXX KDM use busdma here!
12603				 */
12604#if 0
12605				msg.dt.sg_list[0].addr = (void *)
12606					vtophys(io->scsiio.kern_data_ptr);
12607#endif
12608			}
12609
12610			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12611			do_sg_copy = 0;
12612		} else {
12613			struct ctl_sg_entry *sgl;
12614
12615			do_sg_copy = 1;
12616			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12617			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12618			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12619				/*
12620				 * XXX KDM use bus_dmamap_sync() here.
12621				 */
12622			}
12623		}
12624
12625		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12626		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12627		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12628		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12629		msg.dt.sg_sequence = 0;
12630
12631		/*
12632		 * Loop until we've sent all of the S/G entries.  On the
12633		 * other end, we'll recompose these S/G entries into one
12634		 * contiguous list before passing it to the
12635		 */
12636		for (sg_entries_sent = 0; sg_entries_sent <
12637		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12638			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12639				sizeof(msg.dt.sg_list[0])),
12640				msg.dt.kern_sg_entries - sg_entries_sent);
12641
12642			if (do_sg_copy != 0) {
12643				struct ctl_sg_entry *sgl;
12644				int j;
12645
12646				sgl = (struct ctl_sg_entry *)
12647					io->scsiio.kern_data_ptr;
12648				/*
12649				 * If this is in cached memory, flush the cache
12650				 * before we send the DMA request to the other
12651				 * controller.  We want to do this in either
12652				 * the * read or the write case.  The read
12653				 * case is straightforward.  In the write
12654				 * case, we want to make sure nothing is
12655				 * in the local cache that could overwrite
12656				 * the DMAed data.
12657				 */
12658
12659				for (i = sg_entries_sent, j = 0;
12660				     i < msg.dt.cur_sg_entries; i++, j++) {
12661					if ((io->io_hdr.flags &
12662					     CTL_FLAG_NO_DATASYNC) == 0) {
12663						/*
12664						 * XXX KDM use bus_dmamap_sync()
12665						 */
12666					}
12667					if ((io->io_hdr.flags &
12668					     CTL_FLAG_BUS_ADDR) == 0) {
12669						/*
12670						 * XXX KDM use busdma.
12671						 */
12672#if 0
12673						msg.dt.sg_list[j].addr =(void *)
12674						       vtophys(sgl[i].addr);
12675#endif
12676					} else {
12677						msg.dt.sg_list[j].addr =
12678							sgl[i].addr;
12679					}
12680					msg.dt.sg_list[j].len = sgl[i].len;
12681				}
12682			}
12683
12684			sg_entries_sent += msg.dt.cur_sg_entries;
12685			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12686				msg.dt.sg_last = 1;
12687			else
12688				msg.dt.sg_last = 0;
12689
12690			/*
12691			 * XXX KDM drop and reacquire the lock here?
12692			 */
12693			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12694			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12695				/*
12696				 * XXX do something here.
12697				 */
12698			}
12699
12700			msg.dt.sent_sg_entries = sg_entries_sent;
12701		}
12702		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12703		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12704			ctl_failover_io(io, /*have_lock*/ 0);
12705
12706	} else {
12707
12708		/*
12709		 * Lookup the fe_datamove() function for this particular
12710		 * front end.
12711		 */
12712		fe_datamove =
12713		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12714
12715		fe_datamove(io);
12716	}
12717}
12718
12719static void
12720ctl_send_datamove_done(union ctl_io *io, int have_lock)
12721{
12722	union ctl_ha_msg msg;
12723	int isc_status;
12724
12725	memset(&msg, 0, sizeof(msg));
12726
12727	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12728	msg.hdr.original_sc = io;
12729	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12730	msg.hdr.nexus = io->io_hdr.nexus;
12731	msg.hdr.status = io->io_hdr.status;
12732	msg.scsi.tag_num = io->scsiio.tag_num;
12733	msg.scsi.tag_type = io->scsiio.tag_type;
12734	msg.scsi.scsi_status = io->scsiio.scsi_status;
12735	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12736	       sizeof(io->scsiio.sense_data));
12737	msg.scsi.sense_len = io->scsiio.sense_len;
12738	msg.scsi.sense_residual = io->scsiio.sense_residual;
12739	msg.scsi.fetd_status = io->io_hdr.port_status;
12740	msg.scsi.residual = io->scsiio.residual;
12741	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12742
12743	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12744		ctl_failover_io(io, /*have_lock*/ have_lock);
12745		return;
12746	}
12747
12748	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12749	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12750		/* XXX do something if this fails */
12751	}
12752
12753}
12754
12755/*
12756 * The DMA to the remote side is done, now we need to tell the other side
12757 * we're done so it can continue with its data movement.
12758 */
12759static void
12760ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12761{
12762	union ctl_io *io;
12763
12764	io = rq->context;
12765
12766	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12767		printf("%s: ISC DMA write failed with error %d", __func__,
12768		       rq->ret);
12769		ctl_set_internal_failure(&io->scsiio,
12770					 /*sks_valid*/ 1,
12771					 /*retry_count*/ rq->ret);
12772	}
12773
12774	ctl_dt_req_free(rq);
12775
12776	/*
12777	 * In this case, we had to malloc the memory locally.  Free it.
12778	 */
12779	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12780		int i;
12781		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12782			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12783	}
12784	/*
12785	 * The data is in local and remote memory, so now we need to send
12786	 * status (good or back) back to the other side.
12787	 */
12788	ctl_send_datamove_done(io, /*have_lock*/ 0);
12789}
12790
12791/*
12792 * We've moved the data from the host/controller into local memory.  Now we
12793 * need to push it over to the remote controller's memory.
12794 */
12795static int
12796ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12797{
12798	int retval;
12799
12800	retval = 0;
12801
12802	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12803					  ctl_datamove_remote_write_cb);
12804
12805	return (retval);
12806}
12807
12808static void
12809ctl_datamove_remote_write(union ctl_io *io)
12810{
12811	int retval;
12812	void (*fe_datamove)(union ctl_io *io);
12813
12814	/*
12815	 * - Get the data from the host/HBA into local memory.
12816	 * - DMA memory from the local controller to the remote controller.
12817	 * - Send status back to the remote controller.
12818	 */
12819
12820	retval = ctl_datamove_remote_sgl_setup(io);
12821	if (retval != 0)
12822		return;
12823
12824	/* Switch the pointer over so the FETD knows what to do */
12825	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12826
12827	/*
12828	 * Use a custom move done callback, since we need to send completion
12829	 * back to the other controller, not to the backend on this side.
12830	 */
12831	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12832
12833	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12834
12835	fe_datamove(io);
12836
12837	return;
12838
12839}
12840
12841static int
12842ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12843{
12844#if 0
12845	char str[256];
12846	char path_str[64];
12847	struct sbuf sb;
12848#endif
12849
12850	/*
12851	 * In this case, we had to malloc the memory locally.  Free it.
12852	 */
12853	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12854		int i;
12855		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12856			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12857	}
12858
12859#if 0
12860	scsi_path_string(io, path_str, sizeof(path_str));
12861	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12862	sbuf_cat(&sb, path_str);
12863	scsi_command_string(&io->scsiio, NULL, &sb);
12864	sbuf_printf(&sb, "\n");
12865	sbuf_cat(&sb, path_str);
12866	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12867		    io->scsiio.tag_num, io->scsiio.tag_type);
12868	sbuf_cat(&sb, path_str);
12869	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12870		    io->io_hdr.flags, io->io_hdr.status);
12871	sbuf_finish(&sb);
12872	printk("%s", sbuf_data(&sb));
12873#endif
12874
12875
12876	/*
12877	 * The read is done, now we need to send status (good or bad) back
12878	 * to the other side.
12879	 */
12880	ctl_send_datamove_done(io, /*have_lock*/ 0);
12881
12882	return (0);
12883}
12884
12885static void
12886ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12887{
12888	union ctl_io *io;
12889	void (*fe_datamove)(union ctl_io *io);
12890
12891	io = rq->context;
12892
12893	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12894		printf("%s: ISC DMA read failed with error %d", __func__,
12895		       rq->ret);
12896		ctl_set_internal_failure(&io->scsiio,
12897					 /*sks_valid*/ 1,
12898					 /*retry_count*/ rq->ret);
12899	}
12900
12901	ctl_dt_req_free(rq);
12902
12903	/* Switch the pointer over so the FETD knows what to do */
12904	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12905
12906	/*
12907	 * Use a custom move done callback, since we need to send completion
12908	 * back to the other controller, not to the backend on this side.
12909	 */
12910	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12911
12912	/* XXX KDM add checks like the ones in ctl_datamove? */
12913
12914	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12915
12916	fe_datamove(io);
12917}
12918
12919static int
12920ctl_datamove_remote_sgl_setup(union ctl_io *io)
12921{
12922	struct ctl_sg_entry *local_sglist, *remote_sglist;
12923	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12924	struct ctl_softc *softc;
12925	int retval;
12926	int i;
12927
12928	retval = 0;
12929	softc = control_softc;
12930
12931	local_sglist = io->io_hdr.local_sglist;
12932	local_dma_sglist = io->io_hdr.local_dma_sglist;
12933	remote_sglist = io->io_hdr.remote_sglist;
12934	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12935
12936	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12937		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12938			local_sglist[i].len = remote_sglist[i].len;
12939
12940			/*
12941			 * XXX Detect the situation where the RS-level I/O
12942			 * redirector on the other side has already read the
12943			 * data off of the AOR RS on this side, and
12944			 * transferred it to remote (mirror) memory on the
12945			 * other side.  Since we already have the data in
12946			 * memory here, we just need to use it.
12947			 *
12948			 * XXX KDM this can probably be removed once we
12949			 * get the cache device code in and take the
12950			 * current AOR implementation out.
12951			 */
12952#ifdef NEEDTOPORT
12953			if ((remote_sglist[i].addr >=
12954			     (void *)vtophys(softc->mirr->addr))
12955			 && (remote_sglist[i].addr <
12956			     ((void *)vtophys(softc->mirr->addr) +
12957			     CacheMirrorOffset))) {
12958				local_sglist[i].addr = remote_sglist[i].addr -
12959					CacheMirrorOffset;
12960				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12961				     CTL_FLAG_DATA_IN)
12962					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12963			} else {
12964				local_sglist[i].addr = remote_sglist[i].addr +
12965					CacheMirrorOffset;
12966			}
12967#endif
12968#if 0
12969			printf("%s: local %p, remote %p, len %d\n",
12970			       __func__, local_sglist[i].addr,
12971			       remote_sglist[i].addr, local_sglist[i].len);
12972#endif
12973		}
12974	} else {
12975		uint32_t len_to_go;
12976
12977		/*
12978		 * In this case, we don't have automatically allocated
12979		 * memory for this I/O on this controller.  This typically
12980		 * happens with internal CTL I/O -- e.g. inquiry, mode
12981		 * sense, etc.  Anything coming from RAIDCore will have
12982		 * a mirror area available.
12983		 */
12984		len_to_go = io->scsiio.kern_data_len;
12985
12986		/*
12987		 * Clear the no datasync flag, we have to use malloced
12988		 * buffers.
12989		 */
12990		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12991
12992		/*
12993		 * The difficult thing here is that the size of the various
12994		 * S/G segments may be different than the size from the
12995		 * remote controller.  That'll make it harder when DMAing
12996		 * the data back to the other side.
12997		 */
12998		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12999		     sizeof(io->io_hdr.remote_sglist[0])) &&
13000		     (len_to_go > 0); i++) {
13001			local_sglist[i].len = ctl_min(len_to_go, 131072);
13002			CTL_SIZE_8B(local_dma_sglist[i].len,
13003				    local_sglist[i].len);
13004			local_sglist[i].addr =
13005				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13006
13007			local_dma_sglist[i].addr = local_sglist[i].addr;
13008
13009			if (local_sglist[i].addr == NULL) {
13010				int j;
13011
13012				printf("malloc failed for %zd bytes!",
13013				       local_dma_sglist[i].len);
13014				for (j = 0; j < i; j++) {
13015					free(local_sglist[j].addr, M_CTL);
13016				}
13017				ctl_set_internal_failure(&io->scsiio,
13018							 /*sks_valid*/ 1,
13019							 /*retry_count*/ 4857);
13020				retval = 1;
13021				goto bailout_error;
13022
13023			}
13024			/* XXX KDM do we need a sync here? */
13025
13026			len_to_go -= local_sglist[i].len;
13027		}
13028		/*
13029		 * Reset the number of S/G entries accordingly.  The
13030		 * original number of S/G entries is available in
13031		 * rem_sg_entries.
13032		 */
13033		io->scsiio.kern_sg_entries = i;
13034
13035#if 0
13036		printf("%s: kern_sg_entries = %d\n", __func__,
13037		       io->scsiio.kern_sg_entries);
13038		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13039			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13040			       local_sglist[i].addr, local_sglist[i].len,
13041			       local_dma_sglist[i].len);
13042#endif
13043	}
13044
13045
13046	return (retval);
13047
13048bailout_error:
13049
13050	ctl_send_datamove_done(io, /*have_lock*/ 0);
13051
13052	return (retval);
13053}
13054
13055static int
13056ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13057			 ctl_ha_dt_cb callback)
13058{
13059	struct ctl_ha_dt_req *rq;
13060	struct ctl_sg_entry *remote_sglist, *local_sglist;
13061	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13062	uint32_t local_used, remote_used, total_used;
13063	int retval;
13064	int i, j;
13065
13066	retval = 0;
13067
13068	rq = ctl_dt_req_alloc();
13069
13070	/*
13071	 * If we failed to allocate the request, and if the DMA didn't fail
13072	 * anyway, set busy status.  This is just a resource allocation
13073	 * failure.
13074	 */
13075	if ((rq == NULL)
13076	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13077		ctl_set_busy(&io->scsiio);
13078
13079	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13080
13081		if (rq != NULL)
13082			ctl_dt_req_free(rq);
13083
13084		/*
13085		 * The data move failed.  We need to return status back
13086		 * to the other controller.  No point in trying to DMA
13087		 * data to the remote controller.
13088		 */
13089
13090		ctl_send_datamove_done(io, /*have_lock*/ 0);
13091
13092		retval = 1;
13093
13094		goto bailout;
13095	}
13096
13097	local_sglist = io->io_hdr.local_sglist;
13098	local_dma_sglist = io->io_hdr.local_dma_sglist;
13099	remote_sglist = io->io_hdr.remote_sglist;
13100	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13101	local_used = 0;
13102	remote_used = 0;
13103	total_used = 0;
13104
13105	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13106		rq->ret = CTL_HA_STATUS_SUCCESS;
13107		rq->context = io;
13108		callback(rq);
13109		goto bailout;
13110	}
13111
13112	/*
13113	 * Pull/push the data over the wire from/to the other controller.
13114	 * This takes into account the possibility that the local and
13115	 * remote sglists may not be identical in terms of the size of
13116	 * the elements and the number of elements.
13117	 *
13118	 * One fundamental assumption here is that the length allocated for
13119	 * both the local and remote sglists is identical.  Otherwise, we've
13120	 * essentially got a coding error of some sort.
13121	 */
13122	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13123		int isc_ret;
13124		uint32_t cur_len, dma_length;
13125		uint8_t *tmp_ptr;
13126
13127		rq->id = CTL_HA_DATA_CTL;
13128		rq->command = command;
13129		rq->context = io;
13130
13131		/*
13132		 * Both pointers should be aligned.  But it is possible
13133		 * that the allocation length is not.  They should both
13134		 * also have enough slack left over at the end, though,
13135		 * to round up to the next 8 byte boundary.
13136		 */
13137		cur_len = ctl_min(local_sglist[i].len - local_used,
13138				  remote_sglist[j].len - remote_used);
13139
13140		/*
13141		 * In this case, we have a size issue and need to decrease
13142		 * the size, except in the case where we actually have less
13143		 * than 8 bytes left.  In that case, we need to increase
13144		 * the DMA length to get the last bit.
13145		 */
13146		if ((cur_len & 0x7) != 0) {
13147			if (cur_len > 0x7) {
13148				cur_len = cur_len - (cur_len & 0x7);
13149				dma_length = cur_len;
13150			} else {
13151				CTL_SIZE_8B(dma_length, cur_len);
13152			}
13153
13154		} else
13155			dma_length = cur_len;
13156
13157		/*
13158		 * If we had to allocate memory for this I/O, instead of using
13159		 * the non-cached mirror memory, we'll need to flush the cache
13160		 * before trying to DMA to the other controller.
13161		 *
13162		 * We could end up doing this multiple times for the same
13163		 * segment if we have a larger local segment than remote
13164		 * segment.  That shouldn't be an issue.
13165		 */
13166		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13167			/*
13168			 * XXX KDM use bus_dmamap_sync() here.
13169			 */
13170		}
13171
13172		rq->size = dma_length;
13173
13174		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13175		tmp_ptr += local_used;
13176
13177		/* Use physical addresses when talking to ISC hardware */
13178		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13179			/* XXX KDM use busdma */
13180#if 0
13181			rq->local = vtophys(tmp_ptr);
13182#endif
13183		} else
13184			rq->local = tmp_ptr;
13185
13186		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13187		tmp_ptr += remote_used;
13188		rq->remote = tmp_ptr;
13189
13190		rq->callback = NULL;
13191
13192		local_used += cur_len;
13193		if (local_used >= local_sglist[i].len) {
13194			i++;
13195			local_used = 0;
13196		}
13197
13198		remote_used += cur_len;
13199		if (remote_used >= remote_sglist[j].len) {
13200			j++;
13201			remote_used = 0;
13202		}
13203		total_used += cur_len;
13204
13205		if (total_used >= io->scsiio.kern_data_len)
13206			rq->callback = callback;
13207
13208		if ((rq->size & 0x7) != 0) {
13209			printf("%s: warning: size %d is not on 8b boundary\n",
13210			       __func__, rq->size);
13211		}
13212		if (((uintptr_t)rq->local & 0x7) != 0) {
13213			printf("%s: warning: local %p not on 8b boundary\n",
13214			       __func__, rq->local);
13215		}
13216		if (((uintptr_t)rq->remote & 0x7) != 0) {
13217			printf("%s: warning: remote %p not on 8b boundary\n",
13218			       __func__, rq->local);
13219		}
13220#if 0
13221		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13222		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13223		       rq->local, rq->remote, rq->size);
13224#endif
13225
13226		isc_ret = ctl_dt_single(rq);
13227		if (isc_ret == CTL_HA_STATUS_WAIT)
13228			continue;
13229
13230		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13231			rq->ret = CTL_HA_STATUS_SUCCESS;
13232		} else {
13233			rq->ret = isc_ret;
13234		}
13235		callback(rq);
13236		goto bailout;
13237	}
13238
13239bailout:
13240	return (retval);
13241
13242}
13243
13244static void
13245ctl_datamove_remote_read(union ctl_io *io)
13246{
13247	int retval;
13248	int i;
13249
13250	/*
13251	 * This will send an error to the other controller in the case of a
13252	 * failure.
13253	 */
13254	retval = ctl_datamove_remote_sgl_setup(io);
13255	if (retval != 0)
13256		return;
13257
13258	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13259					  ctl_datamove_remote_read_cb);
13260	if ((retval != 0)
13261	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13262		/*
13263		 * Make sure we free memory if there was an error..  The
13264		 * ctl_datamove_remote_xfer() function will send the
13265		 * datamove done message, or call the callback with an
13266		 * error if there is a problem.
13267		 */
13268		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13269			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13270	}
13271
13272	return;
13273}
13274
13275/*
13276 * Process a datamove request from the other controller.  This is used for
13277 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13278 * first.  Once that is complete, the data gets DMAed into the remote
13279 * controller's memory.  For reads, we DMA from the remote controller's
13280 * memory into our memory first, and then move it out to the FETD.
13281 */
13282static void
13283ctl_datamove_remote(union ctl_io *io)
13284{
13285	struct ctl_softc *softc;
13286
13287	softc = control_softc;
13288
13289	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13290
13291	/*
13292	 * Note that we look for an aborted I/O here, but don't do some of
13293	 * the other checks that ctl_datamove() normally does.
13294	 * We don't need to run the datamove delay code, since that should
13295	 * have been done if need be on the other controller.
13296	 */
13297	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13298		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13299		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13300		       io->io_hdr.nexus.targ_port,
13301		       io->io_hdr.nexus.targ_target.id,
13302		       io->io_hdr.nexus.targ_lun);
13303		io->io_hdr.port_status = 31338;
13304		ctl_send_datamove_done(io, /*have_lock*/ 0);
13305		return;
13306	}
13307
13308	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13309		ctl_datamove_remote_write(io);
13310	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13311		ctl_datamove_remote_read(io);
13312	} else {
13313		union ctl_ha_msg msg;
13314		struct scsi_sense_data *sense;
13315		uint8_t sks[3];
13316		int retry_count;
13317
13318		memset(&msg, 0, sizeof(msg));
13319
13320		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13321		msg.hdr.status = CTL_SCSI_ERROR;
13322		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13323
13324		retry_count = 4243;
13325
13326		sense = &msg.scsi.sense_data;
13327		sks[0] = SSD_SCS_VALID;
13328		sks[1] = (retry_count >> 8) & 0xff;
13329		sks[2] = retry_count & 0xff;
13330
13331		/* "Internal target failure" */
13332		scsi_set_sense_data(sense,
13333				    /*sense_format*/ SSD_TYPE_NONE,
13334				    /*current_error*/ 1,
13335				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13336				    /*asc*/ 0x44,
13337				    /*ascq*/ 0x00,
13338				    /*type*/ SSD_ELEM_SKS,
13339				    /*size*/ sizeof(sks),
13340				    /*data*/ sks,
13341				    SSD_ELEM_NONE);
13342
13343		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13344		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13345			ctl_failover_io(io, /*have_lock*/ 1);
13346			return;
13347		}
13348
13349		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13350		    CTL_HA_STATUS_SUCCESS) {
13351			/* XXX KDM what to do if this fails? */
13352		}
13353		return;
13354	}
13355
13356}
13357
13358static int
13359ctl_process_done(union ctl_io *io)
13360{
13361	struct ctl_lun *lun;
13362	struct ctl_softc *ctl_softc;
13363	void (*fe_done)(union ctl_io *io);
13364	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13365
13366	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13367
13368	fe_done =
13369	    control_softc->ctl_ports[targ_port]->fe_done;
13370
13371#ifdef CTL_TIME_IO
13372	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13373		char str[256];
13374		char path_str[64];
13375		struct sbuf sb;
13376
13377		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13378		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13379
13380		sbuf_cat(&sb, path_str);
13381		switch (io->io_hdr.io_type) {
13382		case CTL_IO_SCSI:
13383			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13384			sbuf_printf(&sb, "\n");
13385			sbuf_cat(&sb, path_str);
13386			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13387				    io->scsiio.tag_num, io->scsiio.tag_type);
13388			break;
13389		case CTL_IO_TASK:
13390			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13391				    "Tag Type: %d\n", io->taskio.task_action,
13392				    io->taskio.tag_num, io->taskio.tag_type);
13393			break;
13394		default:
13395			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13396			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13397			break;
13398		}
13399		sbuf_cat(&sb, path_str);
13400		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13401			    (intmax_t)time_uptime - io->io_hdr.start_time);
13402		sbuf_finish(&sb);
13403		printf("%s", sbuf_data(&sb));
13404	}
13405#endif /* CTL_TIME_IO */
13406
13407	switch (io->io_hdr.io_type) {
13408	case CTL_IO_SCSI:
13409		break;
13410	case CTL_IO_TASK:
13411		if (bootverbose || verbose > 0)
13412			ctl_io_error_print(io, NULL);
13413		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13414			ctl_free_io(io);
13415		else
13416			fe_done(io);
13417		return (CTL_RETVAL_COMPLETE);
13418		break;
13419	default:
13420		printf("ctl_process_done: invalid io type %d\n",
13421		       io->io_hdr.io_type);
13422		panic("ctl_process_done: invalid io type %d\n",
13423		      io->io_hdr.io_type);
13424		break; /* NOTREACHED */
13425	}
13426
13427	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13428	if (lun == NULL) {
13429		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13430				 io->io_hdr.nexus.targ_mapped_lun));
13431		fe_done(io);
13432		goto bailout;
13433	}
13434	ctl_softc = lun->ctl_softc;
13435
13436	mtx_lock(&lun->lun_lock);
13437
13438	/*
13439	 * Check to see if we have any errors to inject here.  We only
13440	 * inject errors for commands that don't already have errors set.
13441	 */
13442	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13443	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13444		ctl_inject_error(lun, io);
13445
13446	/*
13447	 * XXX KDM how do we treat commands that aren't completed
13448	 * successfully?
13449	 *
13450	 * XXX KDM should we also track I/O latency?
13451	 */
13452	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13453	    io->io_hdr.io_type == CTL_IO_SCSI) {
13454#ifdef CTL_TIME_IO
13455		struct bintime cur_bt;
13456#endif
13457		int type;
13458
13459		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13460		    CTL_FLAG_DATA_IN)
13461			type = CTL_STATS_READ;
13462		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13463		    CTL_FLAG_DATA_OUT)
13464			type = CTL_STATS_WRITE;
13465		else
13466			type = CTL_STATS_NO_IO;
13467
13468		lun->stats.ports[targ_port].bytes[type] +=
13469		    io->scsiio.kern_total_len;
13470		lun->stats.ports[targ_port].operations[type]++;
13471#ifdef CTL_TIME_IO
13472		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13473		   &io->io_hdr.dma_bt);
13474		lun->stats.ports[targ_port].num_dmas[type] +=
13475		    io->io_hdr.num_dmas;
13476		getbintime(&cur_bt);
13477		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13478		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13479#endif
13480	}
13481
13482	/*
13483	 * Remove this from the OOA queue.
13484	 */
13485	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13486
13487	/*
13488	 * Run through the blocked queue on this LUN and see if anything
13489	 * has become unblocked, now that this transaction is done.
13490	 */
13491	ctl_check_blocked(lun);
13492
13493	/*
13494	 * If the LUN has been invalidated, free it if there is nothing
13495	 * left on its OOA queue.
13496	 */
13497	if ((lun->flags & CTL_LUN_INVALID)
13498	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13499		mtx_unlock(&lun->lun_lock);
13500		mtx_lock(&ctl_softc->ctl_lock);
13501		ctl_free_lun(lun);
13502		mtx_unlock(&ctl_softc->ctl_lock);
13503	} else
13504		mtx_unlock(&lun->lun_lock);
13505
13506	/*
13507	 * If this command has been aborted, make sure we set the status
13508	 * properly.  The FETD is responsible for freeing the I/O and doing
13509	 * whatever it needs to do to clean up its state.
13510	 */
13511	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13512		ctl_set_task_aborted(&io->scsiio);
13513
13514	/*
13515	 * We print out status for every task management command.  For SCSI
13516	 * commands, we filter out any unit attention errors; they happen
13517	 * on every boot, and would clutter up the log.  Note:  task
13518	 * management commands aren't printed here, they are printed above,
13519	 * since they should never even make it down here.
13520	 */
13521	switch (io->io_hdr.io_type) {
13522	case CTL_IO_SCSI: {
13523		int error_code, sense_key, asc, ascq;
13524
13525		sense_key = 0;
13526
13527		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13528		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13529			/*
13530			 * Since this is just for printing, no need to
13531			 * show errors here.
13532			 */
13533			scsi_extract_sense_len(&io->scsiio.sense_data,
13534					       io->scsiio.sense_len,
13535					       &error_code,
13536					       &sense_key,
13537					       &asc,
13538					       &ascq,
13539					       /*show_errors*/ 0);
13540		}
13541
13542		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13543		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13544		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13545		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13546
13547			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13548				ctl_softc->skipped_prints++;
13549			} else {
13550				uint32_t skipped_prints;
13551
13552				skipped_prints = ctl_softc->skipped_prints;
13553
13554				ctl_softc->skipped_prints = 0;
13555				ctl_softc->last_print_jiffies = time_uptime;
13556
13557				if (skipped_prints > 0) {
13558#ifdef NEEDTOPORT
13559					csevent_log(CSC_CTL | CSC_SHELF_SW |
13560					    CTL_ERROR_REPORT,
13561					    csevent_LogType_Trace,
13562					    csevent_Severity_Information,
13563					    csevent_AlertLevel_Green,
13564					    csevent_FRU_Firmware,
13565					    csevent_FRU_Unknown,
13566					    "High CTL error volume, %d prints "
13567					    "skipped", skipped_prints);
13568#endif
13569				}
13570				if (bootverbose || verbose > 0)
13571					ctl_io_error_print(io, NULL);
13572			}
13573		}
13574		break;
13575	}
13576	case CTL_IO_TASK:
13577		if (bootverbose || verbose > 0)
13578			ctl_io_error_print(io, NULL);
13579		break;
13580	default:
13581		break;
13582	}
13583
13584	/*
13585	 * Tell the FETD or the other shelf controller we're done with this
13586	 * command.  Note that only SCSI commands get to this point.  Task
13587	 * management commands are completed above.
13588	 *
13589	 * We only send status to the other controller if we're in XFER
13590	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13591	 * received the I/O (from CTL's perspective), and so the status is
13592	 * generated there.
13593	 *
13594	 * XXX KDM if we hold the lock here, we could cause a deadlock
13595	 * if the frontend comes back in in this context to queue
13596	 * something.
13597	 */
13598	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13599	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13600		union ctl_ha_msg msg;
13601
13602		memset(&msg, 0, sizeof(msg));
13603		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13604		msg.hdr.original_sc = io->io_hdr.original_sc;
13605		msg.hdr.nexus = io->io_hdr.nexus;
13606		msg.hdr.status = io->io_hdr.status;
13607		msg.scsi.scsi_status = io->scsiio.scsi_status;
13608		msg.scsi.tag_num = io->scsiio.tag_num;
13609		msg.scsi.tag_type = io->scsiio.tag_type;
13610		msg.scsi.sense_len = io->scsiio.sense_len;
13611		msg.scsi.sense_residual = io->scsiio.sense_residual;
13612		msg.scsi.residual = io->scsiio.residual;
13613		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13614		       sizeof(io->scsiio.sense_data));
13615		/*
13616		 * We copy this whether or not this is an I/O-related
13617		 * command.  Otherwise, we'd have to go and check to see
13618		 * whether it's a read/write command, and it really isn't
13619		 * worth it.
13620		 */
13621		memcpy(&msg.scsi.lbalen,
13622		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13623		       sizeof(msg.scsi.lbalen));
13624
13625		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13626				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13627			/* XXX do something here */
13628		}
13629
13630		ctl_free_io(io);
13631	} else
13632		fe_done(io);
13633
13634bailout:
13635
13636	return (CTL_RETVAL_COMPLETE);
13637}
13638
13639#ifdef CTL_WITH_CA
13640/*
13641 * Front end should call this if it doesn't do autosense.  When the request
13642 * sense comes back in from the initiator, we'll dequeue this and send it.
13643 */
13644int
13645ctl_queue_sense(union ctl_io *io)
13646{
13647	struct ctl_lun *lun;
13648	struct ctl_softc *ctl_softc;
13649	uint32_t initidx, targ_lun;
13650
13651	ctl_softc = control_softc;
13652
13653	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13654
13655	/*
13656	 * LUN lookup will likely move to the ctl_work_thread() once we
13657	 * have our new queueing infrastructure (that doesn't put things on
13658	 * a per-LUN queue initially).  That is so that we can handle
13659	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13660	 * can't deal with that right now.
13661	 */
13662	mtx_lock(&ctl_softc->ctl_lock);
13663
13664	/*
13665	 * If we don't have a LUN for this, just toss the sense
13666	 * information.
13667	 */
13668	targ_lun = io->io_hdr.nexus.targ_lun;
13669	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13670	if ((targ_lun < CTL_MAX_LUNS)
13671	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13672		lun = ctl_softc->ctl_luns[targ_lun];
13673	else
13674		goto bailout;
13675
13676	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13677
13678	mtx_lock(&lun->lun_lock);
13679	/*
13680	 * Already have CA set for this LUN...toss the sense information.
13681	 */
13682	if (ctl_is_set(lun->have_ca, initidx)) {
13683		mtx_unlock(&lun->lun_lock);
13684		goto bailout;
13685	}
13686
13687	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13688	       ctl_min(sizeof(lun->pending_sense[initidx]),
13689	       sizeof(io->scsiio.sense_data)));
13690	ctl_set_mask(lun->have_ca, initidx);
13691	mtx_unlock(&lun->lun_lock);
13692
13693bailout:
13694	mtx_unlock(&ctl_softc->ctl_lock);
13695
13696	ctl_free_io(io);
13697
13698	return (CTL_RETVAL_COMPLETE);
13699}
13700#endif
13701
13702/*
13703 * Primary command inlet from frontend ports.  All SCSI and task I/O
13704 * requests must go through this function.
13705 */
13706int
13707ctl_queue(union ctl_io *io)
13708{
13709	struct ctl_softc *ctl_softc;
13710
13711	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13712
13713	ctl_softc = control_softc;
13714
13715#ifdef CTL_TIME_IO
13716	io->io_hdr.start_time = time_uptime;
13717	getbintime(&io->io_hdr.start_bt);
13718#endif /* CTL_TIME_IO */
13719
13720	/* Map FE-specific LUN ID into global one. */
13721	io->io_hdr.nexus.targ_mapped_lun =
13722	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13723
13724	switch (io->io_hdr.io_type) {
13725	case CTL_IO_SCSI:
13726	case CTL_IO_TASK:
13727		ctl_enqueue_incoming(io);
13728		break;
13729	default:
13730		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13731		return (EINVAL);
13732	}
13733
13734	return (CTL_RETVAL_COMPLETE);
13735}
13736
13737#ifdef CTL_IO_DELAY
13738static void
13739ctl_done_timer_wakeup(void *arg)
13740{
13741	union ctl_io *io;
13742
13743	io = (union ctl_io *)arg;
13744	ctl_done(io);
13745}
13746#endif /* CTL_IO_DELAY */
13747
13748void
13749ctl_done(union ctl_io *io)
13750{
13751	struct ctl_softc *ctl_softc;
13752
13753	ctl_softc = control_softc;
13754
13755	/*
13756	 * Enable this to catch duplicate completion issues.
13757	 */
13758#if 0
13759	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13760		printf("%s: type %d msg %d cdb %x iptl: "
13761		       "%d:%d:%d:%d tag 0x%04x "
13762		       "flag %#x status %x\n",
13763			__func__,
13764			io->io_hdr.io_type,
13765			io->io_hdr.msg_type,
13766			io->scsiio.cdb[0],
13767			io->io_hdr.nexus.initid.id,
13768			io->io_hdr.nexus.targ_port,
13769			io->io_hdr.nexus.targ_target.id,
13770			io->io_hdr.nexus.targ_lun,
13771			(io->io_hdr.io_type ==
13772			CTL_IO_TASK) ?
13773			io->taskio.tag_num :
13774			io->scsiio.tag_num,
13775		        io->io_hdr.flags,
13776			io->io_hdr.status);
13777	} else
13778		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13779#endif
13780
13781	/*
13782	 * This is an internal copy of an I/O, and should not go through
13783	 * the normal done processing logic.
13784	 */
13785	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13786		return;
13787
13788	/*
13789	 * We need to send a msg to the serializing shelf to finish the IO
13790	 * as well.  We don't send a finish message to the other shelf if
13791	 * this is a task management command.  Task management commands
13792	 * aren't serialized in the OOA queue, but rather just executed on
13793	 * both shelf controllers for commands that originated on that
13794	 * controller.
13795	 */
13796	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13797	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13798		union ctl_ha_msg msg_io;
13799
13800		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13801		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13802		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13803		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13804		}
13805		/* continue on to finish IO */
13806	}
13807#ifdef CTL_IO_DELAY
13808	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13809		struct ctl_lun *lun;
13810
13811		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13812
13813		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13814	} else {
13815		struct ctl_lun *lun;
13816
13817		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13818
13819		if ((lun != NULL)
13820		 && (lun->delay_info.done_delay > 0)) {
13821			struct callout *callout;
13822
13823			callout = (struct callout *)&io->io_hdr.timer_bytes;
13824			callout_init(callout, /*mpsafe*/ 1);
13825			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13826			callout_reset(callout,
13827				      lun->delay_info.done_delay * hz,
13828				      ctl_done_timer_wakeup, io);
13829			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13830				lun->delay_info.done_delay = 0;
13831			return;
13832		}
13833	}
13834#endif /* CTL_IO_DELAY */
13835
13836	ctl_enqueue_done(io);
13837}
13838
13839int
13840ctl_isc(struct ctl_scsiio *ctsio)
13841{
13842	struct ctl_lun *lun;
13843	int retval;
13844
13845	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13846
13847	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13848
13849	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13850
13851	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13852
13853	return (retval);
13854}
13855
13856
13857static void
13858ctl_work_thread(void *arg)
13859{
13860	struct ctl_thread *thr = (struct ctl_thread *)arg;
13861	struct ctl_softc *softc = thr->ctl_softc;
13862	union ctl_io *io;
13863	int retval;
13864
13865	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13866
13867	for (;;) {
13868		retval = 0;
13869
13870		/*
13871		 * We handle the queues in this order:
13872		 * - ISC
13873		 * - done queue (to free up resources, unblock other commands)
13874		 * - RtR queue
13875		 * - incoming queue
13876		 *
13877		 * If those queues are empty, we break out of the loop and
13878		 * go to sleep.
13879		 */
13880		mtx_lock(&thr->queue_lock);
13881		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13882		if (io != NULL) {
13883			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13884			mtx_unlock(&thr->queue_lock);
13885			ctl_handle_isc(io);
13886			continue;
13887		}
13888		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13889		if (io != NULL) {
13890			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13891			/* clear any blocked commands, call fe_done */
13892			mtx_unlock(&thr->queue_lock);
13893			retval = ctl_process_done(io);
13894			continue;
13895		}
13896		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13897		if (io != NULL) {
13898			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13899			mtx_unlock(&thr->queue_lock);
13900			if (io->io_hdr.io_type == CTL_IO_TASK)
13901				ctl_run_task(io);
13902			else
13903				ctl_scsiio_precheck(softc, &io->scsiio);
13904			continue;
13905		}
13906		if (!ctl_pause_rtr) {
13907			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13908			if (io != NULL) {
13909				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13910				mtx_unlock(&thr->queue_lock);
13911				retval = ctl_scsiio(&io->scsiio);
13912				if (retval != CTL_RETVAL_COMPLETE)
13913					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13914				continue;
13915			}
13916		}
13917
13918		/* Sleep until we have something to do. */
13919		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13920	}
13921}
13922
13923static void
13924ctl_lun_thread(void *arg)
13925{
13926	struct ctl_softc *softc = (struct ctl_softc *)arg;
13927	struct ctl_be_lun *be_lun;
13928	int retval;
13929
13930	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13931
13932	for (;;) {
13933		retval = 0;
13934		mtx_lock(&softc->ctl_lock);
13935		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13936		if (be_lun != NULL) {
13937			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13938			mtx_unlock(&softc->ctl_lock);
13939			ctl_create_lun(be_lun);
13940			continue;
13941		}
13942
13943		/* Sleep until we have something to do. */
13944		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13945		    PDROP | PRIBIO, "-", 0);
13946	}
13947}
13948
13949static void
13950ctl_enqueue_incoming(union ctl_io *io)
13951{
13952	struct ctl_softc *softc = control_softc;
13953	struct ctl_thread *thr;
13954	u_int idx;
13955
13956	idx = (io->io_hdr.nexus.targ_port * 127 +
13957	       io->io_hdr.nexus.initid.id) % worker_threads;
13958	thr = &softc->threads[idx];
13959	mtx_lock(&thr->queue_lock);
13960	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13961	mtx_unlock(&thr->queue_lock);
13962	wakeup(thr);
13963}
13964
13965static void
13966ctl_enqueue_rtr(union ctl_io *io)
13967{
13968	struct ctl_softc *softc = control_softc;
13969	struct ctl_thread *thr;
13970
13971	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13972	mtx_lock(&thr->queue_lock);
13973	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13974	mtx_unlock(&thr->queue_lock);
13975	wakeup(thr);
13976}
13977
13978static void
13979ctl_enqueue_done(union ctl_io *io)
13980{
13981	struct ctl_softc *softc = control_softc;
13982	struct ctl_thread *thr;
13983
13984	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13985	mtx_lock(&thr->queue_lock);
13986	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13987	mtx_unlock(&thr->queue_lock);
13988	wakeup(thr);
13989}
13990
13991static void
13992ctl_enqueue_isc(union ctl_io *io)
13993{
13994	struct ctl_softc *softc = control_softc;
13995	struct ctl_thread *thr;
13996
13997	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13998	mtx_lock(&thr->queue_lock);
13999	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14000	mtx_unlock(&thr->queue_lock);
14001	wakeup(thr);
14002}
14003
14004/* Initialization and failover */
14005
14006void
14007ctl_init_isc_msg(void)
14008{
14009	printf("CTL: Still calling this thing\n");
14010}
14011
14012/*
14013 * Init component
14014 * 	Initializes component into configuration defined by bootMode
14015 *	(see hasc-sv.c)
14016 *  	returns hasc_Status:
14017 * 		OK
14018 *		ERROR - fatal error
14019 */
14020static ctl_ha_comp_status
14021ctl_isc_init(struct ctl_ha_component *c)
14022{
14023	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14024
14025	c->status = ret;
14026	return ret;
14027}
14028
14029/* Start component
14030 * 	Starts component in state requested. If component starts successfully,
14031 *	it must set its own state to the requestrd state
14032 *	When requested state is HASC_STATE_HA, the component may refine it
14033 * 	by adding _SLAVE or _MASTER flags.
14034 *	Currently allowed state transitions are:
14035 *	UNKNOWN->HA		- initial startup
14036 *	UNKNOWN->SINGLE - initial startup when no parter detected
14037 *	HA->SINGLE		- failover
14038 * returns ctl_ha_comp_status:
14039 * 		OK	- component successfully started in requested state
14040 *		FAILED  - could not start the requested state, failover may
14041 * 			  be possible
14042 *		ERROR	- fatal error detected, no future startup possible
14043 */
14044static ctl_ha_comp_status
14045ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14046{
14047	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14048
14049	printf("%s: go\n", __func__);
14050
14051	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14052	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14053		ctl_is_single = 0;
14054		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14055		    != CTL_HA_STATUS_SUCCESS) {
14056			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14057			ret = CTL_HA_COMP_STATUS_ERROR;
14058		}
14059	} else if (CTL_HA_STATE_IS_HA(c->state)
14060		&& CTL_HA_STATE_IS_SINGLE(state)){
14061		// HA->SINGLE transition
14062	        ctl_failover();
14063		ctl_is_single = 1;
14064	} else {
14065		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14066		       c->state, state);
14067		ret = CTL_HA_COMP_STATUS_ERROR;
14068	}
14069	if (CTL_HA_STATE_IS_SINGLE(state))
14070		ctl_is_single = 1;
14071
14072	c->state = state;
14073	c->status = ret;
14074	return ret;
14075}
14076
14077/*
14078 * Quiesce component
14079 * The component must clear any error conditions (set status to OK) and
14080 * prepare itself to another Start call
14081 * returns ctl_ha_comp_status:
14082 * 	OK
14083 *	ERROR
14084 */
14085static ctl_ha_comp_status
14086ctl_isc_quiesce(struct ctl_ha_component *c)
14087{
14088	int ret = CTL_HA_COMP_STATUS_OK;
14089
14090	ctl_pause_rtr = 1;
14091	c->status = ret;
14092	return ret;
14093}
14094
14095struct ctl_ha_component ctl_ha_component_ctlisc =
14096{
14097	.name = "CTL ISC",
14098	.state = CTL_HA_STATE_UNKNOWN,
14099	.init = ctl_isc_init,
14100	.start = ctl_isc_start,
14101	.quiesce = ctl_isc_quiesce
14102};
14103
14104/*
14105 *  vim: ts=8
14106 */
14107