ctl.c revision 273075
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 273075 2014-10-14 11:28:25Z 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_debugconf_subpage debugconf_page_default = {
113	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
114	DBGCNF_SUBPAGE_CODE,		/* subpage */
115	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
116	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
117	DBGCNF_VERSION,			/* page_version */
118	{CTL_TIME_IO_DEFAULT_SECS>>8,
119	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
120};
121
122static struct copan_debugconf_subpage debugconf_page_changeable = {
123	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
124	DBGCNF_SUBPAGE_CODE,		/* subpage */
125	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
126	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
127	0,				/* page_version */
128	{0xff,0xff},			/* ctl_time_io_secs */
129};
130
131static struct scsi_da_rw_recovery_page rw_er_page_default = {
132	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
133	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
134	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
135	/*read_retry_count*/0,
136	/*correction_span*/0,
137	/*head_offset_count*/0,
138	/*data_strobe_offset_cnt*/0,
139	/*byte8*/0,
140	/*write_retry_count*/0,
141	/*reserved2*/0,
142	/*recovery_time_limit*/{0, 0},
143};
144
145static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
146	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
147	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
148	/*byte3*/0,
149	/*read_retry_count*/0,
150	/*correction_span*/0,
151	/*head_offset_count*/0,
152	/*data_strobe_offset_cnt*/0,
153	/*byte8*/0,
154	/*write_retry_count*/0,
155	/*reserved2*/0,
156	/*recovery_time_limit*/{0, 0},
157};
158
159static struct scsi_format_page format_page_default = {
160	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
161	/*page_length*/sizeof(struct scsi_format_page) - 2,
162	/*tracks_per_zone*/ {0, 0},
163	/*alt_sectors_per_zone*/ {0, 0},
164	/*alt_tracks_per_zone*/ {0, 0},
165	/*alt_tracks_per_lun*/ {0, 0},
166	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
167			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
168	/*bytes_per_sector*/ {0, 0},
169	/*interleave*/ {0, 0},
170	/*track_skew*/ {0, 0},
171	/*cylinder_skew*/ {0, 0},
172	/*flags*/ SFP_HSEC,
173	/*reserved*/ {0, 0, 0}
174};
175
176static struct scsi_format_page format_page_changeable = {
177	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
178	/*page_length*/sizeof(struct scsi_format_page) - 2,
179	/*tracks_per_zone*/ {0, 0},
180	/*alt_sectors_per_zone*/ {0, 0},
181	/*alt_tracks_per_zone*/ {0, 0},
182	/*alt_tracks_per_lun*/ {0, 0},
183	/*sectors_per_track*/ {0, 0},
184	/*bytes_per_sector*/ {0, 0},
185	/*interleave*/ {0, 0},
186	/*track_skew*/ {0, 0},
187	/*cylinder_skew*/ {0, 0},
188	/*flags*/ 0,
189	/*reserved*/ {0, 0, 0}
190};
191
192static struct scsi_rigid_disk_page rigid_disk_page_default = {
193	/*page_code*/SMS_RIGID_DISK_PAGE,
194	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
195	/*cylinders*/ {0, 0, 0},
196	/*heads*/ CTL_DEFAULT_HEADS,
197	/*start_write_precomp*/ {0, 0, 0},
198	/*start_reduced_current*/ {0, 0, 0},
199	/*step_rate*/ {0, 0},
200	/*landing_zone_cylinder*/ {0, 0, 0},
201	/*rpl*/ SRDP_RPL_DISABLED,
202	/*rotational_offset*/ 0,
203	/*reserved1*/ 0,
204	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
205			   CTL_DEFAULT_ROTATION_RATE & 0xff},
206	/*reserved2*/ {0, 0}
207};
208
209static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
210	/*page_code*/SMS_RIGID_DISK_PAGE,
211	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
212	/*cylinders*/ {0, 0, 0},
213	/*heads*/ 0,
214	/*start_write_precomp*/ {0, 0, 0},
215	/*start_reduced_current*/ {0, 0, 0},
216	/*step_rate*/ {0, 0},
217	/*landing_zone_cylinder*/ {0, 0, 0},
218	/*rpl*/ 0,
219	/*rotational_offset*/ 0,
220	/*reserved1*/ 0,
221	/*rotation_rate*/ {0, 0},
222	/*reserved2*/ {0, 0}
223};
224
225static struct scsi_caching_page caching_page_default = {
226	/*page_code*/SMS_CACHING_PAGE,
227	/*page_length*/sizeof(struct scsi_caching_page) - 2,
228	/*flags1*/ SCP_DISC | SCP_WCE,
229	/*ret_priority*/ 0,
230	/*disable_pf_transfer_len*/ {0xff, 0xff},
231	/*min_prefetch*/ {0, 0},
232	/*max_prefetch*/ {0xff, 0xff},
233	/*max_pf_ceiling*/ {0xff, 0xff},
234	/*flags2*/ 0,
235	/*cache_segments*/ 0,
236	/*cache_seg_size*/ {0, 0},
237	/*reserved*/ 0,
238	/*non_cache_seg_size*/ {0, 0, 0}
239};
240
241static struct scsi_caching_page caching_page_changeable = {
242	/*page_code*/SMS_CACHING_PAGE,
243	/*page_length*/sizeof(struct scsi_caching_page) - 2,
244	/*flags1*/ SCP_WCE | SCP_RCD,
245	/*ret_priority*/ 0,
246	/*disable_pf_transfer_len*/ {0, 0},
247	/*min_prefetch*/ {0, 0},
248	/*max_prefetch*/ {0, 0},
249	/*max_pf_ceiling*/ {0, 0},
250	/*flags2*/ 0,
251	/*cache_segments*/ 0,
252	/*cache_seg_size*/ {0, 0},
253	/*reserved*/ 0,
254	/*non_cache_seg_size*/ {0, 0, 0}
255};
256
257static struct scsi_control_page control_page_default = {
258	/*page_code*/SMS_CONTROL_MODE_PAGE,
259	/*page_length*/sizeof(struct scsi_control_page) - 2,
260	/*rlec*/0,
261	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
262	/*eca_and_aen*/0,
263	/*flags4*/SCP_TAS,
264	/*aen_holdoff_period*/{0, 0},
265	/*busy_timeout_period*/{0, 0},
266	/*extended_selftest_completion_time*/{0, 0}
267};
268
269static struct scsi_control_page control_page_changeable = {
270	/*page_code*/SMS_CONTROL_MODE_PAGE,
271	/*page_length*/sizeof(struct scsi_control_page) - 2,
272	/*rlec*/SCP_DSENSE,
273	/*queue_flags*/SCP_QUEUE_ALG_MASK,
274	/*eca_and_aen*/SCP_SWP,
275	/*flags4*/0,
276	/*aen_holdoff_period*/{0, 0},
277	/*busy_timeout_period*/{0, 0},
278	/*extended_selftest_completion_time*/{0, 0}
279};
280
281static struct scsi_info_exceptions_page ie_page_default = {
282	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
283	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
284	/*info_flags*/SIEP_FLAGS_DEXCPT,
285	/*mrie*/0,
286	/*interval_timer*/{0, 0, 0, 0},
287	/*report_count*/{0, 0, 0, 0}
288};
289
290static struct scsi_info_exceptions_page ie_page_changeable = {
291	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
292	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
293	/*info_flags*/0,
294	/*mrie*/0,
295	/*interval_timer*/{0, 0, 0, 0},
296	/*report_count*/{0, 0, 0, 0}
297};
298
299static struct scsi_logical_block_provisioning_page lbp_page_default = {
300	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
301	/*subpage_code*/0x02,
302	/*page_length*/{0, sizeof(struct scsi_logical_block_provisioning_page) - 4},
303	/*flags*/0,
304	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
305	/*descr*/{}
306};
307
308static struct scsi_logical_block_provisioning_page lbp_page_changeable = {
309	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
310	/*subpage_code*/0x02,
311	/*page_length*/{0, sizeof(struct scsi_logical_block_provisioning_page) - 4},
312	/*flags*/0,
313	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
314	/*descr*/{}
315};
316
317/*
318 * XXX KDM move these into the softc.
319 */
320static int rcv_sync_msg;
321static int persis_offset;
322static uint8_t ctl_pause_rtr;
323static int     ctl_is_single = 1;
324
325SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
326static int worker_threads = -1;
327SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
328    &worker_threads, 1, "Number of worker threads");
329static int verbose = 0;
330SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
331    &verbose, 0, "Show SCSI errors returned to initiator");
332
333/*
334 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
335 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
336 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
337 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
338 */
339#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
340
341static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
342				  int param);
343static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
344static int ctl_init(void);
345void ctl_shutdown(void);
346static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
347static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
348static void ctl_ioctl_online(void *arg);
349static void ctl_ioctl_offline(void *arg);
350static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
351static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
352static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
353static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
354static int ctl_ioctl_submit_wait(union ctl_io *io);
355static void ctl_ioctl_datamove(union ctl_io *io);
356static void ctl_ioctl_done(union ctl_io *io);
357static void ctl_ioctl_hard_startstop_callback(void *arg,
358					      struct cfi_metatask *metatask);
359static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
360static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
361			      struct ctl_ooa *ooa_hdr,
362			      struct ctl_ooa_entry *kern_entries);
363static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
364		     struct thread *td);
365static uint32_t ctl_map_lun(int port_num, uint32_t lun);
366static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
367#ifdef unused
368static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
369				   uint32_t targ_target, uint32_t targ_lun,
370				   int can_wait);
371static void ctl_kfree_io(union ctl_io *io);
372#endif /* unused */
373static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
374			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
375static int ctl_free_lun(struct ctl_lun *lun);
376static void ctl_create_lun(struct ctl_be_lun *be_lun);
377/**
378static void ctl_failover_change_pages(struct ctl_softc *softc,
379				      struct ctl_scsiio *ctsio, int master);
380**/
381
382static int ctl_do_mode_select(union ctl_io *io);
383static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
384			   uint64_t res_key, uint64_t sa_res_key,
385			   uint8_t type, uint32_t residx,
386			   struct ctl_scsiio *ctsio,
387			   struct scsi_per_res_out *cdb,
388			   struct scsi_per_res_out_parms* param);
389static void ctl_pro_preempt_other(struct ctl_lun *lun,
390				  union ctl_ha_msg *msg);
391static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
392static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
393static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
394static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
395static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
396static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
397static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
398					 int alloc_len);
399static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
400					 int alloc_len);
401static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
402static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
403static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
404static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
405static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
406static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
407static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
408    union ctl_io *pending_io, union ctl_io *ooa_io);
409static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
410				union ctl_io *starting_io);
411static int ctl_check_blocked(struct ctl_lun *lun);
412static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
413				struct ctl_lun *lun,
414				const struct ctl_cmd_entry *entry,
415				struct ctl_scsiio *ctsio);
416//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
417static void ctl_failover(void);
418static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
419			       struct ctl_scsiio *ctsio);
420static int ctl_scsiio(struct ctl_scsiio *ctsio);
421
422static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
423static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
424			    ctl_ua_type ua_type);
425static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
426			 ctl_ua_type ua_type);
427static int ctl_abort_task(union ctl_io *io);
428static int ctl_abort_task_set(union ctl_io *io);
429static int ctl_i_t_nexus_reset(union ctl_io *io);
430static void ctl_run_task(union ctl_io *io);
431#ifdef CTL_IO_DELAY
432static void ctl_datamove_timer_wakeup(void *arg);
433static void ctl_done_timer_wakeup(void *arg);
434#endif /* CTL_IO_DELAY */
435
436static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
437static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
438static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
439static void ctl_datamove_remote_write(union ctl_io *io);
440static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
441static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
442static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
443static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
444				    ctl_ha_dt_cb callback);
445static void ctl_datamove_remote_read(union ctl_io *io);
446static void ctl_datamove_remote(union ctl_io *io);
447static int ctl_process_done(union ctl_io *io);
448static void ctl_lun_thread(void *arg);
449static void ctl_work_thread(void *arg);
450static void ctl_enqueue_incoming(union ctl_io *io);
451static void ctl_enqueue_rtr(union ctl_io *io);
452static void ctl_enqueue_done(union ctl_io *io);
453static void ctl_enqueue_isc(union ctl_io *io);
454static const struct ctl_cmd_entry *
455    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
456static const struct ctl_cmd_entry *
457    ctl_validate_command(struct ctl_scsiio *ctsio);
458static int ctl_cmd_applicable(uint8_t lun_type,
459    const struct ctl_cmd_entry *entry);
460
461/*
462 * Load the serialization table.  This isn't very pretty, but is probably
463 * the easiest way to do it.
464 */
465#include "ctl_ser_table.c"
466
467/*
468 * We only need to define open, close and ioctl routines for this driver.
469 */
470static struct cdevsw ctl_cdevsw = {
471	.d_version =	D_VERSION,
472	.d_flags =	0,
473	.d_open =	ctl_open,
474	.d_close =	ctl_close,
475	.d_ioctl =	ctl_ioctl,
476	.d_name =	"ctl",
477};
478
479
480MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
481MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
482
483static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
484
485static moduledata_t ctl_moduledata = {
486	"ctl",
487	ctl_module_event_handler,
488	NULL
489};
490
491DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
492MODULE_VERSION(ctl, 1);
493
494static struct ctl_frontend ioctl_frontend =
495{
496	.name = "ioctl",
497};
498
499static void
500ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
501			    union ctl_ha_msg *msg_info)
502{
503	struct ctl_scsiio *ctsio;
504
505	if (msg_info->hdr.original_sc == NULL) {
506		printf("%s: original_sc == NULL!\n", __func__);
507		/* XXX KDM now what? */
508		return;
509	}
510
511	ctsio = &msg_info->hdr.original_sc->scsiio;
512	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
513	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
514	ctsio->io_hdr.status = msg_info->hdr.status;
515	ctsio->scsi_status = msg_info->scsi.scsi_status;
516	ctsio->sense_len = msg_info->scsi.sense_len;
517	ctsio->sense_residual = msg_info->scsi.sense_residual;
518	ctsio->residual = msg_info->scsi.residual;
519	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
520	       sizeof(ctsio->sense_data));
521	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
522	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
523	ctl_enqueue_isc((union ctl_io *)ctsio);
524}
525
526static void
527ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
528				union ctl_ha_msg *msg_info)
529{
530	struct ctl_scsiio *ctsio;
531
532	if (msg_info->hdr.serializing_sc == NULL) {
533		printf("%s: serializing_sc == NULL!\n", __func__);
534		/* XXX KDM now what? */
535		return;
536	}
537
538	ctsio = &msg_info->hdr.serializing_sc->scsiio;
539#if 0
540	/*
541	 * Attempt to catch the situation where an I/O has
542	 * been freed, and we're using it again.
543	 */
544	if (ctsio->io_hdr.io_type == 0xff) {
545		union ctl_io *tmp_io;
546		tmp_io = (union ctl_io *)ctsio;
547		printf("%s: %p use after free!\n", __func__,
548		       ctsio);
549		printf("%s: type %d msg %d cdb %x iptl: "
550		       "%d:%d:%d:%d tag 0x%04x "
551		       "flag %#x status %x\n",
552			__func__,
553			tmp_io->io_hdr.io_type,
554			tmp_io->io_hdr.msg_type,
555			tmp_io->scsiio.cdb[0],
556			tmp_io->io_hdr.nexus.initid.id,
557			tmp_io->io_hdr.nexus.targ_port,
558			tmp_io->io_hdr.nexus.targ_target.id,
559			tmp_io->io_hdr.nexus.targ_lun,
560			(tmp_io->io_hdr.io_type ==
561			CTL_IO_TASK) ?
562			tmp_io->taskio.tag_num :
563			tmp_io->scsiio.tag_num,
564		        tmp_io->io_hdr.flags,
565			tmp_io->io_hdr.status);
566	}
567#endif
568	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
569	ctl_enqueue_isc((union ctl_io *)ctsio);
570}
571
572/*
573 * ISC (Inter Shelf Communication) event handler.  Events from the HA
574 * subsystem come in here.
575 */
576static void
577ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
578{
579	struct ctl_softc *ctl_softc;
580	union ctl_io *io;
581	struct ctl_prio *presio;
582	ctl_ha_status isc_status;
583
584	ctl_softc = control_softc;
585	io = NULL;
586
587
588#if 0
589	printf("CTL: Isc Msg event %d\n", event);
590#endif
591	if (event == CTL_HA_EVT_MSG_RECV) {
592		union ctl_ha_msg msg_info;
593
594		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
595					     sizeof(msg_info), /*wait*/ 0);
596#if 0
597		printf("CTL: msg_type %d\n", msg_info.msg_type);
598#endif
599		if (isc_status != 0) {
600			printf("Error receiving message, status = %d\n",
601			       isc_status);
602			return;
603		}
604
605		switch (msg_info.hdr.msg_type) {
606		case CTL_MSG_SERIALIZE:
607#if 0
608			printf("Serialize\n");
609#endif
610			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
611			if (io == NULL) {
612				printf("ctl_isc_event_handler: can't allocate "
613				       "ctl_io!\n");
614				/* Bad Juju */
615				/* Need to set busy and send msg back */
616				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
617				msg_info.hdr.status = CTL_SCSI_ERROR;
618				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
619				msg_info.scsi.sense_len = 0;
620			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
621				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
622				}
623				goto bailout;
624			}
625			ctl_zero_io(io);
626			// populate ctsio from msg_info
627			io->io_hdr.io_type = CTL_IO_SCSI;
628			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
629			io->io_hdr.original_sc = msg_info.hdr.original_sc;
630#if 0
631			printf("pOrig %x\n", (int)msg_info.original_sc);
632#endif
633			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
634					    CTL_FLAG_IO_ACTIVE;
635			/*
636			 * If we're in serialization-only mode, we don't
637			 * want to go through full done processing.  Thus
638			 * the COPY flag.
639			 *
640			 * XXX KDM add another flag that is more specific.
641			 */
642			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
643				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
644			io->io_hdr.nexus = msg_info.hdr.nexus;
645#if 0
646			printf("targ %d, port %d, iid %d, lun %d\n",
647			       io->io_hdr.nexus.targ_target.id,
648			       io->io_hdr.nexus.targ_port,
649			       io->io_hdr.nexus.initid.id,
650			       io->io_hdr.nexus.targ_lun);
651#endif
652			io->scsiio.tag_num = msg_info.scsi.tag_num;
653			io->scsiio.tag_type = msg_info.scsi.tag_type;
654			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
655			       CTL_MAX_CDBLEN);
656			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
657				const struct ctl_cmd_entry *entry;
658
659				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
660				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
661				io->io_hdr.flags |=
662					entry->flags & CTL_FLAG_DATA_MASK;
663			}
664			ctl_enqueue_isc(io);
665			break;
666
667		/* Performed on the Originating SC, XFER mode only */
668		case CTL_MSG_DATAMOVE: {
669			struct ctl_sg_entry *sgl;
670			int i, j;
671
672			io = msg_info.hdr.original_sc;
673			if (io == NULL) {
674				printf("%s: original_sc == NULL!\n", __func__);
675				/* XXX KDM do something here */
676				break;
677			}
678			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
679			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
680			/*
681			 * Keep track of this, we need to send it back over
682			 * when the datamove is complete.
683			 */
684			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
685
686			if (msg_info.dt.sg_sequence == 0) {
687				/*
688				 * XXX KDM we use the preallocated S/G list
689				 * here, but we'll need to change this to
690				 * dynamic allocation if we need larger S/G
691				 * lists.
692				 */
693				if (msg_info.dt.kern_sg_entries >
694				    sizeof(io->io_hdr.remote_sglist) /
695				    sizeof(io->io_hdr.remote_sglist[0])) {
696					printf("%s: number of S/G entries "
697					    "needed %u > allocated num %zd\n",
698					    __func__,
699					    msg_info.dt.kern_sg_entries,
700					    sizeof(io->io_hdr.remote_sglist)/
701					    sizeof(io->io_hdr.remote_sglist[0]));
702
703					/*
704					 * XXX KDM send a message back to
705					 * the other side to shut down the
706					 * DMA.  The error will come back
707					 * through via the normal channel.
708					 */
709					break;
710				}
711				sgl = io->io_hdr.remote_sglist;
712				memset(sgl, 0,
713				       sizeof(io->io_hdr.remote_sglist));
714
715				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
716
717				io->scsiio.kern_sg_entries =
718					msg_info.dt.kern_sg_entries;
719				io->scsiio.rem_sg_entries =
720					msg_info.dt.kern_sg_entries;
721				io->scsiio.kern_data_len =
722					msg_info.dt.kern_data_len;
723				io->scsiio.kern_total_len =
724					msg_info.dt.kern_total_len;
725				io->scsiio.kern_data_resid =
726					msg_info.dt.kern_data_resid;
727				io->scsiio.kern_rel_offset =
728					msg_info.dt.kern_rel_offset;
729				/*
730				 * Clear out per-DMA flags.
731				 */
732				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
733				/*
734				 * Add per-DMA flags that are set for this
735				 * particular DMA request.
736				 */
737				io->io_hdr.flags |= msg_info.dt.flags &
738						    CTL_FLAG_RDMA_MASK;
739			} else
740				sgl = (struct ctl_sg_entry *)
741					io->scsiio.kern_data_ptr;
742
743			for (i = msg_info.dt.sent_sg_entries, j = 0;
744			     i < (msg_info.dt.sent_sg_entries +
745			     msg_info.dt.cur_sg_entries); i++, j++) {
746				sgl[i].addr = msg_info.dt.sg_list[j].addr;
747				sgl[i].len = msg_info.dt.sg_list[j].len;
748
749#if 0
750				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
751				       __func__,
752				       msg_info.dt.sg_list[j].addr,
753				       msg_info.dt.sg_list[j].len,
754				       sgl[i].addr, sgl[i].len, j, i);
755#endif
756			}
757#if 0
758			memcpy(&sgl[msg_info.dt.sent_sg_entries],
759			       msg_info.dt.sg_list,
760			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
761#endif
762
763			/*
764			 * If this is the last piece of the I/O, we've got
765			 * the full S/G list.  Queue processing in the thread.
766			 * Otherwise wait for the next piece.
767			 */
768			if (msg_info.dt.sg_last != 0)
769				ctl_enqueue_isc(io);
770			break;
771		}
772		/* Performed on the Serializing (primary) SC, XFER mode only */
773		case CTL_MSG_DATAMOVE_DONE: {
774			if (msg_info.hdr.serializing_sc == NULL) {
775				printf("%s: serializing_sc == NULL!\n",
776				       __func__);
777				/* XXX KDM now what? */
778				break;
779			}
780			/*
781			 * We grab the sense information here in case
782			 * there was a failure, so we can return status
783			 * back to the initiator.
784			 */
785			io = msg_info.hdr.serializing_sc;
786			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
787			io->io_hdr.status = msg_info.hdr.status;
788			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
789			io->scsiio.sense_len = msg_info.scsi.sense_len;
790			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
791			io->io_hdr.port_status = msg_info.scsi.fetd_status;
792			io->scsiio.residual = msg_info.scsi.residual;
793			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
794			       sizeof(io->scsiio.sense_data));
795			ctl_enqueue_isc(io);
796			break;
797		}
798
799		/* Preformed on Originating SC, SER_ONLY mode */
800		case CTL_MSG_R2R:
801			io = msg_info.hdr.original_sc;
802			if (io == NULL) {
803				printf("%s: Major Bummer\n", __func__);
804				return;
805			} else {
806#if 0
807				printf("pOrig %x\n",(int) ctsio);
808#endif
809			}
810			io->io_hdr.msg_type = CTL_MSG_R2R;
811			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
812			ctl_enqueue_isc(io);
813			break;
814
815		/*
816		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
817		 * mode.
818		 * Performed on the Originating (i.e. secondary) SC in XFER
819		 * mode
820		 */
821		case CTL_MSG_FINISH_IO:
822			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
823				ctl_isc_handler_finish_xfer(ctl_softc,
824							    &msg_info);
825			else
826				ctl_isc_handler_finish_ser_only(ctl_softc,
827								&msg_info);
828			break;
829
830		/* Preformed on Originating SC */
831		case CTL_MSG_BAD_JUJU:
832			io = msg_info.hdr.original_sc;
833			if (io == NULL) {
834				printf("%s: Bad JUJU!, original_sc is NULL!\n",
835				       __func__);
836				break;
837			}
838			ctl_copy_sense_data(&msg_info, io);
839			/*
840			 * IO should have already been cleaned up on other
841			 * SC so clear this flag so we won't send a message
842			 * back to finish the IO there.
843			 */
844			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
845			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
846
847			/* io = msg_info.hdr.serializing_sc; */
848			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
849			ctl_enqueue_isc(io);
850			break;
851
852		/* Handle resets sent from the other side */
853		case CTL_MSG_MANAGE_TASKS: {
854			struct ctl_taskio *taskio;
855			taskio = (struct ctl_taskio *)ctl_alloc_io(
856				(void *)ctl_softc->othersc_pool);
857			if (taskio == NULL) {
858				printf("ctl_isc_event_handler: can't allocate "
859				       "ctl_io!\n");
860				/* Bad Juju */
861				/* should I just call the proper reset func
862				   here??? */
863				goto bailout;
864			}
865			ctl_zero_io((union ctl_io *)taskio);
866			taskio->io_hdr.io_type = CTL_IO_TASK;
867			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
868			taskio->io_hdr.nexus = msg_info.hdr.nexus;
869			taskio->task_action = msg_info.task.task_action;
870			taskio->tag_num = msg_info.task.tag_num;
871			taskio->tag_type = msg_info.task.tag_type;
872#ifdef CTL_TIME_IO
873			taskio->io_hdr.start_time = time_uptime;
874			getbintime(&taskio->io_hdr.start_bt);
875#if 0
876			cs_prof_gettime(&taskio->io_hdr.start_ticks);
877#endif
878#endif /* CTL_TIME_IO */
879			ctl_run_task((union ctl_io *)taskio);
880			break;
881		}
882		/* Persistent Reserve action which needs attention */
883		case CTL_MSG_PERS_ACTION:
884			presio = (struct ctl_prio *)ctl_alloc_io(
885				(void *)ctl_softc->othersc_pool);
886			if (presio == NULL) {
887				printf("ctl_isc_event_handler: can't allocate "
888				       "ctl_io!\n");
889				/* Bad Juju */
890				/* Need to set busy and send msg back */
891				goto bailout;
892			}
893			ctl_zero_io((union ctl_io *)presio);
894			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
895			presio->pr_msg = msg_info.pr;
896			ctl_enqueue_isc((union ctl_io *)presio);
897			break;
898		case CTL_MSG_SYNC_FE:
899			rcv_sync_msg = 1;
900			break;
901		default:
902		        printf("How did I get here?\n");
903		}
904	} else if (event == CTL_HA_EVT_MSG_SENT) {
905		if (param != CTL_HA_STATUS_SUCCESS) {
906			printf("Bad status from ctl_ha_msg_send status %d\n",
907			       param);
908		}
909		return;
910	} else if (event == CTL_HA_EVT_DISCONNECT) {
911		printf("CTL: Got a disconnect from Isc\n");
912		return;
913	} else {
914		printf("ctl_isc_event_handler: Unknown event %d\n", event);
915		return;
916	}
917
918bailout:
919	return;
920}
921
922static void
923ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
924{
925	struct scsi_sense_data *sense;
926
927	sense = &dest->scsiio.sense_data;
928	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
929	dest->scsiio.scsi_status = src->scsi.scsi_status;
930	dest->scsiio.sense_len = src->scsi.sense_len;
931	dest->io_hdr.status = src->hdr.status;
932}
933
934static int
935ctl_init(void)
936{
937	struct ctl_softc *softc;
938	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
939	struct ctl_port *port;
940        uint8_t sc_id =0;
941	int i, error, retval;
942	//int isc_retval;
943
944	retval = 0;
945	ctl_pause_rtr = 0;
946        rcv_sync_msg = 0;
947
948	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
949			       M_WAITOK | M_ZERO);
950	softc = control_softc;
951
952	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
953			      "cam/ctl");
954
955	softc->dev->si_drv1 = softc;
956
957	/*
958	 * By default, return a "bad LUN" peripheral qualifier for unknown
959	 * LUNs.  The user can override this default using the tunable or
960	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
961	 */
962	softc->inquiry_pq_no_lun = 1;
963	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
964			  &softc->inquiry_pq_no_lun);
965	sysctl_ctx_init(&softc->sysctl_ctx);
966	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
967		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
968		CTLFLAG_RD, 0, "CAM Target Layer");
969
970	if (softc->sysctl_tree == NULL) {
971		printf("%s: unable to allocate sysctl tree\n", __func__);
972		destroy_dev(softc->dev);
973		free(control_softc, M_DEVBUF);
974		control_softc = NULL;
975		return (ENOMEM);
976	}
977
978	SYSCTL_ADD_INT(&softc->sysctl_ctx,
979		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
980		       "inquiry_pq_no_lun", CTLFLAG_RW,
981		       &softc->inquiry_pq_no_lun, 0,
982		       "Report no lun possible for invalid LUNs");
983
984	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
985	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
986	softc->open_count = 0;
987
988	/*
989	 * Default to actually sending a SYNCHRONIZE CACHE command down to
990	 * the drive.
991	 */
992	softc->flags = CTL_FLAG_REAL_SYNC;
993
994	/*
995	 * In Copan's HA scheme, the "master" and "slave" roles are
996	 * figured out through the slot the controller is in.  Although it
997	 * is an active/active system, someone has to be in charge.
998 	 */
999#ifdef NEEDTOPORT
1000        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1001#endif
1002
1003        if (sc_id == 0) {
1004		softc->flags |= CTL_FLAG_MASTER_SHELF;
1005		persis_offset = 0;
1006	} else
1007		persis_offset = CTL_MAX_INITIATORS;
1008
1009	/*
1010	 * XXX KDM need to figure out where we want to get our target ID
1011	 * and WWID.  Is it different on each port?
1012	 */
1013	softc->target.id = 0;
1014	softc->target.wwid[0] = 0x12345678;
1015	softc->target.wwid[1] = 0x87654321;
1016	STAILQ_INIT(&softc->lun_list);
1017	STAILQ_INIT(&softc->pending_lun_queue);
1018	STAILQ_INIT(&softc->fe_list);
1019	STAILQ_INIT(&softc->port_list);
1020	STAILQ_INIT(&softc->be_list);
1021	STAILQ_INIT(&softc->io_pools);
1022	ctl_tpc_init(softc);
1023
1024	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1025			    &internal_pool)!= 0){
1026		printf("ctl: can't allocate %d entry internal pool, "
1027		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1028		return (ENOMEM);
1029	}
1030
1031	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1032			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1033		printf("ctl: can't allocate %d entry emergency pool, "
1034		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1035		ctl_pool_free(internal_pool);
1036		return (ENOMEM);
1037	}
1038
1039	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1040	                    &other_pool) != 0)
1041	{
1042		printf("ctl: can't allocate %d entry other SC pool, "
1043		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1044		ctl_pool_free(internal_pool);
1045		ctl_pool_free(emergency_pool);
1046		return (ENOMEM);
1047	}
1048
1049	softc->internal_pool = internal_pool;
1050	softc->emergency_pool = emergency_pool;
1051	softc->othersc_pool = other_pool;
1052
1053	if (worker_threads <= 0)
1054		worker_threads = max(1, mp_ncpus / 4);
1055	if (worker_threads > CTL_MAX_THREADS)
1056		worker_threads = CTL_MAX_THREADS;
1057
1058	for (i = 0; i < worker_threads; i++) {
1059		struct ctl_thread *thr = &softc->threads[i];
1060
1061		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1062		thr->ctl_softc = softc;
1063		STAILQ_INIT(&thr->incoming_queue);
1064		STAILQ_INIT(&thr->rtr_queue);
1065		STAILQ_INIT(&thr->done_queue);
1066		STAILQ_INIT(&thr->isc_queue);
1067
1068		error = kproc_kthread_add(ctl_work_thread, thr,
1069		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1070		if (error != 0) {
1071			printf("error creating CTL work thread!\n");
1072			ctl_pool_free(internal_pool);
1073			ctl_pool_free(emergency_pool);
1074			ctl_pool_free(other_pool);
1075			return (error);
1076		}
1077	}
1078	error = kproc_kthread_add(ctl_lun_thread, softc,
1079	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1080	if (error != 0) {
1081		printf("error creating CTL lun thread!\n");
1082		ctl_pool_free(internal_pool);
1083		ctl_pool_free(emergency_pool);
1084		ctl_pool_free(other_pool);
1085		return (error);
1086	}
1087	if (bootverbose)
1088		printf("ctl: CAM Target Layer loaded\n");
1089
1090	/*
1091	 * Initialize the ioctl front end.
1092	 */
1093	ctl_frontend_register(&ioctl_frontend);
1094	port = &softc->ioctl_info.port;
1095	port->frontend = &ioctl_frontend;
1096	sprintf(softc->ioctl_info.port_name, "ioctl");
1097	port->port_type = CTL_PORT_IOCTL;
1098	port->num_requested_ctl_io = 100;
1099	port->port_name = softc->ioctl_info.port_name;
1100	port->port_online = ctl_ioctl_online;
1101	port->port_offline = ctl_ioctl_offline;
1102	port->onoff_arg = &softc->ioctl_info;
1103	port->lun_enable = ctl_ioctl_lun_enable;
1104	port->lun_disable = ctl_ioctl_lun_disable;
1105	port->targ_lun_arg = &softc->ioctl_info;
1106	port->fe_datamove = ctl_ioctl_datamove;
1107	port->fe_done = ctl_ioctl_done;
1108	port->max_targets = 15;
1109	port->max_target_id = 15;
1110
1111	if (ctl_port_register(&softc->ioctl_info.port,
1112	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1113		printf("ctl: ioctl front end registration failed, will "
1114		       "continue anyway\n");
1115	}
1116
1117#ifdef CTL_IO_DELAY
1118	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1119		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1120		       sizeof(struct callout), CTL_TIMER_BYTES);
1121		return (EINVAL);
1122	}
1123#endif /* CTL_IO_DELAY */
1124
1125	return (0);
1126}
1127
1128void
1129ctl_shutdown(void)
1130{
1131	struct ctl_softc *softc;
1132	struct ctl_lun *lun, *next_lun;
1133	struct ctl_io_pool *pool;
1134
1135	softc = (struct ctl_softc *)control_softc;
1136
1137	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1138		printf("ctl: ioctl front end deregistration failed\n");
1139
1140	mtx_lock(&softc->ctl_lock);
1141
1142	/*
1143	 * Free up each LUN.
1144	 */
1145	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1146		next_lun = STAILQ_NEXT(lun, links);
1147		ctl_free_lun(lun);
1148	}
1149
1150	mtx_unlock(&softc->ctl_lock);
1151
1152	ctl_frontend_deregister(&ioctl_frontend);
1153
1154	/*
1155	 * This will rip the rug out from under any FETDs or anyone else
1156	 * that has a pool allocated.  Since we increment our module
1157	 * refcount any time someone outside the main CTL module allocates
1158	 * a pool, we shouldn't have any problems here.  The user won't be
1159	 * able to unload the CTL module until client modules have
1160	 * successfully unloaded.
1161	 */
1162	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1163		ctl_pool_free(pool);
1164
1165#if 0
1166	ctl_shutdown_thread(softc->work_thread);
1167	mtx_destroy(&softc->queue_lock);
1168#endif
1169
1170	ctl_tpc_shutdown(softc);
1171	mtx_destroy(&softc->pool_lock);
1172	mtx_destroy(&softc->ctl_lock);
1173
1174	destroy_dev(softc->dev);
1175
1176	sysctl_ctx_free(&softc->sysctl_ctx);
1177
1178	free(control_softc, M_DEVBUF);
1179	control_softc = NULL;
1180
1181	if (bootverbose)
1182		printf("ctl: CAM Target Layer unloaded\n");
1183}
1184
1185static int
1186ctl_module_event_handler(module_t mod, int what, void *arg)
1187{
1188
1189	switch (what) {
1190	case MOD_LOAD:
1191		return (ctl_init());
1192	case MOD_UNLOAD:
1193		return (EBUSY);
1194	default:
1195		return (EOPNOTSUPP);
1196	}
1197}
1198
1199/*
1200 * XXX KDM should we do some access checks here?  Bump a reference count to
1201 * prevent a CTL module from being unloaded while someone has it open?
1202 */
1203static int
1204ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1205{
1206	return (0);
1207}
1208
1209static int
1210ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1211{
1212	return (0);
1213}
1214
1215int
1216ctl_port_enable(ctl_port_type port_type)
1217{
1218	struct ctl_softc *softc;
1219	struct ctl_port *port;
1220
1221	if (ctl_is_single == 0) {
1222		union ctl_ha_msg msg_info;
1223		int isc_retval;
1224
1225#if 0
1226		printf("%s: HA mode, synchronizing frontend enable\n",
1227		        __func__);
1228#endif
1229		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1230	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1231		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1232			printf("Sync msg send error retval %d\n", isc_retval);
1233		}
1234		if (!rcv_sync_msg) {
1235			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1236			        sizeof(msg_info), 1);
1237		}
1238#if 0
1239        	printf("CTL:Frontend Enable\n");
1240	} else {
1241		printf("%s: single mode, skipping frontend synchronization\n",
1242		        __func__);
1243#endif
1244	}
1245
1246	softc = control_softc;
1247
1248	STAILQ_FOREACH(port, &softc->port_list, links) {
1249		if (port_type & port->port_type)
1250		{
1251#if 0
1252			printf("port %d\n", port->targ_port);
1253#endif
1254			ctl_port_online(port);
1255		}
1256	}
1257
1258	return (0);
1259}
1260
1261int
1262ctl_port_disable(ctl_port_type port_type)
1263{
1264	struct ctl_softc *softc;
1265	struct ctl_port *port;
1266
1267	softc = control_softc;
1268
1269	STAILQ_FOREACH(port, &softc->port_list, links) {
1270		if (port_type & port->port_type)
1271			ctl_port_offline(port);
1272	}
1273
1274	return (0);
1275}
1276
1277/*
1278 * Returns 0 for success, 1 for failure.
1279 * Currently the only failure mode is if there aren't enough entries
1280 * allocated.  So, in case of a failure, look at num_entries_dropped,
1281 * reallocate and try again.
1282 */
1283int
1284ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1285	      int *num_entries_filled, int *num_entries_dropped,
1286	      ctl_port_type port_type, int no_virtual)
1287{
1288	struct ctl_softc *softc;
1289	struct ctl_port *port;
1290	int entries_dropped, entries_filled;
1291	int retval;
1292	int i;
1293
1294	softc = control_softc;
1295
1296	retval = 0;
1297	entries_filled = 0;
1298	entries_dropped = 0;
1299
1300	i = 0;
1301	mtx_lock(&softc->ctl_lock);
1302	STAILQ_FOREACH(port, &softc->port_list, links) {
1303		struct ctl_port_entry *entry;
1304
1305		if ((port->port_type & port_type) == 0)
1306			continue;
1307
1308		if ((no_virtual != 0)
1309		 && (port->virtual_port != 0))
1310			continue;
1311
1312		if (entries_filled >= num_entries_alloced) {
1313			entries_dropped++;
1314			continue;
1315		}
1316		entry = &entries[i];
1317
1318		entry->port_type = port->port_type;
1319		strlcpy(entry->port_name, port->port_name,
1320			sizeof(entry->port_name));
1321		entry->physical_port = port->physical_port;
1322		entry->virtual_port = port->virtual_port;
1323		entry->wwnn = port->wwnn;
1324		entry->wwpn = port->wwpn;
1325
1326		i++;
1327		entries_filled++;
1328	}
1329
1330	mtx_unlock(&softc->ctl_lock);
1331
1332	if (entries_dropped > 0)
1333		retval = 1;
1334
1335	*num_entries_dropped = entries_dropped;
1336	*num_entries_filled = entries_filled;
1337
1338	return (retval);
1339}
1340
1341static void
1342ctl_ioctl_online(void *arg)
1343{
1344	struct ctl_ioctl_info *ioctl_info;
1345
1346	ioctl_info = (struct ctl_ioctl_info *)arg;
1347
1348	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1349}
1350
1351static void
1352ctl_ioctl_offline(void *arg)
1353{
1354	struct ctl_ioctl_info *ioctl_info;
1355
1356	ioctl_info = (struct ctl_ioctl_info *)arg;
1357
1358	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1359}
1360
1361/*
1362 * Remove an initiator by port number and initiator ID.
1363 * Returns 0 for success, -1 for failure.
1364 */
1365int
1366ctl_remove_initiator(struct ctl_port *port, int iid)
1367{
1368	struct ctl_softc *softc = control_softc;
1369
1370	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1371
1372	if (iid > CTL_MAX_INIT_PER_PORT) {
1373		printf("%s: initiator ID %u > maximun %u!\n",
1374		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1375		return (-1);
1376	}
1377
1378	mtx_lock(&softc->ctl_lock);
1379	port->wwpn_iid[iid].in_use--;
1380	port->wwpn_iid[iid].last_use = time_uptime;
1381	mtx_unlock(&softc->ctl_lock);
1382
1383	return (0);
1384}
1385
1386/*
1387 * Add an initiator to the initiator map.
1388 * Returns iid for success, < 0 for failure.
1389 */
1390int
1391ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1392{
1393	struct ctl_softc *softc = control_softc;
1394	time_t best_time;
1395	int i, best;
1396
1397	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1398
1399	if (iid >= CTL_MAX_INIT_PER_PORT) {
1400		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1401		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1402		free(name, M_CTL);
1403		return (-1);
1404	}
1405
1406	mtx_lock(&softc->ctl_lock);
1407
1408	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1409		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1410			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1411				iid = i;
1412				break;
1413			}
1414			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1415			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1416				iid = i;
1417				break;
1418			}
1419		}
1420	}
1421
1422	if (iid < 0) {
1423		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1424			if (port->wwpn_iid[i].in_use == 0 &&
1425			    port->wwpn_iid[i].wwpn == 0 &&
1426			    port->wwpn_iid[i].name == NULL) {
1427				iid = i;
1428				break;
1429			}
1430		}
1431	}
1432
1433	if (iid < 0) {
1434		best = -1;
1435		best_time = INT32_MAX;
1436		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1437			if (port->wwpn_iid[i].in_use == 0) {
1438				if (port->wwpn_iid[i].last_use < best_time) {
1439					best = i;
1440					best_time = port->wwpn_iid[i].last_use;
1441				}
1442			}
1443		}
1444		iid = best;
1445	}
1446
1447	if (iid < 0) {
1448		mtx_unlock(&softc->ctl_lock);
1449		free(name, M_CTL);
1450		return (-2);
1451	}
1452
1453	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1454		/*
1455		 * This is not an error yet.
1456		 */
1457		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1458#if 0
1459			printf("%s: port %d iid %u WWPN %#jx arrived"
1460			    " again\n", __func__, port->targ_port,
1461			    iid, (uintmax_t)wwpn);
1462#endif
1463			goto take;
1464		}
1465		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1466		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1467#if 0
1468			printf("%s: port %d iid %u name '%s' arrived"
1469			    " again\n", __func__, port->targ_port,
1470			    iid, name);
1471#endif
1472			goto take;
1473		}
1474
1475		/*
1476		 * This is an error, but what do we do about it?  The
1477		 * driver is telling us we have a new WWPN for this
1478		 * initiator ID, so we pretty much need to use it.
1479		 */
1480		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1481		    " but WWPN %#jx '%s' is still at that address\n",
1482		    __func__, port->targ_port, iid, wwpn, name,
1483		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1484		    port->wwpn_iid[iid].name);
1485
1486		/*
1487		 * XXX KDM clear have_ca and ua_pending on each LUN for
1488		 * this initiator.
1489		 */
1490	}
1491take:
1492	free(port->wwpn_iid[iid].name, M_CTL);
1493	port->wwpn_iid[iid].name = name;
1494	port->wwpn_iid[iid].wwpn = wwpn;
1495	port->wwpn_iid[iid].in_use++;
1496	mtx_unlock(&softc->ctl_lock);
1497
1498	return (iid);
1499}
1500
1501static int
1502ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1503{
1504	int len;
1505
1506	switch (port->port_type) {
1507	case CTL_PORT_FC:
1508	{
1509		struct scsi_transportid_fcp *id =
1510		    (struct scsi_transportid_fcp *)buf;
1511		if (port->wwpn_iid[iid].wwpn == 0)
1512			return (0);
1513		memset(id, 0, sizeof(*id));
1514		id->format_protocol = SCSI_PROTO_FC;
1515		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1516		return (sizeof(*id));
1517	}
1518	case CTL_PORT_ISCSI:
1519	{
1520		struct scsi_transportid_iscsi_port *id =
1521		    (struct scsi_transportid_iscsi_port *)buf;
1522		if (port->wwpn_iid[iid].name == NULL)
1523			return (0);
1524		memset(id, 0, 256);
1525		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1526		    SCSI_PROTO_ISCSI;
1527		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1528		len = roundup2(min(len, 252), 4);
1529		scsi_ulto2b(len, id->additional_length);
1530		return (sizeof(*id) + len);
1531	}
1532	case CTL_PORT_SAS:
1533	{
1534		struct scsi_transportid_sas *id =
1535		    (struct scsi_transportid_sas *)buf;
1536		if (port->wwpn_iid[iid].wwpn == 0)
1537			return (0);
1538		memset(id, 0, sizeof(*id));
1539		id->format_protocol = SCSI_PROTO_SAS;
1540		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1541		return (sizeof(*id));
1542	}
1543	default:
1544	{
1545		struct scsi_transportid_spi *id =
1546		    (struct scsi_transportid_spi *)buf;
1547		memset(id, 0, sizeof(*id));
1548		id->format_protocol = SCSI_PROTO_SPI;
1549		scsi_ulto2b(iid, id->scsi_addr);
1550		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1551		return (sizeof(*id));
1552	}
1553	}
1554}
1555
1556static int
1557ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1558{
1559	return (0);
1560}
1561
1562static int
1563ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1564{
1565	return (0);
1566}
1567
1568/*
1569 * Data movement routine for the CTL ioctl frontend port.
1570 */
1571static int
1572ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1573{
1574	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1575	struct ctl_sg_entry ext_entry, kern_entry;
1576	int ext_sglen, ext_sg_entries, kern_sg_entries;
1577	int ext_sg_start, ext_offset;
1578	int len_to_copy, len_copied;
1579	int kern_watermark, ext_watermark;
1580	int ext_sglist_malloced;
1581	int i, j;
1582
1583	ext_sglist_malloced = 0;
1584	ext_sg_start = 0;
1585	ext_offset = 0;
1586
1587	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1588
1589	/*
1590	 * If this flag is set, fake the data transfer.
1591	 */
1592	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1593		ctsio->ext_data_filled = ctsio->ext_data_len;
1594		goto bailout;
1595	}
1596
1597	/*
1598	 * To simplify things here, if we have a single buffer, stick it in
1599	 * a S/G entry and just make it a single entry S/G list.
1600	 */
1601	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1602		int len_seen;
1603
1604		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1605
1606		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1607							   M_WAITOK);
1608		ext_sglist_malloced = 1;
1609		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1610				   ext_sglen) != 0) {
1611			ctl_set_internal_failure(ctsio,
1612						 /*sks_valid*/ 0,
1613						 /*retry_count*/ 0);
1614			goto bailout;
1615		}
1616		ext_sg_entries = ctsio->ext_sg_entries;
1617		len_seen = 0;
1618		for (i = 0; i < ext_sg_entries; i++) {
1619			if ((len_seen + ext_sglist[i].len) >=
1620			     ctsio->ext_data_filled) {
1621				ext_sg_start = i;
1622				ext_offset = ctsio->ext_data_filled - len_seen;
1623				break;
1624			}
1625			len_seen += ext_sglist[i].len;
1626		}
1627	} else {
1628		ext_sglist = &ext_entry;
1629		ext_sglist->addr = ctsio->ext_data_ptr;
1630		ext_sglist->len = ctsio->ext_data_len;
1631		ext_sg_entries = 1;
1632		ext_sg_start = 0;
1633		ext_offset = ctsio->ext_data_filled;
1634	}
1635
1636	if (ctsio->kern_sg_entries > 0) {
1637		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1638		kern_sg_entries = ctsio->kern_sg_entries;
1639	} else {
1640		kern_sglist = &kern_entry;
1641		kern_sglist->addr = ctsio->kern_data_ptr;
1642		kern_sglist->len = ctsio->kern_data_len;
1643		kern_sg_entries = 1;
1644	}
1645
1646
1647	kern_watermark = 0;
1648	ext_watermark = ext_offset;
1649	len_copied = 0;
1650	for (i = ext_sg_start, j = 0;
1651	     i < ext_sg_entries && j < kern_sg_entries;) {
1652		uint8_t *ext_ptr, *kern_ptr;
1653
1654		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1655				      kern_sglist[j].len - kern_watermark);
1656
1657		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1658		ext_ptr = ext_ptr + ext_watermark;
1659		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1660			/*
1661			 * XXX KDM fix this!
1662			 */
1663			panic("need to implement bus address support");
1664#if 0
1665			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1666#endif
1667		} else
1668			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1669		kern_ptr = kern_ptr + kern_watermark;
1670
1671		kern_watermark += len_to_copy;
1672		ext_watermark += len_to_copy;
1673
1674		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1675		     CTL_FLAG_DATA_IN) {
1676			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1677					 "bytes to user\n", len_to_copy));
1678			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1679					 "to %p\n", kern_ptr, ext_ptr));
1680			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1681				ctl_set_internal_failure(ctsio,
1682							 /*sks_valid*/ 0,
1683							 /*retry_count*/ 0);
1684				goto bailout;
1685			}
1686		} else {
1687			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1688					 "bytes from user\n", len_to_copy));
1689			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1690					 "to %p\n", ext_ptr, kern_ptr));
1691			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1692				ctl_set_internal_failure(ctsio,
1693							 /*sks_valid*/ 0,
1694							 /*retry_count*/0);
1695				goto bailout;
1696			}
1697		}
1698
1699		len_copied += len_to_copy;
1700
1701		if (ext_sglist[i].len == ext_watermark) {
1702			i++;
1703			ext_watermark = 0;
1704		}
1705
1706		if (kern_sglist[j].len == kern_watermark) {
1707			j++;
1708			kern_watermark = 0;
1709		}
1710	}
1711
1712	ctsio->ext_data_filled += len_copied;
1713
1714	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1715			 "kern_sg_entries: %d\n", ext_sg_entries,
1716			 kern_sg_entries));
1717	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1718			 "kern_data_len = %d\n", ctsio->ext_data_len,
1719			 ctsio->kern_data_len));
1720
1721
1722	/* XXX KDM set residual?? */
1723bailout:
1724
1725	if (ext_sglist_malloced != 0)
1726		free(ext_sglist, M_CTL);
1727
1728	return (CTL_RETVAL_COMPLETE);
1729}
1730
1731/*
1732 * Serialize a command that went down the "wrong" side, and so was sent to
1733 * this controller for execution.  The logic is a little different than the
1734 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1735 * sent back to the other side, but in the success case, we execute the
1736 * command on this side (XFER mode) or tell the other side to execute it
1737 * (SER_ONLY mode).
1738 */
1739static int
1740ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1741{
1742	struct ctl_softc *ctl_softc;
1743	union ctl_ha_msg msg_info;
1744	struct ctl_lun *lun;
1745	int retval = 0;
1746	uint32_t targ_lun;
1747
1748	ctl_softc = control_softc;
1749
1750	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1751	lun = ctl_softc->ctl_luns[targ_lun];
1752	if (lun==NULL)
1753	{
1754		/*
1755		 * Why isn't LUN defined? The other side wouldn't
1756		 * send a cmd if the LUN is undefined.
1757		 */
1758		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1759
1760		/* "Logical unit not supported" */
1761		ctl_set_sense_data(&msg_info.scsi.sense_data,
1762				   lun,
1763				   /*sense_format*/SSD_TYPE_NONE,
1764				   /*current_error*/ 1,
1765				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1766				   /*asc*/ 0x25,
1767				   /*ascq*/ 0x00,
1768				   SSD_ELEM_NONE);
1769
1770		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1771		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1772		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1773		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1774		msg_info.hdr.serializing_sc = NULL;
1775		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1776	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1777				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1778		}
1779		return(1);
1780
1781	}
1782
1783	mtx_lock(&lun->lun_lock);
1784    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1785
1786	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1787		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1788		 ooa_links))) {
1789	case CTL_ACTION_BLOCK:
1790		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1791		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1792				  blocked_links);
1793		break;
1794	case CTL_ACTION_PASS:
1795	case CTL_ACTION_SKIP:
1796		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1797			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1798			ctl_enqueue_rtr((union ctl_io *)ctsio);
1799		} else {
1800
1801			/* send msg back to other side */
1802			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1803			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1804			msg_info.hdr.msg_type = CTL_MSG_R2R;
1805#if 0
1806			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1807#endif
1808		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1809			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1810			}
1811		}
1812		break;
1813	case CTL_ACTION_OVERLAP:
1814		/* OVERLAPPED COMMANDS ATTEMPTED */
1815		ctl_set_sense_data(&msg_info.scsi.sense_data,
1816				   lun,
1817				   /*sense_format*/SSD_TYPE_NONE,
1818				   /*current_error*/ 1,
1819				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1820				   /*asc*/ 0x4E,
1821				   /*ascq*/ 0x00,
1822				   SSD_ELEM_NONE);
1823
1824		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1825		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1826		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1827		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1828		msg_info.hdr.serializing_sc = NULL;
1829		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1830#if 0
1831		printf("BAD JUJU:Major Bummer Overlap\n");
1832#endif
1833		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1834		retval = 1;
1835		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1836		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1837		}
1838		break;
1839	case CTL_ACTION_OVERLAP_TAG:
1840		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1841		ctl_set_sense_data(&msg_info.scsi.sense_data,
1842				   lun,
1843				   /*sense_format*/SSD_TYPE_NONE,
1844				   /*current_error*/ 1,
1845				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1846				   /*asc*/ 0x4D,
1847				   /*ascq*/ ctsio->tag_num & 0xff,
1848				   SSD_ELEM_NONE);
1849
1850		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1851		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1852		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1853		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1854		msg_info.hdr.serializing_sc = NULL;
1855		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1856#if 0
1857		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1858#endif
1859		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1860		retval = 1;
1861		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1862		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1863		}
1864		break;
1865	case CTL_ACTION_ERROR:
1866	default:
1867		/* "Internal target failure" */
1868		ctl_set_sense_data(&msg_info.scsi.sense_data,
1869				   lun,
1870				   /*sense_format*/SSD_TYPE_NONE,
1871				   /*current_error*/ 1,
1872				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1873				   /*asc*/ 0x44,
1874				   /*ascq*/ 0x00,
1875				   SSD_ELEM_NONE);
1876
1877		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1878		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1879		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1880		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1881		msg_info.hdr.serializing_sc = NULL;
1882		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1883#if 0
1884		printf("BAD JUJU:Major Bummer HW Error\n");
1885#endif
1886		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1887		retval = 1;
1888		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1889		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1890		}
1891		break;
1892	}
1893	mtx_unlock(&lun->lun_lock);
1894	return (retval);
1895}
1896
1897static int
1898ctl_ioctl_submit_wait(union ctl_io *io)
1899{
1900	struct ctl_fe_ioctl_params params;
1901	ctl_fe_ioctl_state last_state;
1902	int done, retval;
1903
1904	retval = 0;
1905
1906	bzero(&params, sizeof(params));
1907
1908	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1909	cv_init(&params.sem, "ctlioccv");
1910	params.state = CTL_IOCTL_INPROG;
1911	last_state = params.state;
1912
1913	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1914
1915	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1916
1917	/* This shouldn't happen */
1918	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1919		return (retval);
1920
1921	done = 0;
1922
1923	do {
1924		mtx_lock(&params.ioctl_mtx);
1925		/*
1926		 * Check the state here, and don't sleep if the state has
1927		 * already changed (i.e. wakeup has already occured, but we
1928		 * weren't waiting yet).
1929		 */
1930		if (params.state == last_state) {
1931			/* XXX KDM cv_wait_sig instead? */
1932			cv_wait(&params.sem, &params.ioctl_mtx);
1933		}
1934		last_state = params.state;
1935
1936		switch (params.state) {
1937		case CTL_IOCTL_INPROG:
1938			/* Why did we wake up? */
1939			/* XXX KDM error here? */
1940			mtx_unlock(&params.ioctl_mtx);
1941			break;
1942		case CTL_IOCTL_DATAMOVE:
1943			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1944
1945			/*
1946			 * change last_state back to INPROG to avoid
1947			 * deadlock on subsequent data moves.
1948			 */
1949			params.state = last_state = CTL_IOCTL_INPROG;
1950
1951			mtx_unlock(&params.ioctl_mtx);
1952			ctl_ioctl_do_datamove(&io->scsiio);
1953			/*
1954			 * Note that in some cases, most notably writes,
1955			 * this will queue the I/O and call us back later.
1956			 * In other cases, generally reads, this routine
1957			 * will immediately call back and wake us up,
1958			 * probably using our own context.
1959			 */
1960			io->scsiio.be_move_done(io);
1961			break;
1962		case CTL_IOCTL_DONE:
1963			mtx_unlock(&params.ioctl_mtx);
1964			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1965			done = 1;
1966			break;
1967		default:
1968			mtx_unlock(&params.ioctl_mtx);
1969			/* XXX KDM error here? */
1970			break;
1971		}
1972	} while (done == 0);
1973
1974	mtx_destroy(&params.ioctl_mtx);
1975	cv_destroy(&params.sem);
1976
1977	return (CTL_RETVAL_COMPLETE);
1978}
1979
1980static void
1981ctl_ioctl_datamove(union ctl_io *io)
1982{
1983	struct ctl_fe_ioctl_params *params;
1984
1985	params = (struct ctl_fe_ioctl_params *)
1986		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1987
1988	mtx_lock(&params->ioctl_mtx);
1989	params->state = CTL_IOCTL_DATAMOVE;
1990	cv_broadcast(&params->sem);
1991	mtx_unlock(&params->ioctl_mtx);
1992}
1993
1994static void
1995ctl_ioctl_done(union ctl_io *io)
1996{
1997	struct ctl_fe_ioctl_params *params;
1998
1999	params = (struct ctl_fe_ioctl_params *)
2000		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2001
2002	mtx_lock(&params->ioctl_mtx);
2003	params->state = CTL_IOCTL_DONE;
2004	cv_broadcast(&params->sem);
2005	mtx_unlock(&params->ioctl_mtx);
2006}
2007
2008static void
2009ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2010{
2011	struct ctl_fe_ioctl_startstop_info *sd_info;
2012
2013	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2014
2015	sd_info->hs_info.status = metatask->status;
2016	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2017	sd_info->hs_info.luns_complete =
2018		metatask->taskinfo.startstop.luns_complete;
2019	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2020
2021	cv_broadcast(&sd_info->sem);
2022}
2023
2024static void
2025ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2026{
2027	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2028
2029	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2030
2031	mtx_lock(fe_bbr_info->lock);
2032	fe_bbr_info->bbr_info->status = metatask->status;
2033	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2034	fe_bbr_info->wakeup_done = 1;
2035	mtx_unlock(fe_bbr_info->lock);
2036
2037	cv_broadcast(&fe_bbr_info->sem);
2038}
2039
2040/*
2041 * Returns 0 for success, errno for failure.
2042 */
2043static int
2044ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2045		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2046{
2047	union ctl_io *io;
2048	int retval;
2049
2050	retval = 0;
2051
2052	mtx_lock(&lun->lun_lock);
2053	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2054	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2055	     ooa_links)) {
2056		struct ctl_ooa_entry *entry;
2057
2058		/*
2059		 * If we've got more than we can fit, just count the
2060		 * remaining entries.
2061		 */
2062		if (*cur_fill_num >= ooa_hdr->alloc_num)
2063			continue;
2064
2065		entry = &kern_entries[*cur_fill_num];
2066
2067		entry->tag_num = io->scsiio.tag_num;
2068		entry->lun_num = lun->lun;
2069#ifdef CTL_TIME_IO
2070		entry->start_bt = io->io_hdr.start_bt;
2071#endif
2072		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2073		entry->cdb_len = io->scsiio.cdb_len;
2074		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2075			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2076
2077		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2078			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2079
2080		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2081			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2082
2083		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2084			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2085
2086		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2087			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2088	}
2089	mtx_unlock(&lun->lun_lock);
2090
2091	return (retval);
2092}
2093
2094static void *
2095ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2096		 size_t error_str_len)
2097{
2098	void *kptr;
2099
2100	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2101
2102	if (copyin(user_addr, kptr, len) != 0) {
2103		snprintf(error_str, error_str_len, "Error copying %d bytes "
2104			 "from user address %p to kernel address %p", len,
2105			 user_addr, kptr);
2106		free(kptr, M_CTL);
2107		return (NULL);
2108	}
2109
2110	return (kptr);
2111}
2112
2113static void
2114ctl_free_args(int num_args, struct ctl_be_arg *args)
2115{
2116	int i;
2117
2118	if (args == NULL)
2119		return;
2120
2121	for (i = 0; i < num_args; i++) {
2122		free(args[i].kname, M_CTL);
2123		free(args[i].kvalue, M_CTL);
2124	}
2125
2126	free(args, M_CTL);
2127}
2128
2129static struct ctl_be_arg *
2130ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2131		char *error_str, size_t error_str_len)
2132{
2133	struct ctl_be_arg *args;
2134	int i;
2135
2136	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2137				error_str, error_str_len);
2138
2139	if (args == NULL)
2140		goto bailout;
2141
2142	for (i = 0; i < num_args; i++) {
2143		args[i].kname = NULL;
2144		args[i].kvalue = NULL;
2145	}
2146
2147	for (i = 0; i < num_args; i++) {
2148		uint8_t *tmpptr;
2149
2150		args[i].kname = ctl_copyin_alloc(args[i].name,
2151			args[i].namelen, error_str, error_str_len);
2152		if (args[i].kname == NULL)
2153			goto bailout;
2154
2155		if (args[i].kname[args[i].namelen - 1] != '\0') {
2156			snprintf(error_str, error_str_len, "Argument %d "
2157				 "name is not NUL-terminated", i);
2158			goto bailout;
2159		}
2160
2161		if (args[i].flags & CTL_BEARG_RD) {
2162			tmpptr = ctl_copyin_alloc(args[i].value,
2163				args[i].vallen, error_str, error_str_len);
2164			if (tmpptr == NULL)
2165				goto bailout;
2166			if ((args[i].flags & CTL_BEARG_ASCII)
2167			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2168				snprintf(error_str, error_str_len, "Argument "
2169				    "%d value is not NUL-terminated", i);
2170				goto bailout;
2171			}
2172			args[i].kvalue = tmpptr;
2173		} else {
2174			args[i].kvalue = malloc(args[i].vallen,
2175			    M_CTL, M_WAITOK | M_ZERO);
2176		}
2177	}
2178
2179	return (args);
2180bailout:
2181
2182	ctl_free_args(num_args, args);
2183
2184	return (NULL);
2185}
2186
2187static void
2188ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2189{
2190	int i;
2191
2192	for (i = 0; i < num_args; i++) {
2193		if (args[i].flags & CTL_BEARG_WR)
2194			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2195	}
2196}
2197
2198/*
2199 * Escape characters that are illegal or not recommended in XML.
2200 */
2201int
2202ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2203{
2204	int retval;
2205
2206	retval = 0;
2207
2208	for (; *str; str++) {
2209		switch (*str) {
2210		case '&':
2211			retval = sbuf_printf(sb, "&amp;");
2212			break;
2213		case '>':
2214			retval = sbuf_printf(sb, "&gt;");
2215			break;
2216		case '<':
2217			retval = sbuf_printf(sb, "&lt;");
2218			break;
2219		default:
2220			retval = sbuf_putc(sb, *str);
2221			break;
2222		}
2223
2224		if (retval != 0)
2225			break;
2226
2227	}
2228
2229	return (retval);
2230}
2231
2232static void
2233ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2234{
2235	struct scsi_vpd_id_descriptor *desc;
2236	int i;
2237
2238	if (id == NULL || id->len < 4)
2239		return;
2240	desc = (struct scsi_vpd_id_descriptor *)id->data;
2241	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2242	case SVPD_ID_TYPE_T10:
2243		sbuf_printf(sb, "t10.");
2244		break;
2245	case SVPD_ID_TYPE_EUI64:
2246		sbuf_printf(sb, "eui.");
2247		break;
2248	case SVPD_ID_TYPE_NAA:
2249		sbuf_printf(sb, "naa.");
2250		break;
2251	case SVPD_ID_TYPE_SCSI_NAME:
2252		break;
2253	}
2254	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2255	case SVPD_ID_CODESET_BINARY:
2256		for (i = 0; i < desc->length; i++)
2257			sbuf_printf(sb, "%02x", desc->identifier[i]);
2258		break;
2259	case SVPD_ID_CODESET_ASCII:
2260		sbuf_printf(sb, "%.*s", (int)desc->length,
2261		    (char *)desc->identifier);
2262		break;
2263	case SVPD_ID_CODESET_UTF8:
2264		sbuf_printf(sb, "%s", (char *)desc->identifier);
2265		break;
2266	}
2267}
2268
2269static int
2270ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2271	  struct thread *td)
2272{
2273	struct ctl_softc *softc;
2274	int retval;
2275
2276	softc = control_softc;
2277
2278	retval = 0;
2279
2280	switch (cmd) {
2281	case CTL_IO: {
2282		union ctl_io *io;
2283		void *pool_tmp;
2284
2285		/*
2286		 * If we haven't been "enabled", don't allow any SCSI I/O
2287		 * to this FETD.
2288		 */
2289		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2290			retval = EPERM;
2291			break;
2292		}
2293
2294		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2295		if (io == NULL) {
2296			printf("ctl_ioctl: can't allocate ctl_io!\n");
2297			retval = ENOSPC;
2298			break;
2299		}
2300
2301		/*
2302		 * Need to save the pool reference so it doesn't get
2303		 * spammed by the user's ctl_io.
2304		 */
2305		pool_tmp = io->io_hdr.pool;
2306
2307		memcpy(io, (void *)addr, sizeof(*io));
2308
2309		io->io_hdr.pool = pool_tmp;
2310		/*
2311		 * No status yet, so make sure the status is set properly.
2312		 */
2313		io->io_hdr.status = CTL_STATUS_NONE;
2314
2315		/*
2316		 * The user sets the initiator ID, target and LUN IDs.
2317		 */
2318		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2319		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2320		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2321		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2322			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2323
2324		retval = ctl_ioctl_submit_wait(io);
2325
2326		if (retval != 0) {
2327			ctl_free_io(io);
2328			break;
2329		}
2330
2331		memcpy((void *)addr, io, sizeof(*io));
2332
2333		/* return this to our pool */
2334		ctl_free_io(io);
2335
2336		break;
2337	}
2338	case CTL_ENABLE_PORT:
2339	case CTL_DISABLE_PORT:
2340	case CTL_SET_PORT_WWNS: {
2341		struct ctl_port *port;
2342		struct ctl_port_entry *entry;
2343
2344		entry = (struct ctl_port_entry *)addr;
2345
2346		mtx_lock(&softc->ctl_lock);
2347		STAILQ_FOREACH(port, &softc->port_list, links) {
2348			int action, done;
2349
2350			action = 0;
2351			done = 0;
2352
2353			if ((entry->port_type == CTL_PORT_NONE)
2354			 && (entry->targ_port == port->targ_port)) {
2355				/*
2356				 * If the user only wants to enable or
2357				 * disable or set WWNs on a specific port,
2358				 * do the operation and we're done.
2359				 */
2360				action = 1;
2361				done = 1;
2362			} else if (entry->port_type & port->port_type) {
2363				/*
2364				 * Compare the user's type mask with the
2365				 * particular frontend type to see if we
2366				 * have a match.
2367				 */
2368				action = 1;
2369				done = 0;
2370
2371				/*
2372				 * Make sure the user isn't trying to set
2373				 * WWNs on multiple ports at the same time.
2374				 */
2375				if (cmd == CTL_SET_PORT_WWNS) {
2376					printf("%s: Can't set WWNs on "
2377					       "multiple ports\n", __func__);
2378					retval = EINVAL;
2379					break;
2380				}
2381			}
2382			if (action != 0) {
2383				/*
2384				 * XXX KDM we have to drop the lock here,
2385				 * because the online/offline operations
2386				 * can potentially block.  We need to
2387				 * reference count the frontends so they
2388				 * can't go away,
2389				 */
2390				mtx_unlock(&softc->ctl_lock);
2391
2392				if (cmd == CTL_ENABLE_PORT) {
2393					struct ctl_lun *lun;
2394
2395					STAILQ_FOREACH(lun, &softc->lun_list,
2396						       links) {
2397						port->lun_enable(port->targ_lun_arg,
2398						    lun->target,
2399						    lun->lun);
2400					}
2401
2402					ctl_port_online(port);
2403				} else if (cmd == CTL_DISABLE_PORT) {
2404					struct ctl_lun *lun;
2405
2406					ctl_port_offline(port);
2407
2408					STAILQ_FOREACH(lun, &softc->lun_list,
2409						       links) {
2410						port->lun_disable(
2411						    port->targ_lun_arg,
2412						    lun->target,
2413						    lun->lun);
2414					}
2415				}
2416
2417				mtx_lock(&softc->ctl_lock);
2418
2419				if (cmd == CTL_SET_PORT_WWNS)
2420					ctl_port_set_wwns(port,
2421					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2422					    1 : 0, entry->wwnn,
2423					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2424					    1 : 0, entry->wwpn);
2425			}
2426			if (done != 0)
2427				break;
2428		}
2429		mtx_unlock(&softc->ctl_lock);
2430		break;
2431	}
2432	case CTL_GET_PORT_LIST: {
2433		struct ctl_port *port;
2434		struct ctl_port_list *list;
2435		int i;
2436
2437		list = (struct ctl_port_list *)addr;
2438
2439		if (list->alloc_len != (list->alloc_num *
2440		    sizeof(struct ctl_port_entry))) {
2441			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2442			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2443			       "%zu\n", __func__, list->alloc_len,
2444			       list->alloc_num, sizeof(struct ctl_port_entry));
2445			retval = EINVAL;
2446			break;
2447		}
2448		list->fill_len = 0;
2449		list->fill_num = 0;
2450		list->dropped_num = 0;
2451		i = 0;
2452		mtx_lock(&softc->ctl_lock);
2453		STAILQ_FOREACH(port, &softc->port_list, links) {
2454			struct ctl_port_entry entry, *list_entry;
2455
2456			if (list->fill_num >= list->alloc_num) {
2457				list->dropped_num++;
2458				continue;
2459			}
2460
2461			entry.port_type = port->port_type;
2462			strlcpy(entry.port_name, port->port_name,
2463				sizeof(entry.port_name));
2464			entry.targ_port = port->targ_port;
2465			entry.physical_port = port->physical_port;
2466			entry.virtual_port = port->virtual_port;
2467			entry.wwnn = port->wwnn;
2468			entry.wwpn = port->wwpn;
2469			if (port->status & CTL_PORT_STATUS_ONLINE)
2470				entry.online = 1;
2471			else
2472				entry.online = 0;
2473
2474			list_entry = &list->entries[i];
2475
2476			retval = copyout(&entry, list_entry, sizeof(entry));
2477			if (retval != 0) {
2478				printf("%s: CTL_GET_PORT_LIST: copyout "
2479				       "returned %d\n", __func__, retval);
2480				break;
2481			}
2482			i++;
2483			list->fill_num++;
2484			list->fill_len += sizeof(entry);
2485		}
2486		mtx_unlock(&softc->ctl_lock);
2487
2488		/*
2489		 * If this is non-zero, we had a copyout fault, so there's
2490		 * probably no point in attempting to set the status inside
2491		 * the structure.
2492		 */
2493		if (retval != 0)
2494			break;
2495
2496		if (list->dropped_num > 0)
2497			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2498		else
2499			list->status = CTL_PORT_LIST_OK;
2500		break;
2501	}
2502	case CTL_DUMP_OOA: {
2503		struct ctl_lun *lun;
2504		union ctl_io *io;
2505		char printbuf[128];
2506		struct sbuf sb;
2507
2508		mtx_lock(&softc->ctl_lock);
2509		printf("Dumping OOA queues:\n");
2510		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2511			mtx_lock(&lun->lun_lock);
2512			for (io = (union ctl_io *)TAILQ_FIRST(
2513			     &lun->ooa_queue); io != NULL;
2514			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2515			     ooa_links)) {
2516				sbuf_new(&sb, printbuf, sizeof(printbuf),
2517					 SBUF_FIXEDLEN);
2518				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2519					    (intmax_t)lun->lun,
2520					    io->scsiio.tag_num,
2521					    (io->io_hdr.flags &
2522					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2523					    (io->io_hdr.flags &
2524					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2525					    (io->io_hdr.flags &
2526					    CTL_FLAG_ABORT) ? " ABORT" : "",
2527			                    (io->io_hdr.flags &
2528		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2529				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2530				sbuf_finish(&sb);
2531				printf("%s\n", sbuf_data(&sb));
2532			}
2533			mtx_unlock(&lun->lun_lock);
2534		}
2535		printf("OOA queues dump done\n");
2536		mtx_unlock(&softc->ctl_lock);
2537		break;
2538	}
2539	case CTL_GET_OOA: {
2540		struct ctl_lun *lun;
2541		struct ctl_ooa *ooa_hdr;
2542		struct ctl_ooa_entry *entries;
2543		uint32_t cur_fill_num;
2544
2545		ooa_hdr = (struct ctl_ooa *)addr;
2546
2547		if ((ooa_hdr->alloc_len == 0)
2548		 || (ooa_hdr->alloc_num == 0)) {
2549			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2550			       "must be non-zero\n", __func__,
2551			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2552			retval = EINVAL;
2553			break;
2554		}
2555
2556		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2557		    sizeof(struct ctl_ooa_entry))) {
2558			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2559			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2560			       __func__, ooa_hdr->alloc_len,
2561			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2562			retval = EINVAL;
2563			break;
2564		}
2565
2566		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2567		if (entries == NULL) {
2568			printf("%s: could not allocate %d bytes for OOA "
2569			       "dump\n", __func__, ooa_hdr->alloc_len);
2570			retval = ENOMEM;
2571			break;
2572		}
2573
2574		mtx_lock(&softc->ctl_lock);
2575		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2576		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2577		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2578			mtx_unlock(&softc->ctl_lock);
2579			free(entries, M_CTL);
2580			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2581			       __func__, (uintmax_t)ooa_hdr->lun_num);
2582			retval = EINVAL;
2583			break;
2584		}
2585
2586		cur_fill_num = 0;
2587
2588		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2589			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2590				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2591					ooa_hdr, entries);
2592				if (retval != 0)
2593					break;
2594			}
2595			if (retval != 0) {
2596				mtx_unlock(&softc->ctl_lock);
2597				free(entries, M_CTL);
2598				break;
2599			}
2600		} else {
2601			lun = softc->ctl_luns[ooa_hdr->lun_num];
2602
2603			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2604						    entries);
2605		}
2606		mtx_unlock(&softc->ctl_lock);
2607
2608		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2609		ooa_hdr->fill_len = ooa_hdr->fill_num *
2610			sizeof(struct ctl_ooa_entry);
2611		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2612		if (retval != 0) {
2613			printf("%s: error copying out %d bytes for OOA dump\n",
2614			       __func__, ooa_hdr->fill_len);
2615		}
2616
2617		getbintime(&ooa_hdr->cur_bt);
2618
2619		if (cur_fill_num > ooa_hdr->alloc_num) {
2620			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2621			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2622		} else {
2623			ooa_hdr->dropped_num = 0;
2624			ooa_hdr->status = CTL_OOA_OK;
2625		}
2626
2627		free(entries, M_CTL);
2628		break;
2629	}
2630	case CTL_CHECK_OOA: {
2631		union ctl_io *io;
2632		struct ctl_lun *lun;
2633		struct ctl_ooa_info *ooa_info;
2634
2635
2636		ooa_info = (struct ctl_ooa_info *)addr;
2637
2638		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2639			ooa_info->status = CTL_OOA_INVALID_LUN;
2640			break;
2641		}
2642		mtx_lock(&softc->ctl_lock);
2643		lun = softc->ctl_luns[ooa_info->lun_id];
2644		if (lun == NULL) {
2645			mtx_unlock(&softc->ctl_lock);
2646			ooa_info->status = CTL_OOA_INVALID_LUN;
2647			break;
2648		}
2649		mtx_lock(&lun->lun_lock);
2650		mtx_unlock(&softc->ctl_lock);
2651		ooa_info->num_entries = 0;
2652		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2653		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2654		     &io->io_hdr, ooa_links)) {
2655			ooa_info->num_entries++;
2656		}
2657		mtx_unlock(&lun->lun_lock);
2658
2659		ooa_info->status = CTL_OOA_SUCCESS;
2660
2661		break;
2662	}
2663	case CTL_HARD_START:
2664	case CTL_HARD_STOP: {
2665		struct ctl_fe_ioctl_startstop_info ss_info;
2666		struct cfi_metatask *metatask;
2667		struct mtx hs_mtx;
2668
2669		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2670
2671		cv_init(&ss_info.sem, "hard start/stop cv" );
2672
2673		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2674		if (metatask == NULL) {
2675			retval = ENOMEM;
2676			mtx_destroy(&hs_mtx);
2677			break;
2678		}
2679
2680		if (cmd == CTL_HARD_START)
2681			metatask->tasktype = CFI_TASK_STARTUP;
2682		else
2683			metatask->tasktype = CFI_TASK_SHUTDOWN;
2684
2685		metatask->callback = ctl_ioctl_hard_startstop_callback;
2686		metatask->callback_arg = &ss_info;
2687
2688		cfi_action(metatask);
2689
2690		/* Wait for the callback */
2691		mtx_lock(&hs_mtx);
2692		cv_wait_sig(&ss_info.sem, &hs_mtx);
2693		mtx_unlock(&hs_mtx);
2694
2695		/*
2696		 * All information has been copied from the metatask by the
2697		 * time cv_broadcast() is called, so we free the metatask here.
2698		 */
2699		cfi_free_metatask(metatask);
2700
2701		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2702
2703		mtx_destroy(&hs_mtx);
2704		break;
2705	}
2706	case CTL_BBRREAD: {
2707		struct ctl_bbrread_info *bbr_info;
2708		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2709		struct mtx bbr_mtx;
2710		struct cfi_metatask *metatask;
2711
2712		bbr_info = (struct ctl_bbrread_info *)addr;
2713
2714		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2715
2716		bzero(&bbr_mtx, sizeof(bbr_mtx));
2717		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2718
2719		fe_bbr_info.bbr_info = bbr_info;
2720		fe_bbr_info.lock = &bbr_mtx;
2721
2722		cv_init(&fe_bbr_info.sem, "BBR read cv");
2723		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2724
2725		if (metatask == NULL) {
2726			mtx_destroy(&bbr_mtx);
2727			cv_destroy(&fe_bbr_info.sem);
2728			retval = ENOMEM;
2729			break;
2730		}
2731		metatask->tasktype = CFI_TASK_BBRREAD;
2732		metatask->callback = ctl_ioctl_bbrread_callback;
2733		metatask->callback_arg = &fe_bbr_info;
2734		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2735		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2736		metatask->taskinfo.bbrread.len = bbr_info->len;
2737
2738		cfi_action(metatask);
2739
2740		mtx_lock(&bbr_mtx);
2741		while (fe_bbr_info.wakeup_done == 0)
2742			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2743		mtx_unlock(&bbr_mtx);
2744
2745		bbr_info->status = metatask->status;
2746		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2747		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2748		memcpy(&bbr_info->sense_data,
2749		       &metatask->taskinfo.bbrread.sense_data,
2750		       ctl_min(sizeof(bbr_info->sense_data),
2751			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2752
2753		cfi_free_metatask(metatask);
2754
2755		mtx_destroy(&bbr_mtx);
2756		cv_destroy(&fe_bbr_info.sem);
2757
2758		break;
2759	}
2760	case CTL_DELAY_IO: {
2761		struct ctl_io_delay_info *delay_info;
2762#ifdef CTL_IO_DELAY
2763		struct ctl_lun *lun;
2764#endif /* CTL_IO_DELAY */
2765
2766		delay_info = (struct ctl_io_delay_info *)addr;
2767
2768#ifdef CTL_IO_DELAY
2769		mtx_lock(&softc->ctl_lock);
2770
2771		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2772		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2773			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2774		} else {
2775			lun = softc->ctl_luns[delay_info->lun_id];
2776			mtx_lock(&lun->lun_lock);
2777
2778			delay_info->status = CTL_DELAY_STATUS_OK;
2779
2780			switch (delay_info->delay_type) {
2781			case CTL_DELAY_TYPE_CONT:
2782				break;
2783			case CTL_DELAY_TYPE_ONESHOT:
2784				break;
2785			default:
2786				delay_info->status =
2787					CTL_DELAY_STATUS_INVALID_TYPE;
2788				break;
2789			}
2790
2791			switch (delay_info->delay_loc) {
2792			case CTL_DELAY_LOC_DATAMOVE:
2793				lun->delay_info.datamove_type =
2794					delay_info->delay_type;
2795				lun->delay_info.datamove_delay =
2796					delay_info->delay_secs;
2797				break;
2798			case CTL_DELAY_LOC_DONE:
2799				lun->delay_info.done_type =
2800					delay_info->delay_type;
2801				lun->delay_info.done_delay =
2802					delay_info->delay_secs;
2803				break;
2804			default:
2805				delay_info->status =
2806					CTL_DELAY_STATUS_INVALID_LOC;
2807				break;
2808			}
2809			mtx_unlock(&lun->lun_lock);
2810		}
2811
2812		mtx_unlock(&softc->ctl_lock);
2813#else
2814		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2815#endif /* CTL_IO_DELAY */
2816		break;
2817	}
2818	case CTL_REALSYNC_SET: {
2819		int *syncstate;
2820
2821		syncstate = (int *)addr;
2822
2823		mtx_lock(&softc->ctl_lock);
2824		switch (*syncstate) {
2825		case 0:
2826			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2827			break;
2828		case 1:
2829			softc->flags |= CTL_FLAG_REAL_SYNC;
2830			break;
2831		default:
2832			retval = EINVAL;
2833			break;
2834		}
2835		mtx_unlock(&softc->ctl_lock);
2836		break;
2837	}
2838	case CTL_REALSYNC_GET: {
2839		int *syncstate;
2840
2841		syncstate = (int*)addr;
2842
2843		mtx_lock(&softc->ctl_lock);
2844		if (softc->flags & CTL_FLAG_REAL_SYNC)
2845			*syncstate = 1;
2846		else
2847			*syncstate = 0;
2848		mtx_unlock(&softc->ctl_lock);
2849
2850		break;
2851	}
2852	case CTL_SETSYNC:
2853	case CTL_GETSYNC: {
2854		struct ctl_sync_info *sync_info;
2855		struct ctl_lun *lun;
2856
2857		sync_info = (struct ctl_sync_info *)addr;
2858
2859		mtx_lock(&softc->ctl_lock);
2860		lun = softc->ctl_luns[sync_info->lun_id];
2861		if (lun == NULL) {
2862			mtx_unlock(&softc->ctl_lock);
2863			sync_info->status = CTL_GS_SYNC_NO_LUN;
2864		}
2865		/*
2866		 * Get or set the sync interval.  We're not bounds checking
2867		 * in the set case, hopefully the user won't do something
2868		 * silly.
2869		 */
2870		mtx_lock(&lun->lun_lock);
2871		mtx_unlock(&softc->ctl_lock);
2872		if (cmd == CTL_GETSYNC)
2873			sync_info->sync_interval = lun->sync_interval;
2874		else
2875			lun->sync_interval = sync_info->sync_interval;
2876		mtx_unlock(&lun->lun_lock);
2877
2878		sync_info->status = CTL_GS_SYNC_OK;
2879
2880		break;
2881	}
2882	case CTL_GETSTATS: {
2883		struct ctl_stats *stats;
2884		struct ctl_lun *lun;
2885		int i;
2886
2887		stats = (struct ctl_stats *)addr;
2888
2889		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2890		     stats->alloc_len) {
2891			stats->status = CTL_SS_NEED_MORE_SPACE;
2892			stats->num_luns = softc->num_luns;
2893			break;
2894		}
2895		/*
2896		 * XXX KDM no locking here.  If the LUN list changes,
2897		 * things can blow up.
2898		 */
2899		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2900		     i++, lun = STAILQ_NEXT(lun, links)) {
2901			retval = copyout(&lun->stats, &stats->lun_stats[i],
2902					 sizeof(lun->stats));
2903			if (retval != 0)
2904				break;
2905		}
2906		stats->num_luns = softc->num_luns;
2907		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2908				 softc->num_luns;
2909		stats->status = CTL_SS_OK;
2910#ifdef CTL_TIME_IO
2911		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2912#else
2913		stats->flags = CTL_STATS_FLAG_NONE;
2914#endif
2915		getnanouptime(&stats->timestamp);
2916		break;
2917	}
2918	case CTL_ERROR_INJECT: {
2919		struct ctl_error_desc *err_desc, *new_err_desc;
2920		struct ctl_lun *lun;
2921
2922		err_desc = (struct ctl_error_desc *)addr;
2923
2924		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2925				      M_WAITOK | M_ZERO);
2926		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2927
2928		mtx_lock(&softc->ctl_lock);
2929		lun = softc->ctl_luns[err_desc->lun_id];
2930		if (lun == NULL) {
2931			mtx_unlock(&softc->ctl_lock);
2932			free(new_err_desc, M_CTL);
2933			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2934			       __func__, (uintmax_t)err_desc->lun_id);
2935			retval = EINVAL;
2936			break;
2937		}
2938		mtx_lock(&lun->lun_lock);
2939		mtx_unlock(&softc->ctl_lock);
2940
2941		/*
2942		 * We could do some checking here to verify the validity
2943		 * of the request, but given the complexity of error
2944		 * injection requests, the checking logic would be fairly
2945		 * complex.
2946		 *
2947		 * For now, if the request is invalid, it just won't get
2948		 * executed and might get deleted.
2949		 */
2950		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2951
2952		/*
2953		 * XXX KDM check to make sure the serial number is unique,
2954		 * in case we somehow manage to wrap.  That shouldn't
2955		 * happen for a very long time, but it's the right thing to
2956		 * do.
2957		 */
2958		new_err_desc->serial = lun->error_serial;
2959		err_desc->serial = lun->error_serial;
2960		lun->error_serial++;
2961
2962		mtx_unlock(&lun->lun_lock);
2963		break;
2964	}
2965	case CTL_ERROR_INJECT_DELETE: {
2966		struct ctl_error_desc *delete_desc, *desc, *desc2;
2967		struct ctl_lun *lun;
2968		int delete_done;
2969
2970		delete_desc = (struct ctl_error_desc *)addr;
2971		delete_done = 0;
2972
2973		mtx_lock(&softc->ctl_lock);
2974		lun = softc->ctl_luns[delete_desc->lun_id];
2975		if (lun == NULL) {
2976			mtx_unlock(&softc->ctl_lock);
2977			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2978			       __func__, (uintmax_t)delete_desc->lun_id);
2979			retval = EINVAL;
2980			break;
2981		}
2982		mtx_lock(&lun->lun_lock);
2983		mtx_unlock(&softc->ctl_lock);
2984		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2985			if (desc->serial != delete_desc->serial)
2986				continue;
2987
2988			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2989				      links);
2990			free(desc, M_CTL);
2991			delete_done = 1;
2992		}
2993		mtx_unlock(&lun->lun_lock);
2994		if (delete_done == 0) {
2995			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2996			       "error serial %ju on LUN %u\n", __func__,
2997			       delete_desc->serial, delete_desc->lun_id);
2998			retval = EINVAL;
2999			break;
3000		}
3001		break;
3002	}
3003	case CTL_DUMP_STRUCTS: {
3004		int i, j, k, idx;
3005		struct ctl_port *port;
3006		struct ctl_frontend *fe;
3007
3008		mtx_lock(&softc->ctl_lock);
3009		printf("CTL Persistent Reservation information start:\n");
3010		for (i = 0; i < CTL_MAX_LUNS; i++) {
3011			struct ctl_lun *lun;
3012
3013			lun = softc->ctl_luns[i];
3014
3015			if ((lun == NULL)
3016			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3017				continue;
3018
3019			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3020				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3021					idx = j * CTL_MAX_INIT_PER_PORT + k;
3022					if (lun->pr_keys[idx] == 0)
3023						continue;
3024					printf("  LUN %d port %d iid %d key "
3025					       "%#jx\n", i, j, k,
3026					       (uintmax_t)lun->pr_keys[idx]);
3027				}
3028			}
3029		}
3030		printf("CTL Persistent Reservation information end\n");
3031		printf("CTL Ports:\n");
3032		STAILQ_FOREACH(port, &softc->port_list, links) {
3033			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3034			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3035			       port->frontend->name, port->port_type,
3036			       port->physical_port, port->virtual_port,
3037			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3038			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3039				if (port->wwpn_iid[j].in_use == 0 &&
3040				    port->wwpn_iid[j].wwpn == 0 &&
3041				    port->wwpn_iid[j].name == NULL)
3042					continue;
3043
3044				printf("    iid %u use %d WWPN %#jx '%s'\n",
3045				    j, port->wwpn_iid[j].in_use,
3046				    (uintmax_t)port->wwpn_iid[j].wwpn,
3047				    port->wwpn_iid[j].name);
3048			}
3049		}
3050		printf("CTL Port information end\n");
3051		mtx_unlock(&softc->ctl_lock);
3052		/*
3053		 * XXX KDM calling this without a lock.  We'd likely want
3054		 * to drop the lock before calling the frontend's dump
3055		 * routine anyway.
3056		 */
3057		printf("CTL Frontends:\n");
3058		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3059			printf("  Frontend '%s'\n", fe->name);
3060			if (fe->fe_dump != NULL)
3061				fe->fe_dump();
3062		}
3063		printf("CTL Frontend information end\n");
3064		break;
3065	}
3066	case CTL_LUN_REQ: {
3067		struct ctl_lun_req *lun_req;
3068		struct ctl_backend_driver *backend;
3069
3070		lun_req = (struct ctl_lun_req *)addr;
3071
3072		backend = ctl_backend_find(lun_req->backend);
3073		if (backend == NULL) {
3074			lun_req->status = CTL_LUN_ERROR;
3075			snprintf(lun_req->error_str,
3076				 sizeof(lun_req->error_str),
3077				 "Backend \"%s\" not found.",
3078				 lun_req->backend);
3079			break;
3080		}
3081		if (lun_req->num_be_args > 0) {
3082			lun_req->kern_be_args = ctl_copyin_args(
3083				lun_req->num_be_args,
3084				lun_req->be_args,
3085				lun_req->error_str,
3086				sizeof(lun_req->error_str));
3087			if (lun_req->kern_be_args == NULL) {
3088				lun_req->status = CTL_LUN_ERROR;
3089				break;
3090			}
3091		}
3092
3093		retval = backend->ioctl(dev, cmd, addr, flag, td);
3094
3095		if (lun_req->num_be_args > 0) {
3096			ctl_copyout_args(lun_req->num_be_args,
3097				      lun_req->kern_be_args);
3098			ctl_free_args(lun_req->num_be_args,
3099				      lun_req->kern_be_args);
3100		}
3101		break;
3102	}
3103	case CTL_LUN_LIST: {
3104		struct sbuf *sb;
3105		struct ctl_lun *lun;
3106		struct ctl_lun_list *list;
3107		struct ctl_option *opt;
3108
3109		list = (struct ctl_lun_list *)addr;
3110
3111		/*
3112		 * Allocate a fixed length sbuf here, based on the length
3113		 * of the user's buffer.  We could allocate an auto-extending
3114		 * buffer, and then tell the user how much larger our
3115		 * amount of data is than his buffer, but that presents
3116		 * some problems:
3117		 *
3118		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3119		 *     we can't hold a lock while calling them with an
3120		 *     auto-extending buffer.
3121 		 *
3122		 * 2.  There is not currently a LUN reference counting
3123		 *     mechanism, outside of outstanding transactions on
3124		 *     the LUN's OOA queue.  So a LUN could go away on us
3125		 *     while we're getting the LUN number, backend-specific
3126		 *     information, etc.  Thus, given the way things
3127		 *     currently work, we need to hold the CTL lock while
3128		 *     grabbing LUN information.
3129		 *
3130		 * So, from the user's standpoint, the best thing to do is
3131		 * allocate what he thinks is a reasonable buffer length,
3132		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3133		 * double the buffer length and try again.  (And repeat
3134		 * that until he succeeds.)
3135		 */
3136		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3137		if (sb == NULL) {
3138			list->status = CTL_LUN_LIST_ERROR;
3139			snprintf(list->error_str, sizeof(list->error_str),
3140				 "Unable to allocate %d bytes for LUN list",
3141				 list->alloc_len);
3142			break;
3143		}
3144
3145		sbuf_printf(sb, "<ctllunlist>\n");
3146
3147		mtx_lock(&softc->ctl_lock);
3148		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3149			mtx_lock(&lun->lun_lock);
3150			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3151					     (uintmax_t)lun->lun);
3152
3153			/*
3154			 * Bail out as soon as we see that we've overfilled
3155			 * the buffer.
3156			 */
3157			if (retval != 0)
3158				break;
3159
3160			retval = sbuf_printf(sb, "\t<backend_type>%s"
3161					     "</backend_type>\n",
3162					     (lun->backend == NULL) ?  "none" :
3163					     lun->backend->name);
3164
3165			if (retval != 0)
3166				break;
3167
3168			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3169					     lun->be_lun->lun_type);
3170
3171			if (retval != 0)
3172				break;
3173
3174			if (lun->backend == NULL) {
3175				retval = sbuf_printf(sb, "</lun>\n");
3176				if (retval != 0)
3177					break;
3178				continue;
3179			}
3180
3181			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3182					     (lun->be_lun->maxlba > 0) ?
3183					     lun->be_lun->maxlba + 1 : 0);
3184
3185			if (retval != 0)
3186				break;
3187
3188			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3189					     lun->be_lun->blocksize);
3190
3191			if (retval != 0)
3192				break;
3193
3194			retval = sbuf_printf(sb, "\t<serial_number>");
3195
3196			if (retval != 0)
3197				break;
3198
3199			retval = ctl_sbuf_printf_esc(sb,
3200						     lun->be_lun->serial_num);
3201
3202			if (retval != 0)
3203				break;
3204
3205			retval = sbuf_printf(sb, "</serial_number>\n");
3206
3207			if (retval != 0)
3208				break;
3209
3210			retval = sbuf_printf(sb, "\t<device_id>");
3211
3212			if (retval != 0)
3213				break;
3214
3215			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3216
3217			if (retval != 0)
3218				break;
3219
3220			retval = sbuf_printf(sb, "</device_id>\n");
3221
3222			if (retval != 0)
3223				break;
3224
3225			if (lun->backend->lun_info != NULL) {
3226				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3227				if (retval != 0)
3228					break;
3229			}
3230			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3231				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3232				    opt->name, opt->value, opt->name);
3233				if (retval != 0)
3234					break;
3235			}
3236
3237			retval = sbuf_printf(sb, "</lun>\n");
3238
3239			if (retval != 0)
3240				break;
3241			mtx_unlock(&lun->lun_lock);
3242		}
3243		if (lun != NULL)
3244			mtx_unlock(&lun->lun_lock);
3245		mtx_unlock(&softc->ctl_lock);
3246
3247		if ((retval != 0)
3248		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3249			retval = 0;
3250			sbuf_delete(sb);
3251			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3252			snprintf(list->error_str, sizeof(list->error_str),
3253				 "Out of space, %d bytes is too small",
3254				 list->alloc_len);
3255			break;
3256		}
3257
3258		sbuf_finish(sb);
3259
3260		retval = copyout(sbuf_data(sb), list->lun_xml,
3261				 sbuf_len(sb) + 1);
3262
3263		list->fill_len = sbuf_len(sb) + 1;
3264		list->status = CTL_LUN_LIST_OK;
3265		sbuf_delete(sb);
3266		break;
3267	}
3268	case CTL_ISCSI: {
3269		struct ctl_iscsi *ci;
3270		struct ctl_frontend *fe;
3271
3272		ci = (struct ctl_iscsi *)addr;
3273
3274		fe = ctl_frontend_find("iscsi");
3275		if (fe == NULL) {
3276			ci->status = CTL_ISCSI_ERROR;
3277			snprintf(ci->error_str, sizeof(ci->error_str),
3278			    "Frontend \"iscsi\" not found.");
3279			break;
3280		}
3281
3282		retval = fe->ioctl(dev, cmd, addr, flag, td);
3283		break;
3284	}
3285	case CTL_PORT_REQ: {
3286		struct ctl_req *req;
3287		struct ctl_frontend *fe;
3288
3289		req = (struct ctl_req *)addr;
3290
3291		fe = ctl_frontend_find(req->driver);
3292		if (fe == NULL) {
3293			req->status = CTL_LUN_ERROR;
3294			snprintf(req->error_str, sizeof(req->error_str),
3295			    "Frontend \"%s\" not found.", req->driver);
3296			break;
3297		}
3298		if (req->num_args > 0) {
3299			req->kern_args = ctl_copyin_args(req->num_args,
3300			    req->args, req->error_str, sizeof(req->error_str));
3301			if (req->kern_args == NULL) {
3302				req->status = CTL_LUN_ERROR;
3303				break;
3304			}
3305		}
3306
3307		retval = fe->ioctl(dev, cmd, addr, flag, td);
3308
3309		if (req->num_args > 0) {
3310			ctl_copyout_args(req->num_args, req->kern_args);
3311			ctl_free_args(req->num_args, req->kern_args);
3312		}
3313		break;
3314	}
3315	case CTL_PORT_LIST: {
3316		struct sbuf *sb;
3317		struct ctl_port *port;
3318		struct ctl_lun_list *list;
3319		struct ctl_option *opt;
3320		int j;
3321
3322		list = (struct ctl_lun_list *)addr;
3323
3324		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3325		if (sb == NULL) {
3326			list->status = CTL_LUN_LIST_ERROR;
3327			snprintf(list->error_str, sizeof(list->error_str),
3328				 "Unable to allocate %d bytes for LUN list",
3329				 list->alloc_len);
3330			break;
3331		}
3332
3333		sbuf_printf(sb, "<ctlportlist>\n");
3334
3335		mtx_lock(&softc->ctl_lock);
3336		STAILQ_FOREACH(port, &softc->port_list, links) {
3337			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3338					     (uintmax_t)port->targ_port);
3339
3340			/*
3341			 * Bail out as soon as we see that we've overfilled
3342			 * the buffer.
3343			 */
3344			if (retval != 0)
3345				break;
3346
3347			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3348			    "</frontend_type>\n", port->frontend->name);
3349			if (retval != 0)
3350				break;
3351
3352			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3353					     port->port_type);
3354			if (retval != 0)
3355				break;
3356
3357			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3358			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3359			if (retval != 0)
3360				break;
3361
3362			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3363			    port->port_name);
3364			if (retval != 0)
3365				break;
3366
3367			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3368			    port->physical_port);
3369			if (retval != 0)
3370				break;
3371
3372			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3373			    port->virtual_port);
3374			if (retval != 0)
3375				break;
3376
3377			if (port->target_devid != NULL) {
3378				sbuf_printf(sb, "\t<target>");
3379				ctl_id_sbuf(port->target_devid, sb);
3380				sbuf_printf(sb, "</target>\n");
3381			}
3382
3383			if (port->port_devid != NULL) {
3384				sbuf_printf(sb, "\t<port>");
3385				ctl_id_sbuf(port->port_devid, sb);
3386				sbuf_printf(sb, "</port>\n");
3387			}
3388
3389			if (port->port_info != NULL) {
3390				retval = port->port_info(port->onoff_arg, sb);
3391				if (retval != 0)
3392					break;
3393			}
3394			STAILQ_FOREACH(opt, &port->options, links) {
3395				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3396				    opt->name, opt->value, opt->name);
3397				if (retval != 0)
3398					break;
3399			}
3400
3401			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3402				if (port->wwpn_iid[j].in_use == 0 ||
3403				    (port->wwpn_iid[j].wwpn == 0 &&
3404				     port->wwpn_iid[j].name == NULL))
3405					continue;
3406
3407				if (port->wwpn_iid[j].name != NULL)
3408					retval = sbuf_printf(sb,
3409					    "\t<initiator>%u %s</initiator>\n",
3410					    j, port->wwpn_iid[j].name);
3411				else
3412					retval = sbuf_printf(sb,
3413					    "\t<initiator>%u naa.%08jx</initiator>\n",
3414					    j, port->wwpn_iid[j].wwpn);
3415				if (retval != 0)
3416					break;
3417			}
3418			if (retval != 0)
3419				break;
3420
3421			retval = sbuf_printf(sb, "</targ_port>\n");
3422			if (retval != 0)
3423				break;
3424		}
3425		mtx_unlock(&softc->ctl_lock);
3426
3427		if ((retval != 0)
3428		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3429			retval = 0;
3430			sbuf_delete(sb);
3431			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3432			snprintf(list->error_str, sizeof(list->error_str),
3433				 "Out of space, %d bytes is too small",
3434				 list->alloc_len);
3435			break;
3436		}
3437
3438		sbuf_finish(sb);
3439
3440		retval = copyout(sbuf_data(sb), list->lun_xml,
3441				 sbuf_len(sb) + 1);
3442
3443		list->fill_len = sbuf_len(sb) + 1;
3444		list->status = CTL_LUN_LIST_OK;
3445		sbuf_delete(sb);
3446		break;
3447	}
3448	default: {
3449		/* XXX KDM should we fix this? */
3450#if 0
3451		struct ctl_backend_driver *backend;
3452		unsigned int type;
3453		int found;
3454
3455		found = 0;
3456
3457		/*
3458		 * We encode the backend type as the ioctl type for backend
3459		 * ioctls.  So parse it out here, and then search for a
3460		 * backend of this type.
3461		 */
3462		type = _IOC_TYPE(cmd);
3463
3464		STAILQ_FOREACH(backend, &softc->be_list, links) {
3465			if (backend->type == type) {
3466				found = 1;
3467				break;
3468			}
3469		}
3470		if (found == 0) {
3471			printf("ctl: unknown ioctl command %#lx or backend "
3472			       "%d\n", cmd, type);
3473			retval = EINVAL;
3474			break;
3475		}
3476		retval = backend->ioctl(dev, cmd, addr, flag, td);
3477#endif
3478		retval = ENOTTY;
3479		break;
3480	}
3481	}
3482	return (retval);
3483}
3484
3485uint32_t
3486ctl_get_initindex(struct ctl_nexus *nexus)
3487{
3488	if (nexus->targ_port < CTL_MAX_PORTS)
3489		return (nexus->initid.id +
3490			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3491	else
3492		return (nexus->initid.id +
3493		       ((nexus->targ_port - CTL_MAX_PORTS) *
3494			CTL_MAX_INIT_PER_PORT));
3495}
3496
3497uint32_t
3498ctl_get_resindex(struct ctl_nexus *nexus)
3499{
3500	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3501}
3502
3503uint32_t
3504ctl_port_idx(int port_num)
3505{
3506	if (port_num < CTL_MAX_PORTS)
3507		return(port_num);
3508	else
3509		return(port_num - CTL_MAX_PORTS);
3510}
3511
3512static uint32_t
3513ctl_map_lun(int port_num, uint32_t lun_id)
3514{
3515	struct ctl_port *port;
3516
3517	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3518	if (port == NULL)
3519		return (UINT32_MAX);
3520	if (port->lun_map == NULL)
3521		return (lun_id);
3522	return (port->lun_map(port->targ_lun_arg, lun_id));
3523}
3524
3525static uint32_t
3526ctl_map_lun_back(int port_num, uint32_t lun_id)
3527{
3528	struct ctl_port *port;
3529	uint32_t i;
3530
3531	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3532	if (port->lun_map == NULL)
3533		return (lun_id);
3534	for (i = 0; i < CTL_MAX_LUNS; i++) {
3535		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3536			return (i);
3537	}
3538	return (UINT32_MAX);
3539}
3540
3541/*
3542 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3543 * that are a power of 2.
3544 */
3545int
3546ctl_ffz(uint32_t *mask, uint32_t size)
3547{
3548	uint32_t num_chunks, num_pieces;
3549	int i, j;
3550
3551	num_chunks = (size >> 5);
3552	if (num_chunks == 0)
3553		num_chunks++;
3554	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3555
3556	for (i = 0; i < num_chunks; i++) {
3557		for (j = 0; j < num_pieces; j++) {
3558			if ((mask[i] & (1 << j)) == 0)
3559				return ((i << 5) + j);
3560		}
3561	}
3562
3563	return (-1);
3564}
3565
3566int
3567ctl_set_mask(uint32_t *mask, uint32_t bit)
3568{
3569	uint32_t chunk, piece;
3570
3571	chunk = bit >> 5;
3572	piece = bit % (sizeof(uint32_t) * 8);
3573
3574	if ((mask[chunk] & (1 << piece)) != 0)
3575		return (-1);
3576	else
3577		mask[chunk] |= (1 << piece);
3578
3579	return (0);
3580}
3581
3582int
3583ctl_clear_mask(uint32_t *mask, uint32_t bit)
3584{
3585	uint32_t chunk, piece;
3586
3587	chunk = bit >> 5;
3588	piece = bit % (sizeof(uint32_t) * 8);
3589
3590	if ((mask[chunk] & (1 << piece)) == 0)
3591		return (-1);
3592	else
3593		mask[chunk] &= ~(1 << piece);
3594
3595	return (0);
3596}
3597
3598int
3599ctl_is_set(uint32_t *mask, uint32_t bit)
3600{
3601	uint32_t chunk, piece;
3602
3603	chunk = bit >> 5;
3604	piece = bit % (sizeof(uint32_t) * 8);
3605
3606	if ((mask[chunk] & (1 << piece)) == 0)
3607		return (0);
3608	else
3609		return (1);
3610}
3611
3612#ifdef unused
3613/*
3614 * The bus, target and lun are optional, they can be filled in later.
3615 * can_wait is used to determine whether we can wait on the malloc or not.
3616 */
3617union ctl_io*
3618ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3619	      uint32_t targ_lun, int can_wait)
3620{
3621	union ctl_io *io;
3622
3623	if (can_wait)
3624		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3625	else
3626		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3627
3628	if (io != NULL) {
3629		io->io_hdr.io_type = io_type;
3630		io->io_hdr.targ_port = targ_port;
3631		/*
3632		 * XXX KDM this needs to change/go away.  We need to move
3633		 * to a preallocated pool of ctl_scsiio structures.
3634		 */
3635		io->io_hdr.nexus.targ_target.id = targ_target;
3636		io->io_hdr.nexus.targ_lun = targ_lun;
3637	}
3638
3639	return (io);
3640}
3641
3642void
3643ctl_kfree_io(union ctl_io *io)
3644{
3645	free(io, M_CTL);
3646}
3647#endif /* unused */
3648
3649/*
3650 * ctl_softc, pool_type, total_ctl_io are passed in.
3651 * npool is passed out.
3652 */
3653int
3654ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3655		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3656{
3657	uint32_t i;
3658	union ctl_io *cur_io, *next_io;
3659	struct ctl_io_pool *pool;
3660	int retval;
3661
3662	retval = 0;
3663
3664	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3665					    M_NOWAIT | M_ZERO);
3666	if (pool == NULL) {
3667		retval = ENOMEM;
3668		goto bailout;
3669	}
3670
3671	pool->type = pool_type;
3672	pool->ctl_softc = ctl_softc;
3673
3674	mtx_lock(&ctl_softc->pool_lock);
3675	pool->id = ctl_softc->cur_pool_id++;
3676	mtx_unlock(&ctl_softc->pool_lock);
3677
3678	pool->flags = CTL_POOL_FLAG_NONE;
3679	pool->refcount = 1;		/* Reference for validity. */
3680	STAILQ_INIT(&pool->free_queue);
3681
3682	/*
3683	 * XXX KDM other options here:
3684	 * - allocate a page at a time
3685	 * - allocate one big chunk of memory.
3686	 * Page allocation might work well, but would take a little more
3687	 * tracking.
3688	 */
3689	for (i = 0; i < total_ctl_io; i++) {
3690		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3691						M_NOWAIT);
3692		if (cur_io == NULL) {
3693			retval = ENOMEM;
3694			break;
3695		}
3696		cur_io->io_hdr.pool = pool;
3697		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3698		pool->total_ctl_io++;
3699		pool->free_ctl_io++;
3700	}
3701
3702	if (retval != 0) {
3703		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3704		     cur_io != NULL; cur_io = next_io) {
3705			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3706							      links);
3707			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3708				      ctl_io_hdr, links);
3709			free(cur_io, M_CTLIO);
3710		}
3711
3712		free(pool, M_CTL);
3713		goto bailout;
3714	}
3715	mtx_lock(&ctl_softc->pool_lock);
3716	ctl_softc->num_pools++;
3717	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3718	/*
3719	 * Increment our usage count if this is an external consumer, so we
3720	 * can't get unloaded until the external consumer (most likely a
3721	 * FETD) unloads and frees his pool.
3722	 *
3723	 * XXX KDM will this increment the caller's module use count, or
3724	 * mine?
3725	 */
3726#if 0
3727	if ((pool_type != CTL_POOL_EMERGENCY)
3728	 && (pool_type != CTL_POOL_INTERNAL)
3729	 && (pool_type != CTL_POOL_4OTHERSC))
3730		MOD_INC_USE_COUNT;
3731#endif
3732
3733	mtx_unlock(&ctl_softc->pool_lock);
3734
3735	*npool = pool;
3736
3737bailout:
3738
3739	return (retval);
3740}
3741
3742static int
3743ctl_pool_acquire(struct ctl_io_pool *pool)
3744{
3745
3746	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3747
3748	if (pool->flags & CTL_POOL_FLAG_INVALID)
3749		return (EINVAL);
3750
3751	pool->refcount++;
3752
3753	return (0);
3754}
3755
3756static void
3757ctl_pool_release(struct ctl_io_pool *pool)
3758{
3759	struct ctl_softc *ctl_softc = pool->ctl_softc;
3760	union ctl_io *io;
3761
3762	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3763
3764	if (--pool->refcount != 0)
3765		return;
3766
3767	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3768		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3769			      links);
3770		free(io, M_CTLIO);
3771	}
3772
3773	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3774	ctl_softc->num_pools--;
3775
3776	/*
3777	 * XXX KDM will this decrement the caller's usage count or mine?
3778	 */
3779#if 0
3780	if ((pool->type != CTL_POOL_EMERGENCY)
3781	 && (pool->type != CTL_POOL_INTERNAL)
3782	 && (pool->type != CTL_POOL_4OTHERSC))
3783		MOD_DEC_USE_COUNT;
3784#endif
3785
3786	free(pool, M_CTL);
3787}
3788
3789void
3790ctl_pool_free(struct ctl_io_pool *pool)
3791{
3792	struct ctl_softc *ctl_softc;
3793
3794	if (pool == NULL)
3795		return;
3796
3797	ctl_softc = pool->ctl_softc;
3798	mtx_lock(&ctl_softc->pool_lock);
3799	pool->flags |= CTL_POOL_FLAG_INVALID;
3800	ctl_pool_release(pool);
3801	mtx_unlock(&ctl_softc->pool_lock);
3802}
3803
3804/*
3805 * This routine does not block (except for spinlocks of course).
3806 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3807 * possible.
3808 */
3809union ctl_io *
3810ctl_alloc_io(void *pool_ref)
3811{
3812	union ctl_io *io;
3813	struct ctl_softc *ctl_softc;
3814	struct ctl_io_pool *pool, *npool;
3815	struct ctl_io_pool *emergency_pool;
3816
3817	pool = (struct ctl_io_pool *)pool_ref;
3818
3819	if (pool == NULL) {
3820		printf("%s: pool is NULL\n", __func__);
3821		return (NULL);
3822	}
3823
3824	emergency_pool = NULL;
3825
3826	ctl_softc = pool->ctl_softc;
3827
3828	mtx_lock(&ctl_softc->pool_lock);
3829	/*
3830	 * First, try to get the io structure from the user's pool.
3831	 */
3832	if (ctl_pool_acquire(pool) == 0) {
3833		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3834		if (io != NULL) {
3835			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3836			pool->total_allocated++;
3837			pool->free_ctl_io--;
3838			mtx_unlock(&ctl_softc->pool_lock);
3839			return (io);
3840		} else
3841			ctl_pool_release(pool);
3842	}
3843	/*
3844	 * If he doesn't have any io structures left, search for an
3845	 * emergency pool and grab one from there.
3846	 */
3847	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3848		if (npool->type != CTL_POOL_EMERGENCY)
3849			continue;
3850
3851		if (ctl_pool_acquire(npool) != 0)
3852			continue;
3853
3854		emergency_pool = npool;
3855
3856		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3857		if (io != NULL) {
3858			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3859			npool->total_allocated++;
3860			npool->free_ctl_io--;
3861			mtx_unlock(&ctl_softc->pool_lock);
3862			return (io);
3863		} else
3864			ctl_pool_release(npool);
3865	}
3866
3867	/* Drop the spinlock before we malloc */
3868	mtx_unlock(&ctl_softc->pool_lock);
3869
3870	/*
3871	 * The emergency pool (if it exists) didn't have one, so try an
3872	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3873	 */
3874	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3875	if (io != NULL) {
3876		/*
3877		 * If the emergency pool exists but is empty, add this
3878		 * ctl_io to its list when it gets freed.
3879		 */
3880		if (emergency_pool != NULL) {
3881			mtx_lock(&ctl_softc->pool_lock);
3882			if (ctl_pool_acquire(emergency_pool) == 0) {
3883				io->io_hdr.pool = emergency_pool;
3884				emergency_pool->total_ctl_io++;
3885				/*
3886				 * Need to bump this, otherwise
3887				 * total_allocated and total_freed won't
3888				 * match when we no longer have anything
3889				 * outstanding.
3890				 */
3891				emergency_pool->total_allocated++;
3892			}
3893			mtx_unlock(&ctl_softc->pool_lock);
3894		} else
3895			io->io_hdr.pool = NULL;
3896	}
3897
3898	return (io);
3899}
3900
3901void
3902ctl_free_io(union ctl_io *io)
3903{
3904	if (io == NULL)
3905		return;
3906
3907	/*
3908	 * If this ctl_io has a pool, return it to that pool.
3909	 */
3910	if (io->io_hdr.pool != NULL) {
3911		struct ctl_io_pool *pool;
3912
3913		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3914		mtx_lock(&pool->ctl_softc->pool_lock);
3915		io->io_hdr.io_type = 0xff;
3916		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3917		pool->total_freed++;
3918		pool->free_ctl_io++;
3919		ctl_pool_release(pool);
3920		mtx_unlock(&pool->ctl_softc->pool_lock);
3921	} else {
3922		/*
3923		 * Otherwise, just free it.  We probably malloced it and
3924		 * the emergency pool wasn't available.
3925		 */
3926		free(io, M_CTLIO);
3927	}
3928
3929}
3930
3931void
3932ctl_zero_io(union ctl_io *io)
3933{
3934	void *pool_ref;
3935
3936	if (io == NULL)
3937		return;
3938
3939	/*
3940	 * May need to preserve linked list pointers at some point too.
3941	 */
3942	pool_ref = io->io_hdr.pool;
3943
3944	memset(io, 0, sizeof(*io));
3945
3946	io->io_hdr.pool = pool_ref;
3947}
3948
3949/*
3950 * This routine is currently used for internal copies of ctl_ios that need
3951 * to persist for some reason after we've already returned status to the
3952 * FETD.  (Thus the flag set.)
3953 *
3954 * XXX XXX
3955 * Note that this makes a blind copy of all fields in the ctl_io, except
3956 * for the pool reference.  This includes any memory that has been
3957 * allocated!  That memory will no longer be valid after done has been
3958 * called, so this would be VERY DANGEROUS for command that actually does
3959 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3960 * start and stop commands, which don't transfer any data, so this is not a
3961 * problem.  If it is used for anything else, the caller would also need to
3962 * allocate data buffer space and this routine would need to be modified to
3963 * copy the data buffer(s) as well.
3964 */
3965void
3966ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3967{
3968	void *pool_ref;
3969
3970	if ((src == NULL)
3971	 || (dest == NULL))
3972		return;
3973
3974	/*
3975	 * May need to preserve linked list pointers at some point too.
3976	 */
3977	pool_ref = dest->io_hdr.pool;
3978
3979	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3980
3981	dest->io_hdr.pool = pool_ref;
3982	/*
3983	 * We need to know that this is an internal copy, and doesn't need
3984	 * to get passed back to the FETD that allocated it.
3985	 */
3986	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3987}
3988
3989/*
3990 * This routine could be used in the future to load default and/or saved
3991 * mode page parameters for a particuar lun.
3992 */
3993static int
3994ctl_init_page_index(struct ctl_lun *lun)
3995{
3996	int i;
3997	struct ctl_page_index *page_index;
3998	const char *value;
3999
4000	memcpy(&lun->mode_pages.index, page_index_template,
4001	       sizeof(page_index_template));
4002
4003	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4004
4005		page_index = &lun->mode_pages.index[i];
4006		/*
4007		 * If this is a disk-only mode page, there's no point in
4008		 * setting it up.  For some pages, we have to have some
4009		 * basic information about the disk in order to calculate the
4010		 * mode page data.
4011		 */
4012		if ((lun->be_lun->lun_type != T_DIRECT)
4013		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4014			continue;
4015
4016		switch (page_index->page_code & SMPH_PC_MASK) {
4017		case SMS_RW_ERROR_RECOVERY_PAGE: {
4018			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4019				panic("subpage is incorrect!");
4020			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4021			       &rw_er_page_default,
4022			       sizeof(rw_er_page_default));
4023			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4024			       &rw_er_page_changeable,
4025			       sizeof(rw_er_page_changeable));
4026			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4027			       &rw_er_page_default,
4028			       sizeof(rw_er_page_default));
4029			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4030			       &rw_er_page_default,
4031			       sizeof(rw_er_page_default));
4032			page_index->page_data =
4033				(uint8_t *)lun->mode_pages.rw_er_page;
4034			break;
4035		}
4036		case SMS_FORMAT_DEVICE_PAGE: {
4037			struct scsi_format_page *format_page;
4038
4039			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4040				panic("subpage is incorrect!");
4041
4042			/*
4043			 * Sectors per track are set above.  Bytes per
4044			 * sector need to be set here on a per-LUN basis.
4045			 */
4046			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4047			       &format_page_default,
4048			       sizeof(format_page_default));
4049			memcpy(&lun->mode_pages.format_page[
4050			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4051			       sizeof(format_page_changeable));
4052			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4053			       &format_page_default,
4054			       sizeof(format_page_default));
4055			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4056			       &format_page_default,
4057			       sizeof(format_page_default));
4058
4059			format_page = &lun->mode_pages.format_page[
4060				CTL_PAGE_CURRENT];
4061			scsi_ulto2b(lun->be_lun->blocksize,
4062				    format_page->bytes_per_sector);
4063
4064			format_page = &lun->mode_pages.format_page[
4065				CTL_PAGE_DEFAULT];
4066			scsi_ulto2b(lun->be_lun->blocksize,
4067				    format_page->bytes_per_sector);
4068
4069			format_page = &lun->mode_pages.format_page[
4070				CTL_PAGE_SAVED];
4071			scsi_ulto2b(lun->be_lun->blocksize,
4072				    format_page->bytes_per_sector);
4073
4074			page_index->page_data =
4075				(uint8_t *)lun->mode_pages.format_page;
4076			break;
4077		}
4078		case SMS_RIGID_DISK_PAGE: {
4079			struct scsi_rigid_disk_page *rigid_disk_page;
4080			uint32_t sectors_per_cylinder;
4081			uint64_t cylinders;
4082#ifndef	__XSCALE__
4083			int shift;
4084#endif /* !__XSCALE__ */
4085
4086			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4087				panic("invalid subpage value %d",
4088				      page_index->subpage);
4089
4090			/*
4091			 * Rotation rate and sectors per track are set
4092			 * above.  We calculate the cylinders here based on
4093			 * capacity.  Due to the number of heads and
4094			 * sectors per track we're using, smaller arrays
4095			 * may turn out to have 0 cylinders.  Linux and
4096			 * FreeBSD don't pay attention to these mode pages
4097			 * to figure out capacity, but Solaris does.  It
4098			 * seems to deal with 0 cylinders just fine, and
4099			 * works out a fake geometry based on the capacity.
4100			 */
4101			memcpy(&lun->mode_pages.rigid_disk_page[
4102			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4103			       sizeof(rigid_disk_page_default));
4104			memcpy(&lun->mode_pages.rigid_disk_page[
4105			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4106			       sizeof(rigid_disk_page_changeable));
4107			memcpy(&lun->mode_pages.rigid_disk_page[
4108			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4109			       sizeof(rigid_disk_page_default));
4110			memcpy(&lun->mode_pages.rigid_disk_page[
4111			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4112			       sizeof(rigid_disk_page_default));
4113
4114			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4115				CTL_DEFAULT_HEADS;
4116
4117			/*
4118			 * The divide method here will be more accurate,
4119			 * probably, but results in floating point being
4120			 * used in the kernel on i386 (__udivdi3()).  On the
4121			 * XScale, though, __udivdi3() is implemented in
4122			 * software.
4123			 *
4124			 * The shift method for cylinder calculation is
4125			 * accurate if sectors_per_cylinder is a power of
4126			 * 2.  Otherwise it might be slightly off -- you
4127			 * might have a bit of a truncation problem.
4128			 */
4129#ifdef	__XSCALE__
4130			cylinders = (lun->be_lun->maxlba + 1) /
4131				sectors_per_cylinder;
4132#else
4133			for (shift = 31; shift > 0; shift--) {
4134				if (sectors_per_cylinder & (1 << shift))
4135					break;
4136			}
4137			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4138#endif
4139
4140			/*
4141			 * We've basically got 3 bytes, or 24 bits for the
4142			 * cylinder size in the mode page.  If we're over,
4143			 * just round down to 2^24.
4144			 */
4145			if (cylinders > 0xffffff)
4146				cylinders = 0xffffff;
4147
4148			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4149				CTL_PAGE_CURRENT];
4150			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4151
4152			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4153				CTL_PAGE_DEFAULT];
4154			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4155
4156			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4157				CTL_PAGE_SAVED];
4158			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4159
4160			page_index->page_data =
4161				(uint8_t *)lun->mode_pages.rigid_disk_page;
4162			break;
4163		}
4164		case SMS_CACHING_PAGE: {
4165			struct scsi_caching_page *caching_page;
4166
4167			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4168				panic("invalid subpage value %d",
4169				      page_index->subpage);
4170			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4171			       &caching_page_default,
4172			       sizeof(caching_page_default));
4173			memcpy(&lun->mode_pages.caching_page[
4174			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4175			       sizeof(caching_page_changeable));
4176			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4177			       &caching_page_default,
4178			       sizeof(caching_page_default));
4179			caching_page = &lun->mode_pages.caching_page[
4180			    CTL_PAGE_SAVED];
4181			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4182			if (value != NULL && strcmp(value, "off") == 0)
4183				caching_page->flags1 &= ~SCP_WCE;
4184			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4185			if (value != NULL && strcmp(value, "off") == 0)
4186				caching_page->flags1 |= SCP_RCD;
4187			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4188			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4189			       sizeof(caching_page_default));
4190			page_index->page_data =
4191				(uint8_t *)lun->mode_pages.caching_page;
4192			break;
4193		}
4194		case SMS_CONTROL_MODE_PAGE: {
4195			struct scsi_control_page *control_page;
4196
4197			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4198				panic("invalid subpage value %d",
4199				      page_index->subpage);
4200
4201			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4202			       &control_page_default,
4203			       sizeof(control_page_default));
4204			memcpy(&lun->mode_pages.control_page[
4205			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4206			       sizeof(control_page_changeable));
4207			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4208			       &control_page_default,
4209			       sizeof(control_page_default));
4210			control_page = &lun->mode_pages.control_page[
4211			    CTL_PAGE_SAVED];
4212			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4213			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4214				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4215				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4216			}
4217			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4218			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4219			       sizeof(control_page_default));
4220			page_index->page_data =
4221				(uint8_t *)lun->mode_pages.control_page;
4222			break;
4223
4224		}
4225		case SMS_INFO_EXCEPTIONS_PAGE: {
4226			switch (page_index->subpage) {
4227			case SMS_SUBPAGE_PAGE_0:
4228				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4229				       &ie_page_default,
4230				       sizeof(ie_page_default));
4231				memcpy(&lun->mode_pages.ie_page[
4232				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4233				       sizeof(ie_page_changeable));
4234				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4235				       &ie_page_default,
4236				       sizeof(ie_page_default));
4237				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4238				       &ie_page_default,
4239				       sizeof(ie_page_default));
4240				page_index->page_data =
4241					(uint8_t *)lun->mode_pages.ie_page;
4242				break;
4243			case 0x02:
4244				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4245				       &lbp_page_default,
4246				       sizeof(lbp_page_default));
4247				memcpy(&lun->mode_pages.lbp_page[
4248				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4249				       sizeof(lbp_page_changeable));
4250				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4251				       &lbp_page_default,
4252				       sizeof(lbp_page_default));
4253				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4254				       &lbp_page_default,
4255				       sizeof(lbp_page_default));
4256				page_index->page_data =
4257					(uint8_t *)lun->mode_pages.lbp_page;
4258			}
4259			break;
4260		}
4261		case SMS_VENDOR_SPECIFIC_PAGE:{
4262			switch (page_index->subpage) {
4263			case DBGCNF_SUBPAGE_CODE: {
4264				struct copan_debugconf_subpage *current_page,
4265							       *saved_page;
4266
4267				memcpy(&lun->mode_pages.debugconf_subpage[
4268				       CTL_PAGE_CURRENT],
4269				       &debugconf_page_default,
4270				       sizeof(debugconf_page_default));
4271				memcpy(&lun->mode_pages.debugconf_subpage[
4272				       CTL_PAGE_CHANGEABLE],
4273				       &debugconf_page_changeable,
4274				       sizeof(debugconf_page_changeable));
4275				memcpy(&lun->mode_pages.debugconf_subpage[
4276				       CTL_PAGE_DEFAULT],
4277				       &debugconf_page_default,
4278				       sizeof(debugconf_page_default));
4279				memcpy(&lun->mode_pages.debugconf_subpage[
4280				       CTL_PAGE_SAVED],
4281				       &debugconf_page_default,
4282				       sizeof(debugconf_page_default));
4283				page_index->page_data =
4284					(uint8_t *)lun->mode_pages.debugconf_subpage;
4285
4286				current_page = (struct copan_debugconf_subpage *)
4287					(page_index->page_data +
4288					 (page_index->page_len *
4289					  CTL_PAGE_CURRENT));
4290				saved_page = (struct copan_debugconf_subpage *)
4291					(page_index->page_data +
4292					 (page_index->page_len *
4293					  CTL_PAGE_SAVED));
4294				break;
4295			}
4296			default:
4297				panic("invalid subpage value %d",
4298				      page_index->subpage);
4299				break;
4300			}
4301   			break;
4302		}
4303		default:
4304			panic("invalid page value %d",
4305			      page_index->page_code & SMPH_PC_MASK);
4306			break;
4307    	}
4308	}
4309
4310	return (CTL_RETVAL_COMPLETE);
4311}
4312
4313static int
4314ctl_init_log_page_index(struct ctl_lun *lun)
4315{
4316	struct ctl_page_index *page_index;
4317	int i, j, prev;
4318
4319	memcpy(&lun->log_pages.index, log_page_index_template,
4320	       sizeof(log_page_index_template));
4321
4322	prev = -1;
4323	for (i = 0, j = 0; i < CTL_NUM_LOG_PAGES; i++) {
4324
4325		page_index = &lun->log_pages.index[i];
4326		/*
4327		 * If this is a disk-only mode page, there's no point in
4328		 * setting it up.  For some pages, we have to have some
4329		 * basic information about the disk in order to calculate the
4330		 * mode page data.
4331		 */
4332		if ((lun->be_lun->lun_type != T_DIRECT)
4333		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4334			continue;
4335
4336		if (page_index->page_code != prev) {
4337			lun->log_pages.pages_page[j] = page_index->page_code;
4338			prev = page_index->page_code;
4339			j++;
4340		}
4341		lun->log_pages.subpages_page[i*2] = page_index->page_code;
4342		lun->log_pages.subpages_page[i*2+1] = page_index->subpage;
4343	}
4344	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4345	lun->log_pages.index[0].page_len = j;
4346	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4347	lun->log_pages.index[1].page_len = i * 2;
4348
4349	return (CTL_RETVAL_COMPLETE);
4350}
4351
4352/*
4353 * LUN allocation.
4354 *
4355 * Requirements:
4356 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4357 *   wants us to allocate the LUN and he can block.
4358 * - ctl_softc is always set
4359 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4360 *
4361 * Returns 0 for success, non-zero (errno) for failure.
4362 */
4363static int
4364ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4365	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4366{
4367	struct ctl_lun *nlun, *lun;
4368	struct ctl_port *port;
4369	struct scsi_vpd_id_descriptor *desc;
4370	struct scsi_vpd_id_t10 *t10id;
4371	const char *eui, *naa, *scsiname, *vendor, *value;
4372	int lun_number, i, lun_malloced;
4373	int devidlen, idlen1, idlen2 = 0, len;
4374
4375	if (be_lun == NULL)
4376		return (EINVAL);
4377
4378	/*
4379	 * We currently only support Direct Access or Processor LUN types.
4380	 */
4381	switch (be_lun->lun_type) {
4382	case T_DIRECT:
4383		break;
4384	case T_PROCESSOR:
4385		break;
4386	case T_SEQUENTIAL:
4387	case T_CHANGER:
4388	default:
4389		be_lun->lun_config_status(be_lun->be_lun,
4390					  CTL_LUN_CONFIG_FAILURE);
4391		break;
4392	}
4393	if (ctl_lun == NULL) {
4394		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4395		lun_malloced = 1;
4396	} else {
4397		lun_malloced = 0;
4398		lun = ctl_lun;
4399	}
4400
4401	memset(lun, 0, sizeof(*lun));
4402	if (lun_malloced)
4403		lun->flags = CTL_LUN_MALLOCED;
4404
4405	/* Generate LUN ID. */
4406	devidlen = max(CTL_DEVID_MIN_LEN,
4407	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4408	idlen1 = sizeof(*t10id) + devidlen;
4409	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4410	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4411	if (scsiname != NULL) {
4412		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4413		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4414	}
4415	eui = ctl_get_opt(&be_lun->options, "eui");
4416	if (eui != NULL) {
4417		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4418	}
4419	naa = ctl_get_opt(&be_lun->options, "naa");
4420	if (naa != NULL) {
4421		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4422	}
4423	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4424	    M_CTL, M_WAITOK | M_ZERO);
4425	lun->lun_devid->len = len;
4426	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4427	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4428	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4429	desc->length = idlen1;
4430	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4431	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4432	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4433		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4434	} else {
4435		strncpy(t10id->vendor, vendor,
4436		    min(sizeof(t10id->vendor), strlen(vendor)));
4437	}
4438	strncpy((char *)t10id->vendor_spec_id,
4439	    (char *)be_lun->device_id, devidlen);
4440	if (scsiname != NULL) {
4441		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4442		    desc->length);
4443		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4444		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4445		    SVPD_ID_TYPE_SCSI_NAME;
4446		desc->length = idlen2;
4447		strlcpy(desc->identifier, scsiname, idlen2);
4448	}
4449	if (eui != NULL) {
4450		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4451		    desc->length);
4452		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4453		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4454		    SVPD_ID_TYPE_EUI64;
4455		desc->length = 8;
4456		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4457	}
4458	if (naa != NULL) {
4459		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4460		    desc->length);
4461		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4462		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4463		    SVPD_ID_TYPE_NAA;
4464		desc->length = 8;
4465		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4466	}
4467
4468	mtx_lock(&ctl_softc->ctl_lock);
4469	/*
4470	 * See if the caller requested a particular LUN number.  If so, see
4471	 * if it is available.  Otherwise, allocate the first available LUN.
4472	 */
4473	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4474		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4475		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4476			mtx_unlock(&ctl_softc->ctl_lock);
4477			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4478				printf("ctl: requested LUN ID %d is higher "
4479				       "than CTL_MAX_LUNS - 1 (%d)\n",
4480				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4481			} else {
4482				/*
4483				 * XXX KDM return an error, or just assign
4484				 * another LUN ID in this case??
4485				 */
4486				printf("ctl: requested LUN ID %d is already "
4487				       "in use\n", be_lun->req_lun_id);
4488			}
4489			if (lun->flags & CTL_LUN_MALLOCED)
4490				free(lun, M_CTL);
4491			be_lun->lun_config_status(be_lun->be_lun,
4492						  CTL_LUN_CONFIG_FAILURE);
4493			return (ENOSPC);
4494		}
4495		lun_number = be_lun->req_lun_id;
4496	} else {
4497		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4498		if (lun_number == -1) {
4499			mtx_unlock(&ctl_softc->ctl_lock);
4500			printf("ctl: can't allocate LUN on target %ju, out of "
4501			       "LUNs\n", (uintmax_t)target_id.id);
4502			if (lun->flags & CTL_LUN_MALLOCED)
4503				free(lun, M_CTL);
4504			be_lun->lun_config_status(be_lun->be_lun,
4505						  CTL_LUN_CONFIG_FAILURE);
4506			return (ENOSPC);
4507		}
4508	}
4509	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4510
4511	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4512	lun->target = target_id;
4513	lun->lun = lun_number;
4514	lun->be_lun = be_lun;
4515	/*
4516	 * The processor LUN is always enabled.  Disk LUNs come on line
4517	 * disabled, and must be enabled by the backend.
4518	 */
4519	lun->flags |= CTL_LUN_DISABLED;
4520	lun->backend = be_lun->be;
4521	be_lun->ctl_lun = lun;
4522	be_lun->lun_id = lun_number;
4523	atomic_add_int(&be_lun->be->num_luns, 1);
4524	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4525		lun->flags |= CTL_LUN_OFFLINE;
4526
4527	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4528		lun->flags |= CTL_LUN_STOPPED;
4529
4530	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4531		lun->flags |= CTL_LUN_INOPERABLE;
4532
4533	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4534		lun->flags |= CTL_LUN_PRIMARY_SC;
4535
4536	value = ctl_get_opt(&be_lun->options, "readonly");
4537	if (value != NULL && strcmp(value, "on") == 0)
4538		lun->flags |= CTL_LUN_READONLY;
4539
4540	lun->ctl_softc = ctl_softc;
4541	TAILQ_INIT(&lun->ooa_queue);
4542	TAILQ_INIT(&lun->blocked_queue);
4543	STAILQ_INIT(&lun->error_list);
4544	ctl_tpc_lun_init(lun);
4545
4546	/*
4547	 * Initialize the mode and log page index.
4548	 */
4549	ctl_init_page_index(lun);
4550	ctl_init_log_page_index(lun);
4551
4552	/*
4553	 * Set the poweron UA for all initiators on this LUN only.
4554	 */
4555	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4556		lun->pending_ua[i] = CTL_UA_POWERON;
4557
4558	/*
4559	 * Now, before we insert this lun on the lun list, set the lun
4560	 * inventory changed UA for all other luns.
4561	 */
4562	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4563		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4564			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4565		}
4566	}
4567
4568	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4569
4570	ctl_softc->ctl_luns[lun_number] = lun;
4571
4572	ctl_softc->num_luns++;
4573
4574	/* Setup statistics gathering */
4575	lun->stats.device_type = be_lun->lun_type;
4576	lun->stats.lun_number = lun_number;
4577	if (lun->stats.device_type == T_DIRECT)
4578		lun->stats.blocksize = be_lun->blocksize;
4579	else
4580		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4581	for (i = 0;i < CTL_MAX_PORTS;i++)
4582		lun->stats.ports[i].targ_port = i;
4583
4584	mtx_unlock(&ctl_softc->ctl_lock);
4585
4586	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4587
4588	/*
4589	 * Run through each registered FETD and bring it online if it isn't
4590	 * already.  Enable the target ID if it hasn't been enabled, and
4591	 * enable this particular LUN.
4592	 */
4593	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4594		int retval;
4595
4596		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4597		if (retval != 0) {
4598			printf("ctl_alloc_lun: FETD %s port %d returned error "
4599			       "%d for lun_enable on target %ju lun %d\n",
4600			       port->port_name, port->targ_port, retval,
4601			       (uintmax_t)target_id.id, lun_number);
4602		} else
4603			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4604	}
4605	return (0);
4606}
4607
4608/*
4609 * Delete a LUN.
4610 * Assumptions:
4611 * - LUN has already been marked invalid and any pending I/O has been taken
4612 *   care of.
4613 */
4614static int
4615ctl_free_lun(struct ctl_lun *lun)
4616{
4617	struct ctl_softc *softc;
4618#if 0
4619	struct ctl_port *port;
4620#endif
4621	struct ctl_lun *nlun;
4622	int i;
4623
4624	softc = lun->ctl_softc;
4625
4626	mtx_assert(&softc->ctl_lock, MA_OWNED);
4627
4628	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4629
4630	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4631
4632	softc->ctl_luns[lun->lun] = NULL;
4633
4634	if (!TAILQ_EMPTY(&lun->ooa_queue))
4635		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4636
4637	softc->num_luns--;
4638
4639	/*
4640	 * XXX KDM this scheme only works for a single target/multiple LUN
4641	 * setup.  It needs to be revamped for a multiple target scheme.
4642	 *
4643	 * XXX KDM this results in port->lun_disable() getting called twice,
4644	 * once when ctl_disable_lun() is called, and a second time here.
4645	 * We really need to re-think the LUN disable semantics.  There
4646	 * should probably be several steps/levels to LUN removal:
4647	 *  - disable
4648	 *  - invalidate
4649	 *  - free
4650 	 *
4651	 * Right now we only have a disable method when communicating to
4652	 * the front end ports, at least for individual LUNs.
4653	 */
4654#if 0
4655	STAILQ_FOREACH(port, &softc->port_list, links) {
4656		int retval;
4657
4658		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4659					 lun->lun);
4660		if (retval != 0) {
4661			printf("ctl_free_lun: FETD %s port %d returned error "
4662			       "%d for lun_disable on target %ju lun %jd\n",
4663			       port->port_name, port->targ_port, retval,
4664			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4665		}
4666
4667		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4668			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4669
4670			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4671			if (retval != 0) {
4672				printf("ctl_free_lun: FETD %s port %d "
4673				       "returned error %d for targ_disable on "
4674				       "target %ju\n", port->port_name,
4675				       port->targ_port, retval,
4676				       (uintmax_t)lun->target.id);
4677			} else
4678				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4679
4680			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4681				continue;
4682
4683#if 0
4684			port->port_offline(port->onoff_arg);
4685			port->status &= ~CTL_PORT_STATUS_ONLINE;
4686#endif
4687		}
4688	}
4689#endif
4690
4691	/*
4692	 * Tell the backend to free resources, if this LUN has a backend.
4693	 */
4694	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4695	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4696
4697	ctl_tpc_lun_shutdown(lun);
4698	mtx_destroy(&lun->lun_lock);
4699	free(lun->lun_devid, M_CTL);
4700	if (lun->flags & CTL_LUN_MALLOCED)
4701		free(lun, M_CTL);
4702
4703	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4704		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4705			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4706		}
4707	}
4708
4709	return (0);
4710}
4711
4712static void
4713ctl_create_lun(struct ctl_be_lun *be_lun)
4714{
4715	struct ctl_softc *ctl_softc;
4716
4717	ctl_softc = control_softc;
4718
4719	/*
4720	 * ctl_alloc_lun() should handle all potential failure cases.
4721	 */
4722	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4723}
4724
4725int
4726ctl_add_lun(struct ctl_be_lun *be_lun)
4727{
4728	struct ctl_softc *ctl_softc = control_softc;
4729
4730	mtx_lock(&ctl_softc->ctl_lock);
4731	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4732	mtx_unlock(&ctl_softc->ctl_lock);
4733	wakeup(&ctl_softc->pending_lun_queue);
4734
4735	return (0);
4736}
4737
4738int
4739ctl_enable_lun(struct ctl_be_lun *be_lun)
4740{
4741	struct ctl_softc *ctl_softc;
4742	struct ctl_port *port, *nport;
4743	struct ctl_lun *lun;
4744	int retval;
4745
4746	ctl_softc = control_softc;
4747
4748	lun = (struct ctl_lun *)be_lun->ctl_lun;
4749
4750	mtx_lock(&ctl_softc->ctl_lock);
4751	mtx_lock(&lun->lun_lock);
4752	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4753		/*
4754		 * eh?  Why did we get called if the LUN is already
4755		 * enabled?
4756		 */
4757		mtx_unlock(&lun->lun_lock);
4758		mtx_unlock(&ctl_softc->ctl_lock);
4759		return (0);
4760	}
4761	lun->flags &= ~CTL_LUN_DISABLED;
4762	mtx_unlock(&lun->lun_lock);
4763
4764	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4765		nport = STAILQ_NEXT(port, links);
4766
4767		/*
4768		 * Drop the lock while we call the FETD's enable routine.
4769		 * This can lead to a callback into CTL (at least in the
4770		 * case of the internal initiator frontend.
4771		 */
4772		mtx_unlock(&ctl_softc->ctl_lock);
4773		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4774		mtx_lock(&ctl_softc->ctl_lock);
4775		if (retval != 0) {
4776			printf("%s: FETD %s port %d returned error "
4777			       "%d for lun_enable on target %ju lun %jd\n",
4778			       __func__, port->port_name, port->targ_port, retval,
4779			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4780		}
4781#if 0
4782		 else {
4783            /* NOTE:  TODO:  why does lun enable affect port status? */
4784			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4785		}
4786#endif
4787	}
4788
4789	mtx_unlock(&ctl_softc->ctl_lock);
4790
4791	return (0);
4792}
4793
4794int
4795ctl_disable_lun(struct ctl_be_lun *be_lun)
4796{
4797	struct ctl_softc *ctl_softc;
4798	struct ctl_port *port;
4799	struct ctl_lun *lun;
4800	int retval;
4801
4802	ctl_softc = control_softc;
4803
4804	lun = (struct ctl_lun *)be_lun->ctl_lun;
4805
4806	mtx_lock(&ctl_softc->ctl_lock);
4807	mtx_lock(&lun->lun_lock);
4808	if (lun->flags & CTL_LUN_DISABLED) {
4809		mtx_unlock(&lun->lun_lock);
4810		mtx_unlock(&ctl_softc->ctl_lock);
4811		return (0);
4812	}
4813	lun->flags |= CTL_LUN_DISABLED;
4814	mtx_unlock(&lun->lun_lock);
4815
4816	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4817		mtx_unlock(&ctl_softc->ctl_lock);
4818		/*
4819		 * Drop the lock before we call the frontend's disable
4820		 * routine, to avoid lock order reversals.
4821		 *
4822		 * XXX KDM what happens if the frontend list changes while
4823		 * we're traversing it?  It's unlikely, but should be handled.
4824		 */
4825		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4826					 lun->lun);
4827		mtx_lock(&ctl_softc->ctl_lock);
4828		if (retval != 0) {
4829			printf("ctl_alloc_lun: FETD %s port %d returned error "
4830			       "%d for lun_disable on target %ju lun %jd\n",
4831			       port->port_name, port->targ_port, retval,
4832			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4833		}
4834	}
4835
4836	mtx_unlock(&ctl_softc->ctl_lock);
4837
4838	return (0);
4839}
4840
4841int
4842ctl_start_lun(struct ctl_be_lun *be_lun)
4843{
4844	struct ctl_softc *ctl_softc;
4845	struct ctl_lun *lun;
4846
4847	ctl_softc = control_softc;
4848
4849	lun = (struct ctl_lun *)be_lun->ctl_lun;
4850
4851	mtx_lock(&lun->lun_lock);
4852	lun->flags &= ~CTL_LUN_STOPPED;
4853	mtx_unlock(&lun->lun_lock);
4854
4855	return (0);
4856}
4857
4858int
4859ctl_stop_lun(struct ctl_be_lun *be_lun)
4860{
4861	struct ctl_softc *ctl_softc;
4862	struct ctl_lun *lun;
4863
4864	ctl_softc = control_softc;
4865
4866	lun = (struct ctl_lun *)be_lun->ctl_lun;
4867
4868	mtx_lock(&lun->lun_lock);
4869	lun->flags |= CTL_LUN_STOPPED;
4870	mtx_unlock(&lun->lun_lock);
4871
4872	return (0);
4873}
4874
4875int
4876ctl_lun_offline(struct ctl_be_lun *be_lun)
4877{
4878	struct ctl_softc *ctl_softc;
4879	struct ctl_lun *lun;
4880
4881	ctl_softc = control_softc;
4882
4883	lun = (struct ctl_lun *)be_lun->ctl_lun;
4884
4885	mtx_lock(&lun->lun_lock);
4886	lun->flags |= CTL_LUN_OFFLINE;
4887	mtx_unlock(&lun->lun_lock);
4888
4889	return (0);
4890}
4891
4892int
4893ctl_lun_online(struct ctl_be_lun *be_lun)
4894{
4895	struct ctl_softc *ctl_softc;
4896	struct ctl_lun *lun;
4897
4898	ctl_softc = control_softc;
4899
4900	lun = (struct ctl_lun *)be_lun->ctl_lun;
4901
4902	mtx_lock(&lun->lun_lock);
4903	lun->flags &= ~CTL_LUN_OFFLINE;
4904	mtx_unlock(&lun->lun_lock);
4905
4906	return (0);
4907}
4908
4909int
4910ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4911{
4912	struct ctl_softc *ctl_softc;
4913	struct ctl_lun *lun;
4914
4915	ctl_softc = control_softc;
4916
4917	lun = (struct ctl_lun *)be_lun->ctl_lun;
4918
4919	mtx_lock(&lun->lun_lock);
4920
4921	/*
4922	 * The LUN needs to be disabled before it can be marked invalid.
4923	 */
4924	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4925		mtx_unlock(&lun->lun_lock);
4926		return (-1);
4927	}
4928	/*
4929	 * Mark the LUN invalid.
4930	 */
4931	lun->flags |= CTL_LUN_INVALID;
4932
4933	/*
4934	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4935	 * If we have something in the OOA queue, we'll free it when the
4936	 * last I/O completes.
4937	 */
4938	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4939		mtx_unlock(&lun->lun_lock);
4940		mtx_lock(&ctl_softc->ctl_lock);
4941		ctl_free_lun(lun);
4942		mtx_unlock(&ctl_softc->ctl_lock);
4943	} else
4944		mtx_unlock(&lun->lun_lock);
4945
4946	return (0);
4947}
4948
4949int
4950ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4951{
4952	struct ctl_softc *ctl_softc;
4953	struct ctl_lun *lun;
4954
4955	ctl_softc = control_softc;
4956	lun = (struct ctl_lun *)be_lun->ctl_lun;
4957
4958	mtx_lock(&lun->lun_lock);
4959	lun->flags |= CTL_LUN_INOPERABLE;
4960	mtx_unlock(&lun->lun_lock);
4961
4962	return (0);
4963}
4964
4965int
4966ctl_lun_operable(struct ctl_be_lun *be_lun)
4967{
4968	struct ctl_softc *ctl_softc;
4969	struct ctl_lun *lun;
4970
4971	ctl_softc = control_softc;
4972	lun = (struct ctl_lun *)be_lun->ctl_lun;
4973
4974	mtx_lock(&lun->lun_lock);
4975	lun->flags &= ~CTL_LUN_INOPERABLE;
4976	mtx_unlock(&lun->lun_lock);
4977
4978	return (0);
4979}
4980
4981void
4982ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4983{
4984	struct ctl_lun *lun;
4985	struct ctl_softc *softc;
4986	int i;
4987
4988	softc = control_softc;
4989
4990	lun = (struct ctl_lun *)be_lun->ctl_lun;
4991
4992	mtx_lock(&lun->lun_lock);
4993
4994	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4995		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
4996
4997	mtx_unlock(&lun->lun_lock);
4998}
4999
5000/*
5001 * Backend "memory move is complete" callback for requests that never
5002 * make it down to say RAIDCore's configuration code.
5003 */
5004int
5005ctl_config_move_done(union ctl_io *io)
5006{
5007	int retval;
5008
5009	retval = CTL_RETVAL_COMPLETE;
5010
5011
5012	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5013	/*
5014	 * XXX KDM this shouldn't happen, but what if it does?
5015	 */
5016	if (io->io_hdr.io_type != CTL_IO_SCSI)
5017		panic("I/O type isn't CTL_IO_SCSI!");
5018
5019	if ((io->io_hdr.port_status == 0)
5020	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5021	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5022		io->io_hdr.status = CTL_SUCCESS;
5023	else if ((io->io_hdr.port_status != 0)
5024	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5025	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5026		/*
5027		 * For hardware error sense keys, the sense key
5028		 * specific value is defined to be a retry count,
5029		 * but we use it to pass back an internal FETD
5030		 * error code.  XXX KDM  Hopefully the FETD is only
5031		 * using 16 bits for an error code, since that's
5032		 * all the space we have in the sks field.
5033		 */
5034		ctl_set_internal_failure(&io->scsiio,
5035					 /*sks_valid*/ 1,
5036					 /*retry_count*/
5037					 io->io_hdr.port_status);
5038		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5039			free(io->scsiio.kern_data_ptr, M_CTL);
5040		ctl_done(io);
5041		goto bailout;
5042	}
5043
5044	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5045	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5046	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5047		/*
5048		 * XXX KDM just assuming a single pointer here, and not a
5049		 * S/G list.  If we start using S/G lists for config data,
5050		 * we'll need to know how to clean them up here as well.
5051		 */
5052		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5053			free(io->scsiio.kern_data_ptr, M_CTL);
5054		/* Hopefully the user has already set the status... */
5055		ctl_done(io);
5056	} else {
5057		/*
5058		 * XXX KDM now we need to continue data movement.  Some
5059		 * options:
5060		 * - call ctl_scsiio() again?  We don't do this for data
5061		 *   writes, because for those at least we know ahead of
5062		 *   time where the write will go and how long it is.  For
5063		 *   config writes, though, that information is largely
5064		 *   contained within the write itself, thus we need to
5065		 *   parse out the data again.
5066		 *
5067		 * - Call some other function once the data is in?
5068		 */
5069
5070		/*
5071		 * XXX KDM call ctl_scsiio() again for now, and check flag
5072		 * bits to see whether we're allocated or not.
5073		 */
5074		retval = ctl_scsiio(&io->scsiio);
5075	}
5076bailout:
5077	return (retval);
5078}
5079
5080/*
5081 * This gets called by a backend driver when it is done with a
5082 * data_submit method.
5083 */
5084void
5085ctl_data_submit_done(union ctl_io *io)
5086{
5087	/*
5088	 * If the IO_CONT flag is set, we need to call the supplied
5089	 * function to continue processing the I/O, instead of completing
5090	 * the I/O just yet.
5091	 *
5092	 * If there is an error, though, we don't want to keep processing.
5093	 * Instead, just send status back to the initiator.
5094	 */
5095	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5096	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5097	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5098	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5099		io->scsiio.io_cont(io);
5100		return;
5101	}
5102	ctl_done(io);
5103}
5104
5105/*
5106 * This gets called by a backend driver when it is done with a
5107 * configuration write.
5108 */
5109void
5110ctl_config_write_done(union ctl_io *io)
5111{
5112	uint8_t *buf;
5113
5114	/*
5115	 * If the IO_CONT flag is set, we need to call the supplied
5116	 * function to continue processing the I/O, instead of completing
5117	 * the I/O just yet.
5118	 *
5119	 * If there is an error, though, we don't want to keep processing.
5120	 * Instead, just send status back to the initiator.
5121	 */
5122	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5123	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5124	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5125	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5126		io->scsiio.io_cont(io);
5127		return;
5128	}
5129	/*
5130	 * Since a configuration write can be done for commands that actually
5131	 * have data allocated, like write buffer, and commands that have
5132	 * no data, like start/stop unit, we need to check here.
5133	 */
5134	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5135		buf = io->scsiio.kern_data_ptr;
5136	else
5137		buf = NULL;
5138	ctl_done(io);
5139	if (buf)
5140		free(buf, M_CTL);
5141}
5142
5143/*
5144 * SCSI release command.
5145 */
5146int
5147ctl_scsi_release(struct ctl_scsiio *ctsio)
5148{
5149	int length, longid, thirdparty_id, resv_id;
5150	struct ctl_softc *ctl_softc;
5151	struct ctl_lun *lun;
5152	uint32_t residx;
5153
5154	length = 0;
5155	resv_id = 0;
5156
5157	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5158
5159	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5160	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5161	ctl_softc = control_softc;
5162
5163	switch (ctsio->cdb[0]) {
5164	case RELEASE_10: {
5165		struct scsi_release_10 *cdb;
5166
5167		cdb = (struct scsi_release_10 *)ctsio->cdb;
5168
5169		if (cdb->byte2 & SR10_LONGID)
5170			longid = 1;
5171		else
5172			thirdparty_id = cdb->thirdparty_id;
5173
5174		resv_id = cdb->resv_id;
5175		length = scsi_2btoul(cdb->length);
5176		break;
5177	}
5178	}
5179
5180
5181	/*
5182	 * XXX KDM right now, we only support LUN reservation.  We don't
5183	 * support 3rd party reservations, or extent reservations, which
5184	 * might actually need the parameter list.  If we've gotten this
5185	 * far, we've got a LUN reservation.  Anything else got kicked out
5186	 * above.  So, according to SPC, ignore the length.
5187	 */
5188	length = 0;
5189
5190	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5191	 && (length > 0)) {
5192		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5193		ctsio->kern_data_len = length;
5194		ctsio->kern_total_len = length;
5195		ctsio->kern_data_resid = 0;
5196		ctsio->kern_rel_offset = 0;
5197		ctsio->kern_sg_entries = 0;
5198		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5199		ctsio->be_move_done = ctl_config_move_done;
5200		ctl_datamove((union ctl_io *)ctsio);
5201
5202		return (CTL_RETVAL_COMPLETE);
5203	}
5204
5205	if (length > 0)
5206		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5207
5208	mtx_lock(&lun->lun_lock);
5209
5210	/*
5211	 * According to SPC, it is not an error for an intiator to attempt
5212	 * to release a reservation on a LUN that isn't reserved, or that
5213	 * is reserved by another initiator.  The reservation can only be
5214	 * released, though, by the initiator who made it or by one of
5215	 * several reset type events.
5216	 */
5217	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5218			lun->flags &= ~CTL_LUN_RESERVED;
5219
5220	mtx_unlock(&lun->lun_lock);
5221
5222	ctsio->scsi_status = SCSI_STATUS_OK;
5223	ctsio->io_hdr.status = CTL_SUCCESS;
5224
5225	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5226		free(ctsio->kern_data_ptr, M_CTL);
5227		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5228	}
5229
5230	ctl_done((union ctl_io *)ctsio);
5231	return (CTL_RETVAL_COMPLETE);
5232}
5233
5234int
5235ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5236{
5237	int extent, thirdparty, longid;
5238	int resv_id, length;
5239	uint64_t thirdparty_id;
5240	struct ctl_softc *ctl_softc;
5241	struct ctl_lun *lun;
5242	uint32_t residx;
5243
5244	extent = 0;
5245	thirdparty = 0;
5246	longid = 0;
5247	resv_id = 0;
5248	length = 0;
5249	thirdparty_id = 0;
5250
5251	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5252
5253	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5254	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5255	ctl_softc = control_softc;
5256
5257	switch (ctsio->cdb[0]) {
5258	case RESERVE_10: {
5259		struct scsi_reserve_10 *cdb;
5260
5261		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5262
5263		if (cdb->byte2 & SR10_LONGID)
5264			longid = 1;
5265		else
5266			thirdparty_id = cdb->thirdparty_id;
5267
5268		resv_id = cdb->resv_id;
5269		length = scsi_2btoul(cdb->length);
5270		break;
5271	}
5272	}
5273
5274	/*
5275	 * XXX KDM right now, we only support LUN reservation.  We don't
5276	 * support 3rd party reservations, or extent reservations, which
5277	 * might actually need the parameter list.  If we've gotten this
5278	 * far, we've got a LUN reservation.  Anything else got kicked out
5279	 * above.  So, according to SPC, ignore the length.
5280	 */
5281	length = 0;
5282
5283	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5284	 && (length > 0)) {
5285		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5286		ctsio->kern_data_len = length;
5287		ctsio->kern_total_len = length;
5288		ctsio->kern_data_resid = 0;
5289		ctsio->kern_rel_offset = 0;
5290		ctsio->kern_sg_entries = 0;
5291		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5292		ctsio->be_move_done = ctl_config_move_done;
5293		ctl_datamove((union ctl_io *)ctsio);
5294
5295		return (CTL_RETVAL_COMPLETE);
5296	}
5297
5298	if (length > 0)
5299		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5300
5301	mtx_lock(&lun->lun_lock);
5302	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5303		ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5304		ctsio->io_hdr.status = CTL_SCSI_ERROR;
5305		goto bailout;
5306	}
5307
5308	lun->flags |= CTL_LUN_RESERVED;
5309	lun->res_idx = residx;
5310
5311	ctsio->scsi_status = SCSI_STATUS_OK;
5312	ctsio->io_hdr.status = CTL_SUCCESS;
5313
5314bailout:
5315	mtx_unlock(&lun->lun_lock);
5316
5317	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5318		free(ctsio->kern_data_ptr, M_CTL);
5319		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5320	}
5321
5322	ctl_done((union ctl_io *)ctsio);
5323	return (CTL_RETVAL_COMPLETE);
5324}
5325
5326int
5327ctl_start_stop(struct ctl_scsiio *ctsio)
5328{
5329	struct scsi_start_stop_unit *cdb;
5330	struct ctl_lun *lun;
5331	struct ctl_softc *ctl_softc;
5332	int retval;
5333
5334	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5335
5336	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5337	ctl_softc = control_softc;
5338	retval = 0;
5339
5340	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5341
5342	/*
5343	 * XXX KDM
5344	 * We don't support the immediate bit on a stop unit.  In order to
5345	 * do that, we would need to code up a way to know that a stop is
5346	 * pending, and hold off any new commands until it completes, one
5347	 * way or another.  Then we could accept or reject those commands
5348	 * depending on its status.  We would almost need to do the reverse
5349	 * of what we do below for an immediate start -- return the copy of
5350	 * the ctl_io to the FETD with status to send to the host (and to
5351	 * free the copy!) and then free the original I/O once the stop
5352	 * actually completes.  That way, the OOA queue mechanism can work
5353	 * to block commands that shouldn't proceed.  Another alternative
5354	 * would be to put the copy in the queue in place of the original,
5355	 * and return the original back to the caller.  That could be
5356	 * slightly safer..
5357	 */
5358	if ((cdb->byte2 & SSS_IMMED)
5359	 && ((cdb->how & SSS_START) == 0)) {
5360		ctl_set_invalid_field(ctsio,
5361				      /*sks_valid*/ 1,
5362				      /*command*/ 1,
5363				      /*field*/ 1,
5364				      /*bit_valid*/ 1,
5365				      /*bit*/ 0);
5366		ctl_done((union ctl_io *)ctsio);
5367		return (CTL_RETVAL_COMPLETE);
5368	}
5369
5370	if ((lun->flags & CTL_LUN_PR_RESERVED)
5371	 && ((cdb->how & SSS_START)==0)) {
5372		uint32_t residx;
5373
5374		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5375		if (lun->pr_keys[residx] == 0
5376		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5377
5378			ctl_set_reservation_conflict(ctsio);
5379			ctl_done((union ctl_io *)ctsio);
5380			return (CTL_RETVAL_COMPLETE);
5381		}
5382	}
5383
5384	/*
5385	 * If there is no backend on this device, we can't start or stop
5386	 * it.  In theory we shouldn't get any start/stop commands in the
5387	 * first place at this level if the LUN doesn't have a backend.
5388	 * That should get stopped by the command decode code.
5389	 */
5390	if (lun->backend == NULL) {
5391		ctl_set_invalid_opcode(ctsio);
5392		ctl_done((union ctl_io *)ctsio);
5393		return (CTL_RETVAL_COMPLETE);
5394	}
5395
5396	/*
5397	 * XXX KDM Copan-specific offline behavior.
5398	 * Figure out a reasonable way to port this?
5399	 */
5400#ifdef NEEDTOPORT
5401	mtx_lock(&lun->lun_lock);
5402
5403	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5404	 && (lun->flags & CTL_LUN_OFFLINE)) {
5405		/*
5406		 * If the LUN is offline, and the on/offline bit isn't set,
5407		 * reject the start or stop.  Otherwise, let it through.
5408		 */
5409		mtx_unlock(&lun->lun_lock);
5410		ctl_set_lun_not_ready(ctsio);
5411		ctl_done((union ctl_io *)ctsio);
5412	} else {
5413		mtx_unlock(&lun->lun_lock);
5414#endif /* NEEDTOPORT */
5415		/*
5416		 * This could be a start or a stop when we're online,
5417		 * or a stop/offline or start/online.  A start or stop when
5418		 * we're offline is covered in the case above.
5419		 */
5420		/*
5421		 * In the non-immediate case, we send the request to
5422		 * the backend and return status to the user when
5423		 * it is done.
5424		 *
5425		 * In the immediate case, we allocate a new ctl_io
5426		 * to hold a copy of the request, and send that to
5427		 * the backend.  We then set good status on the
5428		 * user's request and return it immediately.
5429		 */
5430		if (cdb->byte2 & SSS_IMMED) {
5431			union ctl_io *new_io;
5432
5433			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5434			if (new_io == NULL) {
5435				ctl_set_busy(ctsio);
5436				ctl_done((union ctl_io *)ctsio);
5437			} else {
5438				ctl_copy_io((union ctl_io *)ctsio,
5439					    new_io);
5440				retval = lun->backend->config_write(new_io);
5441				ctl_set_success(ctsio);
5442				ctl_done((union ctl_io *)ctsio);
5443			}
5444		} else {
5445			retval = lun->backend->config_write(
5446				(union ctl_io *)ctsio);
5447		}
5448#ifdef NEEDTOPORT
5449	}
5450#endif
5451	return (retval);
5452}
5453
5454/*
5455 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5456 * we don't really do anything with the LBA and length fields if the user
5457 * passes them in.  Instead we'll just flush out the cache for the entire
5458 * LUN.
5459 */
5460int
5461ctl_sync_cache(struct ctl_scsiio *ctsio)
5462{
5463	struct ctl_lun *lun;
5464	struct ctl_softc *ctl_softc;
5465	uint64_t starting_lba;
5466	uint32_t block_count;
5467	int retval;
5468
5469	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5470
5471	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5472	ctl_softc = control_softc;
5473	retval = 0;
5474
5475	switch (ctsio->cdb[0]) {
5476	case SYNCHRONIZE_CACHE: {
5477		struct scsi_sync_cache *cdb;
5478		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5479
5480		starting_lba = scsi_4btoul(cdb->begin_lba);
5481		block_count = scsi_2btoul(cdb->lb_count);
5482		break;
5483	}
5484	case SYNCHRONIZE_CACHE_16: {
5485		struct scsi_sync_cache_16 *cdb;
5486		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5487
5488		starting_lba = scsi_8btou64(cdb->begin_lba);
5489		block_count = scsi_4btoul(cdb->lb_count);
5490		break;
5491	}
5492	default:
5493		ctl_set_invalid_opcode(ctsio);
5494		ctl_done((union ctl_io *)ctsio);
5495		goto bailout;
5496		break; /* NOTREACHED */
5497	}
5498
5499	/*
5500	 * We check the LBA and length, but don't do anything with them.
5501	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5502	 * get flushed.  This check will just help satisfy anyone who wants
5503	 * to see an error for an out of range LBA.
5504	 */
5505	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5506		ctl_set_lba_out_of_range(ctsio);
5507		ctl_done((union ctl_io *)ctsio);
5508		goto bailout;
5509	}
5510
5511	/*
5512	 * If this LUN has no backend, we can't flush the cache anyway.
5513	 */
5514	if (lun->backend == NULL) {
5515		ctl_set_invalid_opcode(ctsio);
5516		ctl_done((union ctl_io *)ctsio);
5517		goto bailout;
5518	}
5519
5520	/*
5521	 * Check to see whether we're configured to send the SYNCHRONIZE
5522	 * CACHE command directly to the back end.
5523	 */
5524	mtx_lock(&lun->lun_lock);
5525	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5526	 && (++(lun->sync_count) >= lun->sync_interval)) {
5527		lun->sync_count = 0;
5528		mtx_unlock(&lun->lun_lock);
5529		retval = lun->backend->config_write((union ctl_io *)ctsio);
5530	} else {
5531		mtx_unlock(&lun->lun_lock);
5532		ctl_set_success(ctsio);
5533		ctl_done((union ctl_io *)ctsio);
5534	}
5535
5536bailout:
5537
5538	return (retval);
5539}
5540
5541int
5542ctl_format(struct ctl_scsiio *ctsio)
5543{
5544	struct scsi_format *cdb;
5545	struct ctl_lun *lun;
5546	struct ctl_softc *ctl_softc;
5547	int length, defect_list_len;
5548
5549	CTL_DEBUG_PRINT(("ctl_format\n"));
5550
5551	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5552	ctl_softc = control_softc;
5553
5554	cdb = (struct scsi_format *)ctsio->cdb;
5555
5556	length = 0;
5557	if (cdb->byte2 & SF_FMTDATA) {
5558		if (cdb->byte2 & SF_LONGLIST)
5559			length = sizeof(struct scsi_format_header_long);
5560		else
5561			length = sizeof(struct scsi_format_header_short);
5562	}
5563
5564	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5565	 && (length > 0)) {
5566		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5567		ctsio->kern_data_len = length;
5568		ctsio->kern_total_len = length;
5569		ctsio->kern_data_resid = 0;
5570		ctsio->kern_rel_offset = 0;
5571		ctsio->kern_sg_entries = 0;
5572		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5573		ctsio->be_move_done = ctl_config_move_done;
5574		ctl_datamove((union ctl_io *)ctsio);
5575
5576		return (CTL_RETVAL_COMPLETE);
5577	}
5578
5579	defect_list_len = 0;
5580
5581	if (cdb->byte2 & SF_FMTDATA) {
5582		if (cdb->byte2 & SF_LONGLIST) {
5583			struct scsi_format_header_long *header;
5584
5585			header = (struct scsi_format_header_long *)
5586				ctsio->kern_data_ptr;
5587
5588			defect_list_len = scsi_4btoul(header->defect_list_len);
5589			if (defect_list_len != 0) {
5590				ctl_set_invalid_field(ctsio,
5591						      /*sks_valid*/ 1,
5592						      /*command*/ 0,
5593						      /*field*/ 2,
5594						      /*bit_valid*/ 0,
5595						      /*bit*/ 0);
5596				goto bailout;
5597			}
5598		} else {
5599			struct scsi_format_header_short *header;
5600
5601			header = (struct scsi_format_header_short *)
5602				ctsio->kern_data_ptr;
5603
5604			defect_list_len = scsi_2btoul(header->defect_list_len);
5605			if (defect_list_len != 0) {
5606				ctl_set_invalid_field(ctsio,
5607						      /*sks_valid*/ 1,
5608						      /*command*/ 0,
5609						      /*field*/ 2,
5610						      /*bit_valid*/ 0,
5611						      /*bit*/ 0);
5612				goto bailout;
5613			}
5614		}
5615	}
5616
5617	/*
5618	 * The format command will clear out the "Medium format corrupted"
5619	 * status if set by the configuration code.  That status is really
5620	 * just a way to notify the host that we have lost the media, and
5621	 * get them to issue a command that will basically make them think
5622	 * they're blowing away the media.
5623	 */
5624	mtx_lock(&lun->lun_lock);
5625	lun->flags &= ~CTL_LUN_INOPERABLE;
5626	mtx_unlock(&lun->lun_lock);
5627
5628	ctsio->scsi_status = SCSI_STATUS_OK;
5629	ctsio->io_hdr.status = CTL_SUCCESS;
5630bailout:
5631
5632	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5633		free(ctsio->kern_data_ptr, M_CTL);
5634		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5635	}
5636
5637	ctl_done((union ctl_io *)ctsio);
5638	return (CTL_RETVAL_COMPLETE);
5639}
5640
5641int
5642ctl_read_buffer(struct ctl_scsiio *ctsio)
5643{
5644	struct scsi_read_buffer *cdb;
5645	struct ctl_lun *lun;
5646	int buffer_offset, len;
5647	static uint8_t descr[4];
5648	static uint8_t echo_descr[4] = { 0 };
5649
5650	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5651
5652	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5653	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5654
5655	if (lun->flags & CTL_LUN_PR_RESERVED) {
5656		uint32_t residx;
5657
5658		/*
5659		 * XXX KDM need a lock here.
5660		 */
5661		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5662		if ((lun->res_type == SPR_TYPE_EX_AC
5663		  && residx != lun->pr_res_idx)
5664		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5665		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5666		  && lun->pr_keys[residx] == 0)) {
5667			ctl_set_reservation_conflict(ctsio);
5668			ctl_done((union ctl_io *)ctsio);
5669			return (CTL_RETVAL_COMPLETE);
5670	        }
5671	}
5672
5673	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5674	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5675	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5676		ctl_set_invalid_field(ctsio,
5677				      /*sks_valid*/ 1,
5678				      /*command*/ 1,
5679				      /*field*/ 1,
5680				      /*bit_valid*/ 1,
5681				      /*bit*/ 4);
5682		ctl_done((union ctl_io *)ctsio);
5683		return (CTL_RETVAL_COMPLETE);
5684	}
5685
5686	len = scsi_3btoul(cdb->length);
5687	buffer_offset = scsi_3btoul(cdb->offset);
5688
5689	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5690		ctl_set_invalid_field(ctsio,
5691				      /*sks_valid*/ 1,
5692				      /*command*/ 1,
5693				      /*field*/ 6,
5694				      /*bit_valid*/ 0,
5695				      /*bit*/ 0);
5696		ctl_done((union ctl_io *)ctsio);
5697		return (CTL_RETVAL_COMPLETE);
5698	}
5699
5700	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5701		descr[0] = 0;
5702		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5703		ctsio->kern_data_ptr = descr;
5704		len = min(len, sizeof(descr));
5705	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5706		ctsio->kern_data_ptr = echo_descr;
5707		len = min(len, sizeof(echo_descr));
5708	} else
5709		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5710	ctsio->kern_data_len = len;
5711	ctsio->kern_total_len = len;
5712	ctsio->kern_data_resid = 0;
5713	ctsio->kern_rel_offset = 0;
5714	ctsio->kern_sg_entries = 0;
5715	ctsio->be_move_done = ctl_config_move_done;
5716	ctl_datamove((union ctl_io *)ctsio);
5717
5718	return (CTL_RETVAL_COMPLETE);
5719}
5720
5721int
5722ctl_write_buffer(struct ctl_scsiio *ctsio)
5723{
5724	struct scsi_write_buffer *cdb;
5725	struct ctl_lun *lun;
5726	int buffer_offset, len;
5727
5728	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5729
5730	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5731	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5732
5733	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5734		ctl_set_invalid_field(ctsio,
5735				      /*sks_valid*/ 1,
5736				      /*command*/ 1,
5737				      /*field*/ 1,
5738				      /*bit_valid*/ 1,
5739				      /*bit*/ 4);
5740		ctl_done((union ctl_io *)ctsio);
5741		return (CTL_RETVAL_COMPLETE);
5742	}
5743
5744	len = scsi_3btoul(cdb->length);
5745	buffer_offset = scsi_3btoul(cdb->offset);
5746
5747	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5748		ctl_set_invalid_field(ctsio,
5749				      /*sks_valid*/ 1,
5750				      /*command*/ 1,
5751				      /*field*/ 6,
5752				      /*bit_valid*/ 0,
5753				      /*bit*/ 0);
5754		ctl_done((union ctl_io *)ctsio);
5755		return (CTL_RETVAL_COMPLETE);
5756	}
5757
5758	/*
5759	 * If we've got a kernel request that hasn't been malloced yet,
5760	 * malloc it and tell the caller the data buffer is here.
5761	 */
5762	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5763		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5764		ctsio->kern_data_len = len;
5765		ctsio->kern_total_len = len;
5766		ctsio->kern_data_resid = 0;
5767		ctsio->kern_rel_offset = 0;
5768		ctsio->kern_sg_entries = 0;
5769		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5770		ctsio->be_move_done = ctl_config_move_done;
5771		ctl_datamove((union ctl_io *)ctsio);
5772
5773		return (CTL_RETVAL_COMPLETE);
5774	}
5775
5776	ctl_done((union ctl_io *)ctsio);
5777
5778	return (CTL_RETVAL_COMPLETE);
5779}
5780
5781int
5782ctl_write_same(struct ctl_scsiio *ctsio)
5783{
5784	struct ctl_lun *lun;
5785	struct ctl_lba_len_flags *lbalen;
5786	uint64_t lba;
5787	uint32_t num_blocks;
5788	int len, retval;
5789	uint8_t byte2;
5790
5791	retval = CTL_RETVAL_COMPLETE;
5792
5793	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5794
5795	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5796
5797	switch (ctsio->cdb[0]) {
5798	case WRITE_SAME_10: {
5799		struct scsi_write_same_10 *cdb;
5800
5801		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5802
5803		lba = scsi_4btoul(cdb->addr);
5804		num_blocks = scsi_2btoul(cdb->length);
5805		byte2 = cdb->byte2;
5806		break;
5807	}
5808	case WRITE_SAME_16: {
5809		struct scsi_write_same_16 *cdb;
5810
5811		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5812
5813		lba = scsi_8btou64(cdb->addr);
5814		num_blocks = scsi_4btoul(cdb->length);
5815		byte2 = cdb->byte2;
5816		break;
5817	}
5818	default:
5819		/*
5820		 * We got a command we don't support.  This shouldn't
5821		 * happen, commands should be filtered out above us.
5822		 */
5823		ctl_set_invalid_opcode(ctsio);
5824		ctl_done((union ctl_io *)ctsio);
5825
5826		return (CTL_RETVAL_COMPLETE);
5827		break; /* NOTREACHED */
5828	}
5829
5830	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5831	if ((byte2 & SWS_UNMAP) == 0 &&
5832	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5833		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5834		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5835		ctl_done((union ctl_io *)ctsio);
5836		return (CTL_RETVAL_COMPLETE);
5837	}
5838
5839	/*
5840	 * The first check is to make sure we're in bounds, the second
5841	 * check is to catch wrap-around problems.  If the lba + num blocks
5842	 * is less than the lba, then we've wrapped around and the block
5843	 * range is invalid anyway.
5844	 */
5845	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5846	 || ((lba + num_blocks) < lba)) {
5847		ctl_set_lba_out_of_range(ctsio);
5848		ctl_done((union ctl_io *)ctsio);
5849		return (CTL_RETVAL_COMPLETE);
5850	}
5851
5852	/* Zero number of blocks means "to the last logical block" */
5853	if (num_blocks == 0) {
5854		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5855			ctl_set_invalid_field(ctsio,
5856					      /*sks_valid*/ 0,
5857					      /*command*/ 1,
5858					      /*field*/ 0,
5859					      /*bit_valid*/ 0,
5860					      /*bit*/ 0);
5861			ctl_done((union ctl_io *)ctsio);
5862			return (CTL_RETVAL_COMPLETE);
5863		}
5864		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5865	}
5866
5867	len = lun->be_lun->blocksize;
5868
5869	/*
5870	 * If we've got a kernel request that hasn't been malloced yet,
5871	 * malloc it and tell the caller the data buffer is here.
5872	 */
5873	if ((byte2 & SWS_NDOB) == 0 &&
5874	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5875		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5876		ctsio->kern_data_len = len;
5877		ctsio->kern_total_len = len;
5878		ctsio->kern_data_resid = 0;
5879		ctsio->kern_rel_offset = 0;
5880		ctsio->kern_sg_entries = 0;
5881		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5882		ctsio->be_move_done = ctl_config_move_done;
5883		ctl_datamove((union ctl_io *)ctsio);
5884
5885		return (CTL_RETVAL_COMPLETE);
5886	}
5887
5888	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5889	lbalen->lba = lba;
5890	lbalen->len = num_blocks;
5891	lbalen->flags = byte2;
5892	retval = lun->backend->config_write((union ctl_io *)ctsio);
5893
5894	return (retval);
5895}
5896
5897int
5898ctl_unmap(struct ctl_scsiio *ctsio)
5899{
5900	struct ctl_lun *lun;
5901	struct scsi_unmap *cdb;
5902	struct ctl_ptr_len_flags *ptrlen;
5903	struct scsi_unmap_header *hdr;
5904	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5905	uint64_t lba;
5906	uint32_t num_blocks;
5907	int len, retval;
5908	uint8_t byte2;
5909
5910	retval = CTL_RETVAL_COMPLETE;
5911
5912	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5913
5914	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5915	cdb = (struct scsi_unmap *)ctsio->cdb;
5916
5917	len = scsi_2btoul(cdb->length);
5918	byte2 = cdb->byte2;
5919
5920	/*
5921	 * If we've got a kernel request that hasn't been malloced yet,
5922	 * malloc it and tell the caller the data buffer is here.
5923	 */
5924	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5925		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5926		ctsio->kern_data_len = len;
5927		ctsio->kern_total_len = len;
5928		ctsio->kern_data_resid = 0;
5929		ctsio->kern_rel_offset = 0;
5930		ctsio->kern_sg_entries = 0;
5931		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5932		ctsio->be_move_done = ctl_config_move_done;
5933		ctl_datamove((union ctl_io *)ctsio);
5934
5935		return (CTL_RETVAL_COMPLETE);
5936	}
5937
5938	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5939	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5940	if (len < sizeof (*hdr) ||
5941	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5942	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5943	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5944		ctl_set_invalid_field(ctsio,
5945				      /*sks_valid*/ 0,
5946				      /*command*/ 0,
5947				      /*field*/ 0,
5948				      /*bit_valid*/ 0,
5949				      /*bit*/ 0);
5950		ctl_done((union ctl_io *)ctsio);
5951		return (CTL_RETVAL_COMPLETE);
5952	}
5953	len = scsi_2btoul(hdr->desc_length);
5954	buf = (struct scsi_unmap_desc *)(hdr + 1);
5955	end = buf + len / sizeof(*buf);
5956
5957	endnz = buf;
5958	for (range = buf; range < end; range++) {
5959		lba = scsi_8btou64(range->lba);
5960		num_blocks = scsi_4btoul(range->length);
5961		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5962		 || ((lba + num_blocks) < lba)) {
5963			ctl_set_lba_out_of_range(ctsio);
5964			ctl_done((union ctl_io *)ctsio);
5965			return (CTL_RETVAL_COMPLETE);
5966		}
5967		if (num_blocks != 0)
5968			endnz = range + 1;
5969	}
5970
5971	/*
5972	 * Block backend can not handle zero last range.
5973	 * Filter it out and return if there is nothing left.
5974	 */
5975	len = (uint8_t *)endnz - (uint8_t *)buf;
5976	if (len == 0) {
5977		ctl_set_success(ctsio);
5978		ctl_done((union ctl_io *)ctsio);
5979		return (CTL_RETVAL_COMPLETE);
5980	}
5981
5982	mtx_lock(&lun->lun_lock);
5983	ptrlen = (struct ctl_ptr_len_flags *)
5984	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5985	ptrlen->ptr = (void *)buf;
5986	ptrlen->len = len;
5987	ptrlen->flags = byte2;
5988	ctl_check_blocked(lun);
5989	mtx_unlock(&lun->lun_lock);
5990
5991	retval = lun->backend->config_write((union ctl_io *)ctsio);
5992	return (retval);
5993}
5994
5995/*
5996 * Note that this function currently doesn't actually do anything inside
5997 * CTL to enforce things if the DQue bit is turned on.
5998 *
5999 * Also note that this function can't be used in the default case, because
6000 * the DQue bit isn't set in the changeable mask for the control mode page
6001 * anyway.  This is just here as an example for how to implement a page
6002 * handler, and a placeholder in case we want to allow the user to turn
6003 * tagged queueing on and off.
6004 *
6005 * The D_SENSE bit handling is functional, however, and will turn
6006 * descriptor sense on and off for a given LUN.
6007 */
6008int
6009ctl_control_page_handler(struct ctl_scsiio *ctsio,
6010			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6011{
6012	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6013	struct ctl_lun *lun;
6014	struct ctl_softc *softc;
6015	int set_ua;
6016	uint32_t initidx;
6017
6018	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6019	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6020	set_ua = 0;
6021
6022	user_cp = (struct scsi_control_page *)page_ptr;
6023	current_cp = (struct scsi_control_page *)
6024		(page_index->page_data + (page_index->page_len *
6025		CTL_PAGE_CURRENT));
6026	saved_cp = (struct scsi_control_page *)
6027		(page_index->page_data + (page_index->page_len *
6028		CTL_PAGE_SAVED));
6029
6030	softc = control_softc;
6031
6032	mtx_lock(&lun->lun_lock);
6033	if (((current_cp->rlec & SCP_DSENSE) == 0)
6034	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6035		/*
6036		 * Descriptor sense is currently turned off and the user
6037		 * wants to turn it on.
6038		 */
6039		current_cp->rlec |= SCP_DSENSE;
6040		saved_cp->rlec |= SCP_DSENSE;
6041		lun->flags |= CTL_LUN_SENSE_DESC;
6042		set_ua = 1;
6043	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6044		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6045		/*
6046		 * Descriptor sense is currently turned on, and the user
6047		 * wants to turn it off.
6048		 */
6049		current_cp->rlec &= ~SCP_DSENSE;
6050		saved_cp->rlec &= ~SCP_DSENSE;
6051		lun->flags &= ~CTL_LUN_SENSE_DESC;
6052		set_ua = 1;
6053	}
6054	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6055	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6056		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6057		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6058		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6059		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6060		set_ua = 1;
6061	}
6062	if ((current_cp->eca_and_aen & SCP_SWP) !=
6063	    (user_cp->eca_and_aen & SCP_SWP)) {
6064		current_cp->eca_and_aen &= ~SCP_SWP;
6065		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6066		saved_cp->eca_and_aen &= ~SCP_SWP;
6067		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6068		set_ua = 1;
6069	}
6070	if (set_ua != 0) {
6071		int i;
6072		/*
6073		 * Let other initiators know that the mode
6074		 * parameters for this LUN have changed.
6075		 */
6076		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6077			if (i == initidx)
6078				continue;
6079
6080			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6081		}
6082	}
6083	mtx_unlock(&lun->lun_lock);
6084
6085	return (0);
6086}
6087
6088int
6089ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6090		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6091{
6092	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6093	struct ctl_lun *lun;
6094	int set_ua;
6095	uint32_t initidx;
6096
6097	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6098	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6099	set_ua = 0;
6100
6101	user_cp = (struct scsi_caching_page *)page_ptr;
6102	current_cp = (struct scsi_caching_page *)
6103		(page_index->page_data + (page_index->page_len *
6104		CTL_PAGE_CURRENT));
6105	saved_cp = (struct scsi_caching_page *)
6106		(page_index->page_data + (page_index->page_len *
6107		CTL_PAGE_SAVED));
6108
6109	mtx_lock(&lun->lun_lock);
6110	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6111	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6112		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6113		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6114		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6115		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6116		set_ua = 1;
6117	}
6118	if (set_ua != 0) {
6119		int i;
6120		/*
6121		 * Let other initiators know that the mode
6122		 * parameters for this LUN have changed.
6123		 */
6124		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6125			if (i == initidx)
6126				continue;
6127
6128			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6129		}
6130	}
6131	mtx_unlock(&lun->lun_lock);
6132
6133	return (0);
6134}
6135
6136int
6137ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6138				struct ctl_page_index *page_index,
6139				uint8_t *page_ptr)
6140{
6141	uint8_t *c;
6142	int i;
6143
6144	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6145	ctl_time_io_secs =
6146		(c[0] << 8) |
6147		(c[1] << 0) |
6148		0;
6149	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6150	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6151	printf("page data:");
6152	for (i=0; i<8; i++)
6153		printf(" %.2x",page_ptr[i]);
6154	printf("\n");
6155	return (0);
6156}
6157
6158int
6159ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6160			       struct ctl_page_index *page_index,
6161			       int pc)
6162{
6163	struct copan_debugconf_subpage *page;
6164
6165	page = (struct copan_debugconf_subpage *)page_index->page_data +
6166		(page_index->page_len * pc);
6167
6168	switch (pc) {
6169	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6170	case SMS_PAGE_CTRL_DEFAULT >> 6:
6171	case SMS_PAGE_CTRL_SAVED >> 6:
6172		/*
6173		 * We don't update the changable or default bits for this page.
6174		 */
6175		break;
6176	case SMS_PAGE_CTRL_CURRENT >> 6:
6177		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6178		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6179		break;
6180	default:
6181#ifdef NEEDTOPORT
6182		EPRINT(0, "Invalid PC %d!!", pc);
6183#endif /* NEEDTOPORT */
6184		break;
6185	}
6186	return (0);
6187}
6188
6189
6190static int
6191ctl_do_mode_select(union ctl_io *io)
6192{
6193	struct scsi_mode_page_header *page_header;
6194	struct ctl_page_index *page_index;
6195	struct ctl_scsiio *ctsio;
6196	int control_dev, page_len;
6197	int page_len_offset, page_len_size;
6198	union ctl_modepage_info *modepage_info;
6199	struct ctl_lun *lun;
6200	int *len_left, *len_used;
6201	int retval, i;
6202
6203	ctsio = &io->scsiio;
6204	page_index = NULL;
6205	page_len = 0;
6206	retval = CTL_RETVAL_COMPLETE;
6207
6208	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6209
6210	if (lun->be_lun->lun_type != T_DIRECT)
6211		control_dev = 1;
6212	else
6213		control_dev = 0;
6214
6215	modepage_info = (union ctl_modepage_info *)
6216		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6217	len_left = &modepage_info->header.len_left;
6218	len_used = &modepage_info->header.len_used;
6219
6220do_next_page:
6221
6222	page_header = (struct scsi_mode_page_header *)
6223		(ctsio->kern_data_ptr + *len_used);
6224
6225	if (*len_left == 0) {
6226		free(ctsio->kern_data_ptr, M_CTL);
6227		ctl_set_success(ctsio);
6228		ctl_done((union ctl_io *)ctsio);
6229		return (CTL_RETVAL_COMPLETE);
6230	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6231
6232		free(ctsio->kern_data_ptr, M_CTL);
6233		ctl_set_param_len_error(ctsio);
6234		ctl_done((union ctl_io *)ctsio);
6235		return (CTL_RETVAL_COMPLETE);
6236
6237	} else if ((page_header->page_code & SMPH_SPF)
6238		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6239
6240		free(ctsio->kern_data_ptr, M_CTL);
6241		ctl_set_param_len_error(ctsio);
6242		ctl_done((union ctl_io *)ctsio);
6243		return (CTL_RETVAL_COMPLETE);
6244	}
6245
6246
6247	/*
6248	 * XXX KDM should we do something with the block descriptor?
6249	 */
6250	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6251
6252		if ((control_dev != 0)
6253		 && (lun->mode_pages.index[i].page_flags &
6254		     CTL_PAGE_FLAG_DISK_ONLY))
6255			continue;
6256
6257		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6258		    (page_header->page_code & SMPH_PC_MASK))
6259			continue;
6260
6261		/*
6262		 * If neither page has a subpage code, then we've got a
6263		 * match.
6264		 */
6265		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6266		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6267			page_index = &lun->mode_pages.index[i];
6268			page_len = page_header->page_length;
6269			break;
6270		}
6271
6272		/*
6273		 * If both pages have subpages, then the subpage numbers
6274		 * have to match.
6275		 */
6276		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6277		  && (page_header->page_code & SMPH_SPF)) {
6278			struct scsi_mode_page_header_sp *sph;
6279
6280			sph = (struct scsi_mode_page_header_sp *)page_header;
6281
6282			if (lun->mode_pages.index[i].subpage ==
6283			    sph->subpage) {
6284				page_index = &lun->mode_pages.index[i];
6285				page_len = scsi_2btoul(sph->page_length);
6286				break;
6287			}
6288		}
6289	}
6290
6291	/*
6292	 * If we couldn't find the page, or if we don't have a mode select
6293	 * handler for it, send back an error to the user.
6294	 */
6295	if ((page_index == NULL)
6296	 || (page_index->select_handler == NULL)) {
6297		ctl_set_invalid_field(ctsio,
6298				      /*sks_valid*/ 1,
6299				      /*command*/ 0,
6300				      /*field*/ *len_used,
6301				      /*bit_valid*/ 0,
6302				      /*bit*/ 0);
6303		free(ctsio->kern_data_ptr, M_CTL);
6304		ctl_done((union ctl_io *)ctsio);
6305		return (CTL_RETVAL_COMPLETE);
6306	}
6307
6308	if (page_index->page_code & SMPH_SPF) {
6309		page_len_offset = 2;
6310		page_len_size = 2;
6311	} else {
6312		page_len_size = 1;
6313		page_len_offset = 1;
6314	}
6315
6316	/*
6317	 * If the length the initiator gives us isn't the one we specify in
6318	 * the mode page header, or if they didn't specify enough data in
6319	 * the CDB to avoid truncating this page, kick out the request.
6320	 */
6321	if ((page_len != (page_index->page_len - page_len_offset -
6322			  page_len_size))
6323	 || (*len_left < page_index->page_len)) {
6324
6325
6326		ctl_set_invalid_field(ctsio,
6327				      /*sks_valid*/ 1,
6328				      /*command*/ 0,
6329				      /*field*/ *len_used + page_len_offset,
6330				      /*bit_valid*/ 0,
6331				      /*bit*/ 0);
6332		free(ctsio->kern_data_ptr, M_CTL);
6333		ctl_done((union ctl_io *)ctsio);
6334		return (CTL_RETVAL_COMPLETE);
6335	}
6336
6337	/*
6338	 * Run through the mode page, checking to make sure that the bits
6339	 * the user changed are actually legal for him to change.
6340	 */
6341	for (i = 0; i < page_index->page_len; i++) {
6342		uint8_t *user_byte, *change_mask, *current_byte;
6343		int bad_bit;
6344		int j;
6345
6346		user_byte = (uint8_t *)page_header + i;
6347		change_mask = page_index->page_data +
6348			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6349		current_byte = page_index->page_data +
6350			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6351
6352		/*
6353		 * Check to see whether the user set any bits in this byte
6354		 * that he is not allowed to set.
6355		 */
6356		if ((*user_byte & ~(*change_mask)) ==
6357		    (*current_byte & ~(*change_mask)))
6358			continue;
6359
6360		/*
6361		 * Go through bit by bit to determine which one is illegal.
6362		 */
6363		bad_bit = 0;
6364		for (j = 7; j >= 0; j--) {
6365			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6366			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6367				bad_bit = i;
6368				break;
6369			}
6370		}
6371		ctl_set_invalid_field(ctsio,
6372				      /*sks_valid*/ 1,
6373				      /*command*/ 0,
6374				      /*field*/ *len_used + i,
6375				      /*bit_valid*/ 1,
6376				      /*bit*/ bad_bit);
6377		free(ctsio->kern_data_ptr, M_CTL);
6378		ctl_done((union ctl_io *)ctsio);
6379		return (CTL_RETVAL_COMPLETE);
6380	}
6381
6382	/*
6383	 * Decrement these before we call the page handler, since we may
6384	 * end up getting called back one way or another before the handler
6385	 * returns to this context.
6386	 */
6387	*len_left -= page_index->page_len;
6388	*len_used += page_index->page_len;
6389
6390	retval = page_index->select_handler(ctsio, page_index,
6391					    (uint8_t *)page_header);
6392
6393	/*
6394	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6395	 * wait until this queued command completes to finish processing
6396	 * the mode page.  If it returns anything other than
6397	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6398	 * already set the sense information, freed the data pointer, and
6399	 * completed the io for us.
6400	 */
6401	if (retval != CTL_RETVAL_COMPLETE)
6402		goto bailout_no_done;
6403
6404	/*
6405	 * If the initiator sent us more than one page, parse the next one.
6406	 */
6407	if (*len_left > 0)
6408		goto do_next_page;
6409
6410	ctl_set_success(ctsio);
6411	free(ctsio->kern_data_ptr, M_CTL);
6412	ctl_done((union ctl_io *)ctsio);
6413
6414bailout_no_done:
6415
6416	return (CTL_RETVAL_COMPLETE);
6417
6418}
6419
6420int
6421ctl_mode_select(struct ctl_scsiio *ctsio)
6422{
6423	int param_len, pf, sp;
6424	int header_size, bd_len;
6425	int len_left, len_used;
6426	struct ctl_page_index *page_index;
6427	struct ctl_lun *lun;
6428	int control_dev, page_len;
6429	union ctl_modepage_info *modepage_info;
6430	int retval;
6431
6432	pf = 0;
6433	sp = 0;
6434	page_len = 0;
6435	len_used = 0;
6436	len_left = 0;
6437	retval = 0;
6438	bd_len = 0;
6439	page_index = NULL;
6440
6441	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6442
6443	if (lun->be_lun->lun_type != T_DIRECT)
6444		control_dev = 1;
6445	else
6446		control_dev = 0;
6447
6448	switch (ctsio->cdb[0]) {
6449	case MODE_SELECT_6: {
6450		struct scsi_mode_select_6 *cdb;
6451
6452		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6453
6454		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6455		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6456
6457		param_len = cdb->length;
6458		header_size = sizeof(struct scsi_mode_header_6);
6459		break;
6460	}
6461	case MODE_SELECT_10: {
6462		struct scsi_mode_select_10 *cdb;
6463
6464		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6465
6466		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6467		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6468
6469		param_len = scsi_2btoul(cdb->length);
6470		header_size = sizeof(struct scsi_mode_header_10);
6471		break;
6472	}
6473	default:
6474		ctl_set_invalid_opcode(ctsio);
6475		ctl_done((union ctl_io *)ctsio);
6476		return (CTL_RETVAL_COMPLETE);
6477		break; /* NOTREACHED */
6478	}
6479
6480	/*
6481	 * From SPC-3:
6482	 * "A parameter list length of zero indicates that the Data-Out Buffer
6483	 * shall be empty. This condition shall not be considered as an error."
6484	 */
6485	if (param_len == 0) {
6486		ctl_set_success(ctsio);
6487		ctl_done((union ctl_io *)ctsio);
6488		return (CTL_RETVAL_COMPLETE);
6489	}
6490
6491	/*
6492	 * Since we'll hit this the first time through, prior to
6493	 * allocation, we don't need to free a data buffer here.
6494	 */
6495	if (param_len < header_size) {
6496		ctl_set_param_len_error(ctsio);
6497		ctl_done((union ctl_io *)ctsio);
6498		return (CTL_RETVAL_COMPLETE);
6499	}
6500
6501	/*
6502	 * Allocate the data buffer and grab the user's data.  In theory,
6503	 * we shouldn't have to sanity check the parameter list length here
6504	 * because the maximum size is 64K.  We should be able to malloc
6505	 * that much without too many problems.
6506	 */
6507	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6508		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6509		ctsio->kern_data_len = param_len;
6510		ctsio->kern_total_len = param_len;
6511		ctsio->kern_data_resid = 0;
6512		ctsio->kern_rel_offset = 0;
6513		ctsio->kern_sg_entries = 0;
6514		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6515		ctsio->be_move_done = ctl_config_move_done;
6516		ctl_datamove((union ctl_io *)ctsio);
6517
6518		return (CTL_RETVAL_COMPLETE);
6519	}
6520
6521	switch (ctsio->cdb[0]) {
6522	case MODE_SELECT_6: {
6523		struct scsi_mode_header_6 *mh6;
6524
6525		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6526		bd_len = mh6->blk_desc_len;
6527		break;
6528	}
6529	case MODE_SELECT_10: {
6530		struct scsi_mode_header_10 *mh10;
6531
6532		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6533		bd_len = scsi_2btoul(mh10->blk_desc_len);
6534		break;
6535	}
6536	default:
6537		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6538		break;
6539	}
6540
6541	if (param_len < (header_size + bd_len)) {
6542		free(ctsio->kern_data_ptr, M_CTL);
6543		ctl_set_param_len_error(ctsio);
6544		ctl_done((union ctl_io *)ctsio);
6545		return (CTL_RETVAL_COMPLETE);
6546	}
6547
6548	/*
6549	 * Set the IO_CONT flag, so that if this I/O gets passed to
6550	 * ctl_config_write_done(), it'll get passed back to
6551	 * ctl_do_mode_select() for further processing, or completion if
6552	 * we're all done.
6553	 */
6554	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6555	ctsio->io_cont = ctl_do_mode_select;
6556
6557	modepage_info = (union ctl_modepage_info *)
6558		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6559
6560	memset(modepage_info, 0, sizeof(*modepage_info));
6561
6562	len_left = param_len - header_size - bd_len;
6563	len_used = header_size + bd_len;
6564
6565	modepage_info->header.len_left = len_left;
6566	modepage_info->header.len_used = len_used;
6567
6568	return (ctl_do_mode_select((union ctl_io *)ctsio));
6569}
6570
6571int
6572ctl_mode_sense(struct ctl_scsiio *ctsio)
6573{
6574	struct ctl_lun *lun;
6575	int pc, page_code, dbd, llba, subpage;
6576	int alloc_len, page_len, header_len, total_len;
6577	struct scsi_mode_block_descr *block_desc;
6578	struct ctl_page_index *page_index;
6579	int control_dev;
6580
6581	dbd = 0;
6582	llba = 0;
6583	block_desc = NULL;
6584	page_index = NULL;
6585
6586	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6587
6588	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6589
6590	if (lun->be_lun->lun_type != T_DIRECT)
6591		control_dev = 1;
6592	else
6593		control_dev = 0;
6594
6595	if (lun->flags & CTL_LUN_PR_RESERVED) {
6596		uint32_t residx;
6597
6598		/*
6599		 * XXX KDM need a lock here.
6600		 */
6601		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6602		if ((lun->res_type == SPR_TYPE_EX_AC
6603		  && residx != lun->pr_res_idx)
6604		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6605		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6606		  && lun->pr_keys[residx] == 0)) {
6607			ctl_set_reservation_conflict(ctsio);
6608			ctl_done((union ctl_io *)ctsio);
6609			return (CTL_RETVAL_COMPLETE);
6610		}
6611	}
6612
6613	switch (ctsio->cdb[0]) {
6614	case MODE_SENSE_6: {
6615		struct scsi_mode_sense_6 *cdb;
6616
6617		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6618
6619		header_len = sizeof(struct scsi_mode_hdr_6);
6620		if (cdb->byte2 & SMS_DBD)
6621			dbd = 1;
6622		else
6623			header_len += sizeof(struct scsi_mode_block_descr);
6624
6625		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6626		page_code = cdb->page & SMS_PAGE_CODE;
6627		subpage = cdb->subpage;
6628		alloc_len = cdb->length;
6629		break;
6630	}
6631	case MODE_SENSE_10: {
6632		struct scsi_mode_sense_10 *cdb;
6633
6634		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6635
6636		header_len = sizeof(struct scsi_mode_hdr_10);
6637
6638		if (cdb->byte2 & SMS_DBD)
6639			dbd = 1;
6640		else
6641			header_len += sizeof(struct scsi_mode_block_descr);
6642		if (cdb->byte2 & SMS10_LLBAA)
6643			llba = 1;
6644		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6645		page_code = cdb->page & SMS_PAGE_CODE;
6646		subpage = cdb->subpage;
6647		alloc_len = scsi_2btoul(cdb->length);
6648		break;
6649	}
6650	default:
6651		ctl_set_invalid_opcode(ctsio);
6652		ctl_done((union ctl_io *)ctsio);
6653		return (CTL_RETVAL_COMPLETE);
6654		break; /* NOTREACHED */
6655	}
6656
6657	/*
6658	 * We have to make a first pass through to calculate the size of
6659	 * the pages that match the user's query.  Then we allocate enough
6660	 * memory to hold it, and actually copy the data into the buffer.
6661	 */
6662	switch (page_code) {
6663	case SMS_ALL_PAGES_PAGE: {
6664		int i;
6665
6666		page_len = 0;
6667
6668		/*
6669		 * At the moment, values other than 0 and 0xff here are
6670		 * reserved according to SPC-3.
6671		 */
6672		if ((subpage != SMS_SUBPAGE_PAGE_0)
6673		 && (subpage != SMS_SUBPAGE_ALL)) {
6674			ctl_set_invalid_field(ctsio,
6675					      /*sks_valid*/ 1,
6676					      /*command*/ 1,
6677					      /*field*/ 3,
6678					      /*bit_valid*/ 0,
6679					      /*bit*/ 0);
6680			ctl_done((union ctl_io *)ctsio);
6681			return (CTL_RETVAL_COMPLETE);
6682		}
6683
6684		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6685			if ((control_dev != 0)
6686			 && (lun->mode_pages.index[i].page_flags &
6687			     CTL_PAGE_FLAG_DISK_ONLY))
6688				continue;
6689
6690			/*
6691			 * We don't use this subpage if the user didn't
6692			 * request all subpages.
6693			 */
6694			if ((lun->mode_pages.index[i].subpage != 0)
6695			 && (subpage == SMS_SUBPAGE_PAGE_0))
6696				continue;
6697
6698#if 0
6699			printf("found page %#x len %d\n",
6700			       lun->mode_pages.index[i].page_code &
6701			       SMPH_PC_MASK,
6702			       lun->mode_pages.index[i].page_len);
6703#endif
6704			page_len += lun->mode_pages.index[i].page_len;
6705		}
6706		break;
6707	}
6708	default: {
6709		int i;
6710
6711		page_len = 0;
6712
6713		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6714			/* Look for the right page code */
6715			if ((lun->mode_pages.index[i].page_code &
6716			     SMPH_PC_MASK) != page_code)
6717				continue;
6718
6719			/* Look for the right subpage or the subpage wildcard*/
6720			if ((lun->mode_pages.index[i].subpage != subpage)
6721			 && (subpage != SMS_SUBPAGE_ALL))
6722				continue;
6723
6724			/* Make sure the page is supported for this dev type */
6725			if ((control_dev != 0)
6726			 && (lun->mode_pages.index[i].page_flags &
6727			     CTL_PAGE_FLAG_DISK_ONLY))
6728				continue;
6729
6730#if 0
6731			printf("found page %#x len %d\n",
6732			       lun->mode_pages.index[i].page_code &
6733			       SMPH_PC_MASK,
6734			       lun->mode_pages.index[i].page_len);
6735#endif
6736
6737			page_len += lun->mode_pages.index[i].page_len;
6738		}
6739
6740		if (page_len == 0) {
6741			ctl_set_invalid_field(ctsio,
6742					      /*sks_valid*/ 1,
6743					      /*command*/ 1,
6744					      /*field*/ 2,
6745					      /*bit_valid*/ 1,
6746					      /*bit*/ 5);
6747			ctl_done((union ctl_io *)ctsio);
6748			return (CTL_RETVAL_COMPLETE);
6749		}
6750		break;
6751	}
6752	}
6753
6754	total_len = header_len + page_len;
6755#if 0
6756	printf("header_len = %d, page_len = %d, total_len = %d\n",
6757	       header_len, page_len, total_len);
6758#endif
6759
6760	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6761	ctsio->kern_sg_entries = 0;
6762	ctsio->kern_data_resid = 0;
6763	ctsio->kern_rel_offset = 0;
6764	if (total_len < alloc_len) {
6765		ctsio->residual = alloc_len - total_len;
6766		ctsio->kern_data_len = total_len;
6767		ctsio->kern_total_len = total_len;
6768	} else {
6769		ctsio->residual = 0;
6770		ctsio->kern_data_len = alloc_len;
6771		ctsio->kern_total_len = alloc_len;
6772	}
6773
6774	switch (ctsio->cdb[0]) {
6775	case MODE_SENSE_6: {
6776		struct scsi_mode_hdr_6 *header;
6777
6778		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6779
6780		header->datalen = ctl_min(total_len - 1, 254);
6781		if (control_dev == 0) {
6782			header->dev_specific = 0x10; /* DPOFUA */
6783			if ((lun->flags & CTL_LUN_READONLY) ||
6784			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6785			    .eca_and_aen & SCP_SWP) != 0)
6786				    header->dev_specific |= 0x80; /* WP */
6787		}
6788		if (dbd)
6789			header->block_descr_len = 0;
6790		else
6791			header->block_descr_len =
6792				sizeof(struct scsi_mode_block_descr);
6793		block_desc = (struct scsi_mode_block_descr *)&header[1];
6794		break;
6795	}
6796	case MODE_SENSE_10: {
6797		struct scsi_mode_hdr_10 *header;
6798		int datalen;
6799
6800		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6801
6802		datalen = ctl_min(total_len - 2, 65533);
6803		scsi_ulto2b(datalen, header->datalen);
6804		if (control_dev == 0) {
6805			header->dev_specific = 0x10; /* DPOFUA */
6806			if ((lun->flags & CTL_LUN_READONLY) ||
6807			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6808			    .eca_and_aen & SCP_SWP) != 0)
6809				    header->dev_specific |= 0x80; /* WP */
6810		}
6811		if (dbd)
6812			scsi_ulto2b(0, header->block_descr_len);
6813		else
6814			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6815				    header->block_descr_len);
6816		block_desc = (struct scsi_mode_block_descr *)&header[1];
6817		break;
6818	}
6819	default:
6820		panic("invalid CDB type %#x", ctsio->cdb[0]);
6821		break; /* NOTREACHED */
6822	}
6823
6824	/*
6825	 * If we've got a disk, use its blocksize in the block
6826	 * descriptor.  Otherwise, just set it to 0.
6827	 */
6828	if (dbd == 0) {
6829		if (control_dev == 0)
6830			scsi_ulto3b(lun->be_lun->blocksize,
6831				    block_desc->block_len);
6832		else
6833			scsi_ulto3b(0, block_desc->block_len);
6834	}
6835
6836	switch (page_code) {
6837	case SMS_ALL_PAGES_PAGE: {
6838		int i, data_used;
6839
6840		data_used = header_len;
6841		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6842			struct ctl_page_index *page_index;
6843
6844			page_index = &lun->mode_pages.index[i];
6845
6846			if ((control_dev != 0)
6847			 && (page_index->page_flags &
6848			    CTL_PAGE_FLAG_DISK_ONLY))
6849				continue;
6850
6851			/*
6852			 * We don't use this subpage if the user didn't
6853			 * request all subpages.  We already checked (above)
6854			 * to make sure the user only specified a subpage
6855			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6856			 */
6857			if ((page_index->subpage != 0)
6858			 && (subpage == SMS_SUBPAGE_PAGE_0))
6859				continue;
6860
6861			/*
6862			 * Call the handler, if it exists, to update the
6863			 * page to the latest values.
6864			 */
6865			if (page_index->sense_handler != NULL)
6866				page_index->sense_handler(ctsio, page_index,pc);
6867
6868			memcpy(ctsio->kern_data_ptr + data_used,
6869			       page_index->page_data +
6870			       (page_index->page_len * pc),
6871			       page_index->page_len);
6872			data_used += page_index->page_len;
6873		}
6874		break;
6875	}
6876	default: {
6877		int i, data_used;
6878
6879		data_used = header_len;
6880
6881		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6882			struct ctl_page_index *page_index;
6883
6884			page_index = &lun->mode_pages.index[i];
6885
6886			/* Look for the right page code */
6887			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6888				continue;
6889
6890			/* Look for the right subpage or the subpage wildcard*/
6891			if ((page_index->subpage != subpage)
6892			 && (subpage != SMS_SUBPAGE_ALL))
6893				continue;
6894
6895			/* Make sure the page is supported for this dev type */
6896			if ((control_dev != 0)
6897			 && (page_index->page_flags &
6898			     CTL_PAGE_FLAG_DISK_ONLY))
6899				continue;
6900
6901			/*
6902			 * Call the handler, if it exists, to update the
6903			 * page to the latest values.
6904			 */
6905			if (page_index->sense_handler != NULL)
6906				page_index->sense_handler(ctsio, page_index,pc);
6907
6908			memcpy(ctsio->kern_data_ptr + data_used,
6909			       page_index->page_data +
6910			       (page_index->page_len * pc),
6911			       page_index->page_len);
6912			data_used += page_index->page_len;
6913		}
6914		break;
6915	}
6916	}
6917
6918	ctsio->scsi_status = SCSI_STATUS_OK;
6919
6920	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6921	ctsio->be_move_done = ctl_config_move_done;
6922	ctl_datamove((union ctl_io *)ctsio);
6923
6924	return (CTL_RETVAL_COMPLETE);
6925}
6926
6927int
6928ctl_log_sense(struct ctl_scsiio *ctsio)
6929{
6930	struct ctl_lun *lun;
6931	int i, pc, page_code, subpage;
6932	int alloc_len, total_len;
6933	struct ctl_page_index *page_index;
6934	struct scsi_log_sense *cdb;
6935	struct scsi_log_header *header;
6936
6937	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6938
6939	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6940	cdb = (struct scsi_log_sense *)ctsio->cdb;
6941	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6942	page_code = cdb->page & SLS_PAGE_CODE;
6943	subpage = cdb->subpage;
6944	alloc_len = scsi_2btoul(cdb->length);
6945
6946	page_index = NULL;
6947	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6948		page_index = &lun->log_pages.index[i];
6949
6950		/* Look for the right page code */
6951		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6952			continue;
6953
6954		/* Look for the right subpage or the subpage wildcard*/
6955		if (page_index->subpage != subpage)
6956			continue;
6957
6958		break;
6959	}
6960	if (i >= CTL_NUM_LOG_PAGES) {
6961		ctl_set_invalid_field(ctsio,
6962				      /*sks_valid*/ 1,
6963				      /*command*/ 1,
6964				      /*field*/ 2,
6965				      /*bit_valid*/ 0,
6966				      /*bit*/ 0);
6967		ctl_done((union ctl_io *)ctsio);
6968		return (CTL_RETVAL_COMPLETE);
6969	}
6970
6971	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6972
6973	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6974	ctsio->kern_sg_entries = 0;
6975	ctsio->kern_data_resid = 0;
6976	ctsio->kern_rel_offset = 0;
6977	if (total_len < alloc_len) {
6978		ctsio->residual = alloc_len - total_len;
6979		ctsio->kern_data_len = total_len;
6980		ctsio->kern_total_len = total_len;
6981	} else {
6982		ctsio->residual = 0;
6983		ctsio->kern_data_len = alloc_len;
6984		ctsio->kern_total_len = alloc_len;
6985	}
6986
6987	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6988	header->page = page_index->page_code;
6989	if (page_index->subpage) {
6990		header->page |= SL_SPF;
6991		header->subpage = page_index->subpage;
6992	}
6993	scsi_ulto2b(page_index->page_len, header->datalen);
6994
6995	/*
6996	 * Call the handler, if it exists, to update the
6997	 * page to the latest values.
6998	 */
6999	if (page_index->sense_handler != NULL)
7000		page_index->sense_handler(ctsio, page_index, pc);
7001
7002	memcpy(header + 1, page_index->page_data, page_index->page_len);
7003
7004	ctsio->scsi_status = SCSI_STATUS_OK;
7005	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7006	ctsio->be_move_done = ctl_config_move_done;
7007	ctl_datamove((union ctl_io *)ctsio);
7008
7009	return (CTL_RETVAL_COMPLETE);
7010}
7011
7012int
7013ctl_read_capacity(struct ctl_scsiio *ctsio)
7014{
7015	struct scsi_read_capacity *cdb;
7016	struct scsi_read_capacity_data *data;
7017	struct ctl_lun *lun;
7018	uint32_t lba;
7019
7020	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7021
7022	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7023
7024	lba = scsi_4btoul(cdb->addr);
7025	if (((cdb->pmi & SRC_PMI) == 0)
7026	 && (lba != 0)) {
7027		ctl_set_invalid_field(/*ctsio*/ ctsio,
7028				      /*sks_valid*/ 1,
7029				      /*command*/ 1,
7030				      /*field*/ 2,
7031				      /*bit_valid*/ 0,
7032				      /*bit*/ 0);
7033		ctl_done((union ctl_io *)ctsio);
7034		return (CTL_RETVAL_COMPLETE);
7035	}
7036
7037	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7038
7039	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7040	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7041	ctsio->residual = 0;
7042	ctsio->kern_data_len = sizeof(*data);
7043	ctsio->kern_total_len = sizeof(*data);
7044	ctsio->kern_data_resid = 0;
7045	ctsio->kern_rel_offset = 0;
7046	ctsio->kern_sg_entries = 0;
7047
7048	/*
7049	 * If the maximum LBA is greater than 0xfffffffe, the user must
7050	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7051	 * serivce action set.
7052	 */
7053	if (lun->be_lun->maxlba > 0xfffffffe)
7054		scsi_ulto4b(0xffffffff, data->addr);
7055	else
7056		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7057
7058	/*
7059	 * XXX KDM this may not be 512 bytes...
7060	 */
7061	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7062
7063	ctsio->scsi_status = SCSI_STATUS_OK;
7064
7065	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7066	ctsio->be_move_done = ctl_config_move_done;
7067	ctl_datamove((union ctl_io *)ctsio);
7068
7069	return (CTL_RETVAL_COMPLETE);
7070}
7071
7072int
7073ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7074{
7075	struct scsi_read_capacity_16 *cdb;
7076	struct scsi_read_capacity_data_long *data;
7077	struct ctl_lun *lun;
7078	uint64_t lba;
7079	uint32_t alloc_len;
7080
7081	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7082
7083	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7084
7085	alloc_len = scsi_4btoul(cdb->alloc_len);
7086	lba = scsi_8btou64(cdb->addr);
7087
7088	if ((cdb->reladr & SRC16_PMI)
7089	 && (lba != 0)) {
7090		ctl_set_invalid_field(/*ctsio*/ ctsio,
7091				      /*sks_valid*/ 1,
7092				      /*command*/ 1,
7093				      /*field*/ 2,
7094				      /*bit_valid*/ 0,
7095				      /*bit*/ 0);
7096		ctl_done((union ctl_io *)ctsio);
7097		return (CTL_RETVAL_COMPLETE);
7098	}
7099
7100	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7101
7102	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7103	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7104
7105	if (sizeof(*data) < alloc_len) {
7106		ctsio->residual = alloc_len - sizeof(*data);
7107		ctsio->kern_data_len = sizeof(*data);
7108		ctsio->kern_total_len = sizeof(*data);
7109	} else {
7110		ctsio->residual = 0;
7111		ctsio->kern_data_len = alloc_len;
7112		ctsio->kern_total_len = alloc_len;
7113	}
7114	ctsio->kern_data_resid = 0;
7115	ctsio->kern_rel_offset = 0;
7116	ctsio->kern_sg_entries = 0;
7117
7118	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7119	/* XXX KDM this may not be 512 bytes... */
7120	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7121	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7122	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7123	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7124		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7125
7126	ctsio->scsi_status = SCSI_STATUS_OK;
7127
7128	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7129	ctsio->be_move_done = ctl_config_move_done;
7130	ctl_datamove((union ctl_io *)ctsio);
7131
7132	return (CTL_RETVAL_COMPLETE);
7133}
7134
7135int
7136ctl_read_defect(struct ctl_scsiio *ctsio)
7137{
7138	struct scsi_read_defect_data_10 *ccb10;
7139	struct scsi_read_defect_data_12 *ccb12;
7140	struct scsi_read_defect_data_hdr_10 *data10;
7141	struct scsi_read_defect_data_hdr_12 *data12;
7142	struct ctl_lun *lun;
7143	uint32_t alloc_len, data_len;
7144	uint8_t format;
7145
7146	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7147
7148	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7149	if (lun->flags & CTL_LUN_PR_RESERVED) {
7150		uint32_t residx;
7151
7152		/*
7153		 * XXX KDM need a lock here.
7154		 */
7155		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7156		if ((lun->res_type == SPR_TYPE_EX_AC
7157		  && residx != lun->pr_res_idx)
7158		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
7159		   || lun->res_type == SPR_TYPE_EX_AC_AR)
7160		  && lun->pr_keys[residx] == 0)) {
7161			ctl_set_reservation_conflict(ctsio);
7162			ctl_done((union ctl_io *)ctsio);
7163			return (CTL_RETVAL_COMPLETE);
7164	        }
7165	}
7166
7167	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7168		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7169		format = ccb10->format;
7170		alloc_len = scsi_2btoul(ccb10->alloc_length);
7171		data_len = sizeof(*data10);
7172	} else {
7173		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7174		format = ccb12->format;
7175		alloc_len = scsi_4btoul(ccb12->alloc_length);
7176		data_len = sizeof(*data12);
7177	}
7178	if (alloc_len == 0) {
7179		ctl_set_success(ctsio);
7180		ctl_done((union ctl_io *)ctsio);
7181		return (CTL_RETVAL_COMPLETE);
7182	}
7183
7184	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7185	if (data_len < alloc_len) {
7186		ctsio->residual = alloc_len - data_len;
7187		ctsio->kern_data_len = data_len;
7188		ctsio->kern_total_len = data_len;
7189	} else {
7190		ctsio->residual = 0;
7191		ctsio->kern_data_len = alloc_len;
7192		ctsio->kern_total_len = alloc_len;
7193	}
7194	ctsio->kern_data_resid = 0;
7195	ctsio->kern_rel_offset = 0;
7196	ctsio->kern_sg_entries = 0;
7197
7198	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7199		data10 = (struct scsi_read_defect_data_hdr_10 *)
7200		    ctsio->kern_data_ptr;
7201		data10->format = format;
7202		scsi_ulto2b(0, data10->length);
7203	} else {
7204		data12 = (struct scsi_read_defect_data_hdr_12 *)
7205		    ctsio->kern_data_ptr;
7206		data12->format = format;
7207		scsi_ulto2b(0, data12->generation);
7208		scsi_ulto4b(0, data12->length);
7209	}
7210
7211	ctsio->scsi_status = SCSI_STATUS_OK;
7212	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7213	ctsio->be_move_done = ctl_config_move_done;
7214	ctl_datamove((union ctl_io *)ctsio);
7215	return (CTL_RETVAL_COMPLETE);
7216}
7217
7218int
7219ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7220{
7221	struct scsi_maintenance_in *cdb;
7222	int retval;
7223	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7224	int num_target_port_groups, num_target_ports, single;
7225	struct ctl_lun *lun;
7226	struct ctl_softc *softc;
7227	struct ctl_port *port;
7228	struct scsi_target_group_data *rtg_ptr;
7229	struct scsi_target_group_data_extended *rtg_ext_ptr;
7230	struct scsi_target_port_group_descriptor *tpg_desc;
7231
7232	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7233
7234	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7235	softc = control_softc;
7236	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7237
7238	retval = CTL_RETVAL_COMPLETE;
7239
7240	switch (cdb->byte2 & STG_PDF_MASK) {
7241	case STG_PDF_LENGTH:
7242		ext = 0;
7243		break;
7244	case STG_PDF_EXTENDED:
7245		ext = 1;
7246		break;
7247	default:
7248		ctl_set_invalid_field(/*ctsio*/ ctsio,
7249				      /*sks_valid*/ 1,
7250				      /*command*/ 1,
7251				      /*field*/ 2,
7252				      /*bit_valid*/ 1,
7253				      /*bit*/ 5);
7254		ctl_done((union ctl_io *)ctsio);
7255		return(retval);
7256	}
7257
7258	single = ctl_is_single;
7259	if (single)
7260		num_target_port_groups = 1;
7261	else
7262		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7263	num_target_ports = 0;
7264	mtx_lock(&softc->ctl_lock);
7265	STAILQ_FOREACH(port, &softc->port_list, links) {
7266		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7267			continue;
7268		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7269			continue;
7270		num_target_ports++;
7271	}
7272	mtx_unlock(&softc->ctl_lock);
7273
7274	if (ext)
7275		total_len = sizeof(struct scsi_target_group_data_extended);
7276	else
7277		total_len = sizeof(struct scsi_target_group_data);
7278	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7279		num_target_port_groups +
7280	    sizeof(struct scsi_target_port_descriptor) *
7281		num_target_ports * num_target_port_groups;
7282
7283	alloc_len = scsi_4btoul(cdb->length);
7284
7285	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7286
7287	ctsio->kern_sg_entries = 0;
7288
7289	if (total_len < alloc_len) {
7290		ctsio->residual = alloc_len - total_len;
7291		ctsio->kern_data_len = total_len;
7292		ctsio->kern_total_len = total_len;
7293	} else {
7294		ctsio->residual = 0;
7295		ctsio->kern_data_len = alloc_len;
7296		ctsio->kern_total_len = alloc_len;
7297	}
7298	ctsio->kern_data_resid = 0;
7299	ctsio->kern_rel_offset = 0;
7300
7301	if (ext) {
7302		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7303		    ctsio->kern_data_ptr;
7304		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7305		rtg_ext_ptr->format_type = 0x10;
7306		rtg_ext_ptr->implicit_transition_time = 0;
7307		tpg_desc = &rtg_ext_ptr->groups[0];
7308	} else {
7309		rtg_ptr = (struct scsi_target_group_data *)
7310		    ctsio->kern_data_ptr;
7311		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7312		tpg_desc = &rtg_ptr->groups[0];
7313	}
7314
7315	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7316	mtx_lock(&softc->ctl_lock);
7317	for (g = 0; g < num_target_port_groups; g++) {
7318		if (g == pg)
7319			tpg_desc->pref_state = TPG_PRIMARY |
7320			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7321		else
7322			tpg_desc->pref_state =
7323			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7324		tpg_desc->support = TPG_AO_SUP;
7325		if (!single)
7326			tpg_desc->support |= TPG_AN_SUP;
7327		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7328		tpg_desc->status = TPG_IMPLICIT;
7329		pc = 0;
7330		STAILQ_FOREACH(port, &softc->port_list, links) {
7331			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7332				continue;
7333			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7334			    CTL_MAX_LUNS)
7335				continue;
7336			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7337			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7338			    relative_target_port_identifier);
7339			pc++;
7340		}
7341		tpg_desc->target_port_count = pc;
7342		tpg_desc = (struct scsi_target_port_group_descriptor *)
7343		    &tpg_desc->descriptors[pc];
7344	}
7345	mtx_unlock(&softc->ctl_lock);
7346
7347	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7348	ctsio->be_move_done = ctl_config_move_done;
7349
7350	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7351			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7352			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7353			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7354			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7355
7356	ctl_datamove((union ctl_io *)ctsio);
7357	return(retval);
7358}
7359
7360int
7361ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7362{
7363	struct ctl_lun *lun;
7364	struct scsi_report_supported_opcodes *cdb;
7365	const struct ctl_cmd_entry *entry, *sentry;
7366	struct scsi_report_supported_opcodes_all *all;
7367	struct scsi_report_supported_opcodes_descr *descr;
7368	struct scsi_report_supported_opcodes_one *one;
7369	int retval;
7370	int alloc_len, total_len;
7371	int opcode, service_action, i, j, num;
7372
7373	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7374
7375	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7376	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7377
7378	retval = CTL_RETVAL_COMPLETE;
7379
7380	opcode = cdb->requested_opcode;
7381	service_action = scsi_2btoul(cdb->requested_service_action);
7382	switch (cdb->options & RSO_OPTIONS_MASK) {
7383	case RSO_OPTIONS_ALL:
7384		num = 0;
7385		for (i = 0; i < 256; i++) {
7386			entry = &ctl_cmd_table[i];
7387			if (entry->flags & CTL_CMD_FLAG_SA5) {
7388				for (j = 0; j < 32; j++) {
7389					sentry = &((const struct ctl_cmd_entry *)
7390					    entry->execute)[j];
7391					if (ctl_cmd_applicable(
7392					    lun->be_lun->lun_type, sentry))
7393						num++;
7394				}
7395			} else {
7396				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7397				    entry))
7398					num++;
7399			}
7400		}
7401		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7402		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7403		break;
7404	case RSO_OPTIONS_OC:
7405		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7406			ctl_set_invalid_field(/*ctsio*/ ctsio,
7407					      /*sks_valid*/ 1,
7408					      /*command*/ 1,
7409					      /*field*/ 2,
7410					      /*bit_valid*/ 1,
7411					      /*bit*/ 2);
7412			ctl_done((union ctl_io *)ctsio);
7413			return (CTL_RETVAL_COMPLETE);
7414		}
7415		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7416		break;
7417	case RSO_OPTIONS_OC_SA:
7418		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7419		    service_action >= 32) {
7420			ctl_set_invalid_field(/*ctsio*/ ctsio,
7421					      /*sks_valid*/ 1,
7422					      /*command*/ 1,
7423					      /*field*/ 2,
7424					      /*bit_valid*/ 1,
7425					      /*bit*/ 2);
7426			ctl_done((union ctl_io *)ctsio);
7427			return (CTL_RETVAL_COMPLETE);
7428		}
7429		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7430		break;
7431	default:
7432		ctl_set_invalid_field(/*ctsio*/ ctsio,
7433				      /*sks_valid*/ 1,
7434				      /*command*/ 1,
7435				      /*field*/ 2,
7436				      /*bit_valid*/ 1,
7437				      /*bit*/ 2);
7438		ctl_done((union ctl_io *)ctsio);
7439		return (CTL_RETVAL_COMPLETE);
7440	}
7441
7442	alloc_len = scsi_4btoul(cdb->length);
7443
7444	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7445
7446	ctsio->kern_sg_entries = 0;
7447
7448	if (total_len < alloc_len) {
7449		ctsio->residual = alloc_len - total_len;
7450		ctsio->kern_data_len = total_len;
7451		ctsio->kern_total_len = total_len;
7452	} else {
7453		ctsio->residual = 0;
7454		ctsio->kern_data_len = alloc_len;
7455		ctsio->kern_total_len = alloc_len;
7456	}
7457	ctsio->kern_data_resid = 0;
7458	ctsio->kern_rel_offset = 0;
7459
7460	switch (cdb->options & RSO_OPTIONS_MASK) {
7461	case RSO_OPTIONS_ALL:
7462		all = (struct scsi_report_supported_opcodes_all *)
7463		    ctsio->kern_data_ptr;
7464		num = 0;
7465		for (i = 0; i < 256; i++) {
7466			entry = &ctl_cmd_table[i];
7467			if (entry->flags & CTL_CMD_FLAG_SA5) {
7468				for (j = 0; j < 32; j++) {
7469					sentry = &((const struct ctl_cmd_entry *)
7470					    entry->execute)[j];
7471					if (!ctl_cmd_applicable(
7472					    lun->be_lun->lun_type, sentry))
7473						continue;
7474					descr = &all->descr[num++];
7475					descr->opcode = i;
7476					scsi_ulto2b(j, descr->service_action);
7477					descr->flags = RSO_SERVACTV;
7478					scsi_ulto2b(sentry->length,
7479					    descr->cdb_length);
7480				}
7481			} else {
7482				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7483				    entry))
7484					continue;
7485				descr = &all->descr[num++];
7486				descr->opcode = i;
7487				scsi_ulto2b(0, descr->service_action);
7488				descr->flags = 0;
7489				scsi_ulto2b(entry->length, descr->cdb_length);
7490			}
7491		}
7492		scsi_ulto4b(
7493		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7494		    all->length);
7495		break;
7496	case RSO_OPTIONS_OC:
7497		one = (struct scsi_report_supported_opcodes_one *)
7498		    ctsio->kern_data_ptr;
7499		entry = &ctl_cmd_table[opcode];
7500		goto fill_one;
7501	case RSO_OPTIONS_OC_SA:
7502		one = (struct scsi_report_supported_opcodes_one *)
7503		    ctsio->kern_data_ptr;
7504		entry = &ctl_cmd_table[opcode];
7505		entry = &((const struct ctl_cmd_entry *)
7506		    entry->execute)[service_action];
7507fill_one:
7508		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7509			one->support = 3;
7510			scsi_ulto2b(entry->length, one->cdb_length);
7511			one->cdb_usage[0] = opcode;
7512			memcpy(&one->cdb_usage[1], entry->usage,
7513			    entry->length - 1);
7514		} else
7515			one->support = 1;
7516		break;
7517	}
7518
7519	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7520	ctsio->be_move_done = ctl_config_move_done;
7521
7522	ctl_datamove((union ctl_io *)ctsio);
7523	return(retval);
7524}
7525
7526int
7527ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7528{
7529	struct ctl_lun *lun;
7530	struct scsi_report_supported_tmf *cdb;
7531	struct scsi_report_supported_tmf_data *data;
7532	int retval;
7533	int alloc_len, total_len;
7534
7535	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7536
7537	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7538	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7539
7540	retval = CTL_RETVAL_COMPLETE;
7541
7542	total_len = sizeof(struct scsi_report_supported_tmf_data);
7543	alloc_len = scsi_4btoul(cdb->length);
7544
7545	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7546
7547	ctsio->kern_sg_entries = 0;
7548
7549	if (total_len < alloc_len) {
7550		ctsio->residual = alloc_len - total_len;
7551		ctsio->kern_data_len = total_len;
7552		ctsio->kern_total_len = total_len;
7553	} else {
7554		ctsio->residual = 0;
7555		ctsio->kern_data_len = alloc_len;
7556		ctsio->kern_total_len = alloc_len;
7557	}
7558	ctsio->kern_data_resid = 0;
7559	ctsio->kern_rel_offset = 0;
7560
7561	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7562	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7563	data->byte2 |= RST_ITNRS;
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_timestamp(struct ctl_scsiio *ctsio)
7574{
7575	struct ctl_lun *lun;
7576	struct scsi_report_timestamp *cdb;
7577	struct scsi_report_timestamp_data *data;
7578	struct timeval tv;
7579	int64_t timestamp;
7580	int retval;
7581	int alloc_len, total_len;
7582
7583	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7584
7585	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7586	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7587
7588	retval = CTL_RETVAL_COMPLETE;
7589
7590	total_len = sizeof(struct scsi_report_timestamp_data);
7591	alloc_len = scsi_4btoul(cdb->length);
7592
7593	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7594
7595	ctsio->kern_sg_entries = 0;
7596
7597	if (total_len < alloc_len) {
7598		ctsio->residual = alloc_len - total_len;
7599		ctsio->kern_data_len = total_len;
7600		ctsio->kern_total_len = total_len;
7601	} else {
7602		ctsio->residual = 0;
7603		ctsio->kern_data_len = alloc_len;
7604		ctsio->kern_total_len = alloc_len;
7605	}
7606	ctsio->kern_data_resid = 0;
7607	ctsio->kern_rel_offset = 0;
7608
7609	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7610	scsi_ulto2b(sizeof(*data) - 2, data->length);
7611	data->origin = RTS_ORIG_OUTSIDE;
7612	getmicrotime(&tv);
7613	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7614	scsi_ulto4b(timestamp >> 16, data->timestamp);
7615	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7616
7617	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7618	ctsio->be_move_done = ctl_config_move_done;
7619
7620	ctl_datamove((union ctl_io *)ctsio);
7621	return (retval);
7622}
7623
7624int
7625ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7626{
7627	struct scsi_per_res_in *cdb;
7628	int alloc_len, total_len = 0;
7629	/* struct scsi_per_res_in_rsrv in_data; */
7630	struct ctl_lun *lun;
7631	struct ctl_softc *softc;
7632
7633	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7634
7635	softc = control_softc;
7636
7637	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7638
7639	alloc_len = scsi_2btoul(cdb->length);
7640
7641	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7642
7643retry:
7644	mtx_lock(&lun->lun_lock);
7645	switch (cdb->action) {
7646	case SPRI_RK: /* read keys */
7647		total_len = sizeof(struct scsi_per_res_in_keys) +
7648			lun->pr_key_count *
7649			sizeof(struct scsi_per_res_key);
7650		break;
7651	case SPRI_RR: /* read reservation */
7652		if (lun->flags & CTL_LUN_PR_RESERVED)
7653			total_len = sizeof(struct scsi_per_res_in_rsrv);
7654		else
7655			total_len = sizeof(struct scsi_per_res_in_header);
7656		break;
7657	case SPRI_RC: /* report capabilities */
7658		total_len = sizeof(struct scsi_per_res_cap);
7659		break;
7660	case SPRI_RS: /* read full status */
7661		total_len = sizeof(struct scsi_per_res_in_header) +
7662		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7663		    lun->pr_key_count;
7664		break;
7665	default:
7666		panic("Invalid PR type %x", cdb->action);
7667	}
7668	mtx_unlock(&lun->lun_lock);
7669
7670	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7671
7672	if (total_len < alloc_len) {
7673		ctsio->residual = alloc_len - total_len;
7674		ctsio->kern_data_len = total_len;
7675		ctsio->kern_total_len = total_len;
7676	} else {
7677		ctsio->residual = 0;
7678		ctsio->kern_data_len = alloc_len;
7679		ctsio->kern_total_len = alloc_len;
7680	}
7681
7682	ctsio->kern_data_resid = 0;
7683	ctsio->kern_rel_offset = 0;
7684	ctsio->kern_sg_entries = 0;
7685
7686	mtx_lock(&lun->lun_lock);
7687	switch (cdb->action) {
7688	case SPRI_RK: { // read keys
7689        struct scsi_per_res_in_keys *res_keys;
7690		int i, key_count;
7691
7692		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7693
7694		/*
7695		 * We had to drop the lock to allocate our buffer, which
7696		 * leaves time for someone to come in with another
7697		 * persistent reservation.  (That is unlikely, though,
7698		 * since this should be the only persistent reservation
7699		 * command active right now.)
7700		 */
7701		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7702		    (lun->pr_key_count *
7703		     sizeof(struct scsi_per_res_key)))){
7704			mtx_unlock(&lun->lun_lock);
7705			free(ctsio->kern_data_ptr, M_CTL);
7706			printf("%s: reservation length changed, retrying\n",
7707			       __func__);
7708			goto retry;
7709		}
7710
7711		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7712
7713		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7714			     lun->pr_key_count, res_keys->header.length);
7715
7716		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7717			if (lun->pr_keys[i] == 0)
7718				continue;
7719
7720			/*
7721			 * We used lun->pr_key_count to calculate the
7722			 * size to allocate.  If it turns out the number of
7723			 * initiators with the registered flag set is
7724			 * larger than that (i.e. they haven't been kept in
7725			 * sync), we've got a problem.
7726			 */
7727			if (key_count >= lun->pr_key_count) {
7728#ifdef NEEDTOPORT
7729				csevent_log(CSC_CTL | CSC_SHELF_SW |
7730					    CTL_PR_ERROR,
7731					    csevent_LogType_Fault,
7732					    csevent_AlertLevel_Yellow,
7733					    csevent_FRU_ShelfController,
7734					    csevent_FRU_Firmware,
7735				        csevent_FRU_Unknown,
7736					    "registered keys %d >= key "
7737					    "count %d", key_count,
7738					    lun->pr_key_count);
7739#endif
7740				key_count++;
7741				continue;
7742			}
7743			scsi_u64to8b(lun->pr_keys[i],
7744			    res_keys->keys[key_count].key);
7745			key_count++;
7746		}
7747		break;
7748	}
7749	case SPRI_RR: { // read reservation
7750		struct scsi_per_res_in_rsrv *res;
7751		int tmp_len, header_only;
7752
7753		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7754
7755		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7756
7757		if (lun->flags & CTL_LUN_PR_RESERVED)
7758		{
7759			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7760			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7761				    res->header.length);
7762			header_only = 0;
7763		} else {
7764			tmp_len = sizeof(struct scsi_per_res_in_header);
7765			scsi_ulto4b(0, res->header.length);
7766			header_only = 1;
7767		}
7768
7769		/*
7770		 * We had to drop the lock to allocate our buffer, which
7771		 * leaves time for someone to come in with another
7772		 * persistent reservation.  (That is unlikely, though,
7773		 * since this should be the only persistent reservation
7774		 * command active right now.)
7775		 */
7776		if (tmp_len != total_len) {
7777			mtx_unlock(&lun->lun_lock);
7778			free(ctsio->kern_data_ptr, M_CTL);
7779			printf("%s: reservation status changed, retrying\n",
7780			       __func__);
7781			goto retry;
7782		}
7783
7784		/*
7785		 * No reservation held, so we're done.
7786		 */
7787		if (header_only != 0)
7788			break;
7789
7790		/*
7791		 * If the registration is an All Registrants type, the key
7792		 * is 0, since it doesn't really matter.
7793		 */
7794		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7795			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7796			    res->data.reservation);
7797		}
7798		res->data.scopetype = lun->res_type;
7799		break;
7800	}
7801	case SPRI_RC:     //report capabilities
7802	{
7803		struct scsi_per_res_cap *res_cap;
7804		uint16_t type_mask;
7805
7806		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7807		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7808		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7809		type_mask = SPRI_TM_WR_EX_AR |
7810			    SPRI_TM_EX_AC_RO |
7811			    SPRI_TM_WR_EX_RO |
7812			    SPRI_TM_EX_AC |
7813			    SPRI_TM_WR_EX |
7814			    SPRI_TM_EX_AC_AR;
7815		scsi_ulto2b(type_mask, res_cap->type_mask);
7816		break;
7817	}
7818	case SPRI_RS: { // read full status
7819		struct scsi_per_res_in_full *res_status;
7820		struct scsi_per_res_in_full_desc *res_desc;
7821		struct ctl_port *port;
7822		int i, len;
7823
7824		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7825
7826		/*
7827		 * We had to drop the lock to allocate our buffer, which
7828		 * leaves time for someone to come in with another
7829		 * persistent reservation.  (That is unlikely, though,
7830		 * since this should be the only persistent reservation
7831		 * command active right now.)
7832		 */
7833		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7834		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7835		     lun->pr_key_count)){
7836			mtx_unlock(&lun->lun_lock);
7837			free(ctsio->kern_data_ptr, M_CTL);
7838			printf("%s: reservation length changed, retrying\n",
7839			       __func__);
7840			goto retry;
7841		}
7842
7843		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7844
7845		res_desc = &res_status->desc[0];
7846		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7847			if (lun->pr_keys[i] == 0)
7848				continue;
7849
7850			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7851			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7852			    (lun->pr_res_idx == i ||
7853			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7854				res_desc->flags = SPRI_FULL_R_HOLDER;
7855				res_desc->scopetype = lun->res_type;
7856			}
7857			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7858			    res_desc->rel_trgt_port_id);
7859			len = 0;
7860			port = softc->ctl_ports[
7861			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7862			if (port != NULL)
7863				len = ctl_create_iid(port,
7864				    i % CTL_MAX_INIT_PER_PORT,
7865				    res_desc->transport_id);
7866			scsi_ulto4b(len, res_desc->additional_length);
7867			res_desc = (struct scsi_per_res_in_full_desc *)
7868			    &res_desc->transport_id[len];
7869		}
7870		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7871		    res_status->header.length);
7872		break;
7873	}
7874	default:
7875		/*
7876		 * This is a bug, because we just checked for this above,
7877		 * and should have returned an error.
7878		 */
7879		panic("Invalid PR type %x", cdb->action);
7880		break; /* NOTREACHED */
7881	}
7882	mtx_unlock(&lun->lun_lock);
7883
7884	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7885	ctsio->be_move_done = ctl_config_move_done;
7886
7887	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7888			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7889			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7890			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7891			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7892
7893	ctl_datamove((union ctl_io *)ctsio);
7894
7895	return (CTL_RETVAL_COMPLETE);
7896}
7897
7898/*
7899 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7900 * it should return.
7901 */
7902static int
7903ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7904		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7905		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7906		struct scsi_per_res_out_parms* param)
7907{
7908	union ctl_ha_msg persis_io;
7909	int retval, i;
7910	int isc_retval;
7911
7912	retval = 0;
7913
7914	mtx_lock(&lun->lun_lock);
7915	if (sa_res_key == 0) {
7916		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7917			/* validate scope and type */
7918			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7919			     SPR_LU_SCOPE) {
7920				mtx_unlock(&lun->lun_lock);
7921				ctl_set_invalid_field(/*ctsio*/ ctsio,
7922						      /*sks_valid*/ 1,
7923						      /*command*/ 1,
7924						      /*field*/ 2,
7925						      /*bit_valid*/ 1,
7926						      /*bit*/ 4);
7927				ctl_done((union ctl_io *)ctsio);
7928				return (1);
7929			}
7930
7931		        if (type>8 || type==2 || type==4 || type==0) {
7932				mtx_unlock(&lun->lun_lock);
7933				ctl_set_invalid_field(/*ctsio*/ ctsio,
7934       	           				      /*sks_valid*/ 1,
7935						      /*command*/ 1,
7936						      /*field*/ 2,
7937						      /*bit_valid*/ 1,
7938						      /*bit*/ 0);
7939				ctl_done((union ctl_io *)ctsio);
7940				return (1);
7941		        }
7942
7943			/*
7944			 * Unregister everybody else and build UA for
7945			 * them
7946			 */
7947			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7948				if (i == residx || lun->pr_keys[i] == 0)
7949					continue;
7950
7951				if (!persis_offset
7952				 && i <CTL_MAX_INITIATORS)
7953					lun->pending_ua[i] |=
7954						CTL_UA_REG_PREEMPT;
7955				else if (persis_offset
7956				      && i >= persis_offset)
7957					lun->pending_ua[i-persis_offset] |=
7958						CTL_UA_REG_PREEMPT;
7959				lun->pr_keys[i] = 0;
7960			}
7961			lun->pr_key_count = 1;
7962			lun->res_type = type;
7963			if (lun->res_type != SPR_TYPE_WR_EX_AR
7964			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7965				lun->pr_res_idx = residx;
7966
7967			/* send msg to other side */
7968			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7969			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7970			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7971			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7972			persis_io.pr.pr_info.res_type = type;
7973			memcpy(persis_io.pr.pr_info.sa_res_key,
7974			       param->serv_act_res_key,
7975			       sizeof(param->serv_act_res_key));
7976			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7977			     &persis_io, sizeof(persis_io), 0)) >
7978			     CTL_HA_STATUS_SUCCESS) {
7979				printf("CTL:Persis Out error returned "
7980				       "from ctl_ha_msg_send %d\n",
7981				       isc_retval);
7982			}
7983		} else {
7984			/* not all registrants */
7985			mtx_unlock(&lun->lun_lock);
7986			free(ctsio->kern_data_ptr, M_CTL);
7987			ctl_set_invalid_field(ctsio,
7988					      /*sks_valid*/ 1,
7989					      /*command*/ 0,
7990					      /*field*/ 8,
7991					      /*bit_valid*/ 0,
7992					      /*bit*/ 0);
7993			ctl_done((union ctl_io *)ctsio);
7994			return (1);
7995		}
7996	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7997		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7998		int found = 0;
7999
8000		if (res_key == sa_res_key) {
8001			/* special case */
8002			/*
8003			 * The spec implies this is not good but doesn't
8004			 * say what to do. There are two choices either
8005			 * generate a res conflict or check condition
8006			 * with illegal field in parameter data. Since
8007			 * that is what is done when the sa_res_key is
8008			 * zero I'll take that approach since this has
8009			 * to do with the sa_res_key.
8010			 */
8011			mtx_unlock(&lun->lun_lock);
8012			free(ctsio->kern_data_ptr, M_CTL);
8013			ctl_set_invalid_field(ctsio,
8014					      /*sks_valid*/ 1,
8015					      /*command*/ 0,
8016					      /*field*/ 8,
8017					      /*bit_valid*/ 0,
8018					      /*bit*/ 0);
8019			ctl_done((union ctl_io *)ctsio);
8020			return (1);
8021		}
8022
8023		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8024			if (lun->pr_keys[i] != sa_res_key)
8025				continue;
8026
8027			found = 1;
8028			lun->pr_keys[i] = 0;
8029			lun->pr_key_count--;
8030
8031			if (!persis_offset && i < CTL_MAX_INITIATORS)
8032				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8033			else if (persis_offset && i >= persis_offset)
8034				lun->pending_ua[i-persis_offset] |=
8035					CTL_UA_REG_PREEMPT;
8036		}
8037		if (!found) {
8038			mtx_unlock(&lun->lun_lock);
8039			free(ctsio->kern_data_ptr, M_CTL);
8040			ctl_set_reservation_conflict(ctsio);
8041			ctl_done((union ctl_io *)ctsio);
8042			return (CTL_RETVAL_COMPLETE);
8043		}
8044		/* send msg to other side */
8045		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8046		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8047		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8048		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8049		persis_io.pr.pr_info.res_type = type;
8050		memcpy(persis_io.pr.pr_info.sa_res_key,
8051		       param->serv_act_res_key,
8052		       sizeof(param->serv_act_res_key));
8053		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8054		     &persis_io, sizeof(persis_io), 0)) >
8055		     CTL_HA_STATUS_SUCCESS) {
8056			printf("CTL:Persis Out error returned from "
8057			       "ctl_ha_msg_send %d\n", isc_retval);
8058		}
8059	} else {
8060		/* Reserved but not all registrants */
8061		/* sa_res_key is res holder */
8062		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8063			/* validate scope and type */
8064			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8065			     SPR_LU_SCOPE) {
8066				mtx_unlock(&lun->lun_lock);
8067				ctl_set_invalid_field(/*ctsio*/ ctsio,
8068						      /*sks_valid*/ 1,
8069						      /*command*/ 1,
8070						      /*field*/ 2,
8071						      /*bit_valid*/ 1,
8072						      /*bit*/ 4);
8073				ctl_done((union ctl_io *)ctsio);
8074				return (1);
8075			}
8076
8077			if (type>8 || type==2 || type==4 || type==0) {
8078				mtx_unlock(&lun->lun_lock);
8079				ctl_set_invalid_field(/*ctsio*/ ctsio,
8080						      /*sks_valid*/ 1,
8081						      /*command*/ 1,
8082						      /*field*/ 2,
8083						      /*bit_valid*/ 1,
8084						      /*bit*/ 0);
8085				ctl_done((union ctl_io *)ctsio);
8086				return (1);
8087			}
8088
8089			/*
8090			 * Do the following:
8091			 * if sa_res_key != res_key remove all
8092			 * registrants w/sa_res_key and generate UA
8093			 * for these registrants(Registrations
8094			 * Preempted) if it wasn't an exclusive
8095			 * reservation generate UA(Reservations
8096			 * Preempted) for all other registered nexuses
8097			 * if the type has changed. Establish the new
8098			 * reservation and holder. If res_key and
8099			 * sa_res_key are the same do the above
8100			 * except don't unregister the res holder.
8101			 */
8102
8103			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8104				if (i == residx || lun->pr_keys[i] == 0)
8105					continue;
8106
8107				if (sa_res_key == lun->pr_keys[i]) {
8108					lun->pr_keys[i] = 0;
8109					lun->pr_key_count--;
8110
8111					if (!persis_offset
8112					 && i < CTL_MAX_INITIATORS)
8113						lun->pending_ua[i] |=
8114							CTL_UA_REG_PREEMPT;
8115					else if (persis_offset
8116					      && i >= persis_offset)
8117						lun->pending_ua[i-persis_offset] |=
8118						  CTL_UA_REG_PREEMPT;
8119				} else if (type != lun->res_type
8120					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8121					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8122						if (!persis_offset
8123						 && i < CTL_MAX_INITIATORS)
8124							lun->pending_ua[i] |=
8125							CTL_UA_RES_RELEASE;
8126						else if (persis_offset
8127						      && i >= persis_offset)
8128							lun->pending_ua[
8129							i-persis_offset] |=
8130							CTL_UA_RES_RELEASE;
8131				}
8132			}
8133			lun->res_type = type;
8134			if (lun->res_type != SPR_TYPE_WR_EX_AR
8135			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8136				lun->pr_res_idx = residx;
8137			else
8138				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8139
8140			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8141			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8142			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8143			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8144			persis_io.pr.pr_info.res_type = type;
8145			memcpy(persis_io.pr.pr_info.sa_res_key,
8146			       param->serv_act_res_key,
8147			       sizeof(param->serv_act_res_key));
8148			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8149			     &persis_io, sizeof(persis_io), 0)) >
8150			     CTL_HA_STATUS_SUCCESS) {
8151				printf("CTL:Persis Out error returned "
8152				       "from ctl_ha_msg_send %d\n",
8153				       isc_retval);
8154			}
8155		} else {
8156			/*
8157			 * sa_res_key is not the res holder just
8158			 * remove registrants
8159			 */
8160			int found=0;
8161
8162			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8163				if (sa_res_key != lun->pr_keys[i])
8164					continue;
8165
8166				found = 1;
8167				lun->pr_keys[i] = 0;
8168				lun->pr_key_count--;
8169
8170				if (!persis_offset
8171				 && i < CTL_MAX_INITIATORS)
8172					lun->pending_ua[i] |=
8173						CTL_UA_REG_PREEMPT;
8174				else if (persis_offset
8175				      && i >= persis_offset)
8176					lun->pending_ua[i-persis_offset] |=
8177						CTL_UA_REG_PREEMPT;
8178			}
8179
8180			if (!found) {
8181				mtx_unlock(&lun->lun_lock);
8182				free(ctsio->kern_data_ptr, M_CTL);
8183				ctl_set_reservation_conflict(ctsio);
8184				ctl_done((union ctl_io *)ctsio);
8185		        	return (1);
8186			}
8187			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8188			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8189			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8190			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8191			persis_io.pr.pr_info.res_type = type;
8192			memcpy(persis_io.pr.pr_info.sa_res_key,
8193			       param->serv_act_res_key,
8194			       sizeof(param->serv_act_res_key));
8195			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8196			     &persis_io, sizeof(persis_io), 0)) >
8197			     CTL_HA_STATUS_SUCCESS) {
8198				printf("CTL:Persis Out error returned "
8199				       "from ctl_ha_msg_send %d\n",
8200				isc_retval);
8201			}
8202		}
8203	}
8204
8205	lun->PRGeneration++;
8206	mtx_unlock(&lun->lun_lock);
8207
8208	return (retval);
8209}
8210
8211static void
8212ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8213{
8214	uint64_t sa_res_key;
8215	int i;
8216
8217	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8218
8219	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8220	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8221	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8222		if (sa_res_key == 0) {
8223			/*
8224			 * Unregister everybody else and build UA for
8225			 * them
8226			 */
8227			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8228				if (i == msg->pr.pr_info.residx ||
8229				    lun->pr_keys[i] == 0)
8230					continue;
8231
8232				if (!persis_offset
8233				 && i < CTL_MAX_INITIATORS)
8234					lun->pending_ua[i] |=
8235						CTL_UA_REG_PREEMPT;
8236				else if (persis_offset && i >= persis_offset)
8237					lun->pending_ua[i - persis_offset] |=
8238						CTL_UA_REG_PREEMPT;
8239				lun->pr_keys[i] = 0;
8240			}
8241
8242			lun->pr_key_count = 1;
8243			lun->res_type = msg->pr.pr_info.res_type;
8244			if (lun->res_type != SPR_TYPE_WR_EX_AR
8245			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8246				lun->pr_res_idx = msg->pr.pr_info.residx;
8247		} else {
8248		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8249				if (sa_res_key == lun->pr_keys[i])
8250					continue;
8251
8252				lun->pr_keys[i] = 0;
8253				lun->pr_key_count--;
8254
8255				if (!persis_offset
8256				 && i < persis_offset)
8257					lun->pending_ua[i] |=
8258						CTL_UA_REG_PREEMPT;
8259				else if (persis_offset
8260				      && i >= persis_offset)
8261					lun->pending_ua[i - persis_offset] |=
8262						CTL_UA_REG_PREEMPT;
8263			}
8264		}
8265	} else {
8266		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8267			if (i == msg->pr.pr_info.residx ||
8268			    lun->pr_keys[i] == 0)
8269				continue;
8270
8271			if (sa_res_key == lun->pr_keys[i]) {
8272				lun->pr_keys[i] = 0;
8273				lun->pr_key_count--;
8274				if (!persis_offset
8275				 && i < CTL_MAX_INITIATORS)
8276					lun->pending_ua[i] |=
8277						CTL_UA_REG_PREEMPT;
8278				else if (persis_offset
8279				      && i >= persis_offset)
8280					lun->pending_ua[i - persis_offset] |=
8281						CTL_UA_REG_PREEMPT;
8282			} else if (msg->pr.pr_info.res_type != lun->res_type
8283				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8284				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8285					if (!persis_offset
8286					 && i < persis_offset)
8287						lun->pending_ua[i] |=
8288							CTL_UA_RES_RELEASE;
8289					else if (persis_offset
8290					      && i >= persis_offset)
8291					lun->pending_ua[i - persis_offset] |=
8292						CTL_UA_RES_RELEASE;
8293			}
8294		}
8295		lun->res_type = msg->pr.pr_info.res_type;
8296		if (lun->res_type != SPR_TYPE_WR_EX_AR
8297		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8298			lun->pr_res_idx = msg->pr.pr_info.residx;
8299		else
8300			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8301	}
8302	lun->PRGeneration++;
8303
8304}
8305
8306
8307int
8308ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8309{
8310	int retval;
8311	int isc_retval;
8312	u_int32_t param_len;
8313	struct scsi_per_res_out *cdb;
8314	struct ctl_lun *lun;
8315	struct scsi_per_res_out_parms* param;
8316	struct ctl_softc *softc;
8317	uint32_t residx;
8318	uint64_t res_key, sa_res_key;
8319	uint8_t type;
8320	union ctl_ha_msg persis_io;
8321	int    i;
8322
8323	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8324
8325	retval = CTL_RETVAL_COMPLETE;
8326
8327	softc = control_softc;
8328
8329	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8330	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8331
8332	/*
8333	 * We only support whole-LUN scope.  The scope & type are ignored for
8334	 * register, register and ignore existing key and clear.
8335	 * We sometimes ignore scope and type on preempts too!!
8336	 * Verify reservation type here as well.
8337	 */
8338	type = cdb->scope_type & SPR_TYPE_MASK;
8339	if ((cdb->action == SPRO_RESERVE)
8340	 || (cdb->action == SPRO_RELEASE)) {
8341		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8342			ctl_set_invalid_field(/*ctsio*/ ctsio,
8343					      /*sks_valid*/ 1,
8344					      /*command*/ 1,
8345					      /*field*/ 2,
8346					      /*bit_valid*/ 1,
8347					      /*bit*/ 4);
8348			ctl_done((union ctl_io *)ctsio);
8349			return (CTL_RETVAL_COMPLETE);
8350		}
8351
8352		if (type>8 || type==2 || type==4 || type==0) {
8353			ctl_set_invalid_field(/*ctsio*/ ctsio,
8354					      /*sks_valid*/ 1,
8355					      /*command*/ 1,
8356					      /*field*/ 2,
8357					      /*bit_valid*/ 1,
8358					      /*bit*/ 0);
8359			ctl_done((union ctl_io *)ctsio);
8360			return (CTL_RETVAL_COMPLETE);
8361		}
8362	}
8363
8364	param_len = scsi_4btoul(cdb->length);
8365
8366	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8367		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8368		ctsio->kern_data_len = param_len;
8369		ctsio->kern_total_len = param_len;
8370		ctsio->kern_data_resid = 0;
8371		ctsio->kern_rel_offset = 0;
8372		ctsio->kern_sg_entries = 0;
8373		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8374		ctsio->be_move_done = ctl_config_move_done;
8375		ctl_datamove((union ctl_io *)ctsio);
8376
8377		return (CTL_RETVAL_COMPLETE);
8378	}
8379
8380	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8381
8382	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8383	res_key = scsi_8btou64(param->res_key.key);
8384	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8385
8386	/*
8387	 * Validate the reservation key here except for SPRO_REG_IGNO
8388	 * This must be done for all other service actions
8389	 */
8390	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8391		mtx_lock(&lun->lun_lock);
8392		if (lun->pr_keys[residx] != 0) {
8393		    if (res_key != lun->pr_keys[residx]) {
8394				/*
8395				 * The current key passed in doesn't match
8396				 * the one the initiator previously
8397				 * registered.
8398				 */
8399				mtx_unlock(&lun->lun_lock);
8400				free(ctsio->kern_data_ptr, M_CTL);
8401				ctl_set_reservation_conflict(ctsio);
8402				ctl_done((union ctl_io *)ctsio);
8403				return (CTL_RETVAL_COMPLETE);
8404			}
8405		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8406			/*
8407			 * We are not registered
8408			 */
8409			mtx_unlock(&lun->lun_lock);
8410			free(ctsio->kern_data_ptr, M_CTL);
8411			ctl_set_reservation_conflict(ctsio);
8412			ctl_done((union ctl_io *)ctsio);
8413			return (CTL_RETVAL_COMPLETE);
8414		} else if (res_key != 0) {
8415			/*
8416			 * We are not registered and trying to register but
8417			 * the register key isn't zero.
8418			 */
8419			mtx_unlock(&lun->lun_lock);
8420			free(ctsio->kern_data_ptr, M_CTL);
8421			ctl_set_reservation_conflict(ctsio);
8422			ctl_done((union ctl_io *)ctsio);
8423			return (CTL_RETVAL_COMPLETE);
8424		}
8425		mtx_unlock(&lun->lun_lock);
8426	}
8427
8428	switch (cdb->action & SPRO_ACTION_MASK) {
8429	case SPRO_REGISTER:
8430	case SPRO_REG_IGNO: {
8431
8432#if 0
8433		printf("Registration received\n");
8434#endif
8435
8436		/*
8437		 * We don't support any of these options, as we report in
8438		 * the read capabilities request (see
8439		 * ctl_persistent_reserve_in(), above).
8440		 */
8441		if ((param->flags & SPR_SPEC_I_PT)
8442		 || (param->flags & SPR_ALL_TG_PT)
8443		 || (param->flags & SPR_APTPL)) {
8444			int bit_ptr;
8445
8446			if (param->flags & SPR_APTPL)
8447				bit_ptr = 0;
8448			else if (param->flags & SPR_ALL_TG_PT)
8449				bit_ptr = 2;
8450			else /* SPR_SPEC_I_PT */
8451				bit_ptr = 3;
8452
8453			free(ctsio->kern_data_ptr, M_CTL);
8454			ctl_set_invalid_field(ctsio,
8455					      /*sks_valid*/ 1,
8456					      /*command*/ 0,
8457					      /*field*/ 20,
8458					      /*bit_valid*/ 1,
8459					      /*bit*/ bit_ptr);
8460			ctl_done((union ctl_io *)ctsio);
8461			return (CTL_RETVAL_COMPLETE);
8462		}
8463
8464		mtx_lock(&lun->lun_lock);
8465
8466		/*
8467		 * The initiator wants to clear the
8468		 * key/unregister.
8469		 */
8470		if (sa_res_key == 0) {
8471			if ((res_key == 0
8472			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8473			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8474			  && lun->pr_keys[residx] == 0)) {
8475				mtx_unlock(&lun->lun_lock);
8476				goto done;
8477			}
8478
8479			lun->pr_keys[residx] = 0;
8480			lun->pr_key_count--;
8481
8482			if (residx == lun->pr_res_idx) {
8483				lun->flags &= ~CTL_LUN_PR_RESERVED;
8484				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8485
8486				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8487				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8488				 && lun->pr_key_count) {
8489					/*
8490					 * If the reservation is a registrants
8491					 * only type we need to generate a UA
8492					 * for other registered inits.  The
8493					 * sense code should be RESERVATIONS
8494					 * RELEASED
8495					 */
8496
8497					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8498						if (lun->pr_keys[
8499						    i + persis_offset] == 0)
8500							continue;
8501						lun->pending_ua[i] |=
8502							CTL_UA_RES_RELEASE;
8503					}
8504				}
8505				lun->res_type = 0;
8506			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8507				if (lun->pr_key_count==0) {
8508					lun->flags &= ~CTL_LUN_PR_RESERVED;
8509					lun->res_type = 0;
8510					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8511				}
8512			}
8513			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8514			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8515			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8516			persis_io.pr.pr_info.residx = residx;
8517			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8518			     &persis_io, sizeof(persis_io), 0 )) >
8519			     CTL_HA_STATUS_SUCCESS) {
8520				printf("CTL:Persis Out error returned from "
8521				       "ctl_ha_msg_send %d\n", isc_retval);
8522			}
8523		} else /* sa_res_key != 0 */ {
8524
8525			/*
8526			 * If we aren't registered currently then increment
8527			 * the key count and set the registered flag.
8528			 */
8529			if (lun->pr_keys[residx] == 0)
8530				lun->pr_key_count++;
8531			lun->pr_keys[residx] = sa_res_key;
8532
8533			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8534			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8535			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8536			persis_io.pr.pr_info.residx = residx;
8537			memcpy(persis_io.pr.pr_info.sa_res_key,
8538			       param->serv_act_res_key,
8539			       sizeof(param->serv_act_res_key));
8540			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8541			     &persis_io, sizeof(persis_io), 0)) >
8542			     CTL_HA_STATUS_SUCCESS) {
8543				printf("CTL:Persis Out error returned from "
8544				       "ctl_ha_msg_send %d\n", isc_retval);
8545			}
8546		}
8547		lun->PRGeneration++;
8548		mtx_unlock(&lun->lun_lock);
8549
8550		break;
8551	}
8552	case SPRO_RESERVE:
8553#if 0
8554                printf("Reserve executed type %d\n", type);
8555#endif
8556		mtx_lock(&lun->lun_lock);
8557		if (lun->flags & CTL_LUN_PR_RESERVED) {
8558			/*
8559			 * if this isn't the reservation holder and it's
8560			 * not a "all registrants" type or if the type is
8561			 * different then we have a conflict
8562			 */
8563			if ((lun->pr_res_idx != residx
8564			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8565			 || lun->res_type != type) {
8566				mtx_unlock(&lun->lun_lock);
8567				free(ctsio->kern_data_ptr, M_CTL);
8568				ctl_set_reservation_conflict(ctsio);
8569				ctl_done((union ctl_io *)ctsio);
8570				return (CTL_RETVAL_COMPLETE);
8571			}
8572			mtx_unlock(&lun->lun_lock);
8573		} else /* create a reservation */ {
8574			/*
8575			 * If it's not an "all registrants" type record
8576			 * reservation holder
8577			 */
8578			if (type != SPR_TYPE_WR_EX_AR
8579			 && type != SPR_TYPE_EX_AC_AR)
8580				lun->pr_res_idx = residx; /* Res holder */
8581			else
8582				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8583
8584			lun->flags |= CTL_LUN_PR_RESERVED;
8585			lun->res_type = type;
8586
8587			mtx_unlock(&lun->lun_lock);
8588
8589			/* send msg to other side */
8590			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8591			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8592			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8593			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8594			persis_io.pr.pr_info.res_type = type;
8595			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8596			     &persis_io, sizeof(persis_io), 0)) >
8597			     CTL_HA_STATUS_SUCCESS) {
8598				printf("CTL:Persis Out error returned from "
8599				       "ctl_ha_msg_send %d\n", isc_retval);
8600			}
8601		}
8602		break;
8603
8604	case SPRO_RELEASE:
8605		mtx_lock(&lun->lun_lock);
8606		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8607			/* No reservation exists return good status */
8608			mtx_unlock(&lun->lun_lock);
8609			goto done;
8610		}
8611		/*
8612		 * Is this nexus a reservation holder?
8613		 */
8614		if (lun->pr_res_idx != residx
8615		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8616			/*
8617			 * not a res holder return good status but
8618			 * do nothing
8619			 */
8620			mtx_unlock(&lun->lun_lock);
8621			goto done;
8622		}
8623
8624		if (lun->res_type != type) {
8625			mtx_unlock(&lun->lun_lock);
8626			free(ctsio->kern_data_ptr, M_CTL);
8627			ctl_set_illegal_pr_release(ctsio);
8628			ctl_done((union ctl_io *)ctsio);
8629			return (CTL_RETVAL_COMPLETE);
8630		}
8631
8632		/* okay to release */
8633		lun->flags &= ~CTL_LUN_PR_RESERVED;
8634		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8635		lun->res_type = 0;
8636
8637		/*
8638		 * if this isn't an exclusive access
8639		 * res generate UA for all other
8640		 * registrants.
8641		 */
8642		if (type != SPR_TYPE_EX_AC
8643		 && type != SPR_TYPE_WR_EX) {
8644			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8645				if (i == residx ||
8646				    lun->pr_keys[i + persis_offset] == 0)
8647					continue;
8648				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8649			}
8650		}
8651		mtx_unlock(&lun->lun_lock);
8652		/* Send msg to other side */
8653		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8654		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8655		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8656		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8657		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8658			printf("CTL:Persis Out error returned from "
8659			       "ctl_ha_msg_send %d\n", isc_retval);
8660		}
8661		break;
8662
8663	case SPRO_CLEAR:
8664		/* send msg to other side */
8665
8666		mtx_lock(&lun->lun_lock);
8667		lun->flags &= ~CTL_LUN_PR_RESERVED;
8668		lun->res_type = 0;
8669		lun->pr_key_count = 0;
8670		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8671
8672		lun->pr_keys[residx] = 0;
8673
8674		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8675			if (lun->pr_keys[i] != 0) {
8676				if (!persis_offset && i < CTL_MAX_INITIATORS)
8677					lun->pending_ua[i] |=
8678						CTL_UA_RES_PREEMPT;
8679				else if (persis_offset && i >= persis_offset)
8680					lun->pending_ua[i-persis_offset] |=
8681					    CTL_UA_RES_PREEMPT;
8682
8683				lun->pr_keys[i] = 0;
8684			}
8685		lun->PRGeneration++;
8686		mtx_unlock(&lun->lun_lock);
8687		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8688		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8689		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8690		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8691		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8692			printf("CTL:Persis Out error returned from "
8693			       "ctl_ha_msg_send %d\n", isc_retval);
8694		}
8695		break;
8696
8697	case SPRO_PREEMPT: {
8698		int nretval;
8699
8700		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8701					  residx, ctsio, cdb, param);
8702		if (nretval != 0)
8703			return (CTL_RETVAL_COMPLETE);
8704		break;
8705	}
8706	default:
8707		panic("Invalid PR type %x", cdb->action);
8708	}
8709
8710done:
8711	free(ctsio->kern_data_ptr, M_CTL);
8712	ctl_set_success(ctsio);
8713	ctl_done((union ctl_io *)ctsio);
8714
8715	return (retval);
8716}
8717
8718/*
8719 * This routine is for handling a message from the other SC pertaining to
8720 * persistent reserve out. All the error checking will have been done
8721 * so only perorming the action need be done here to keep the two
8722 * in sync.
8723 */
8724static void
8725ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8726{
8727	struct ctl_lun *lun;
8728	struct ctl_softc *softc;
8729	int i;
8730	uint32_t targ_lun;
8731
8732	softc = control_softc;
8733
8734	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8735	lun = softc->ctl_luns[targ_lun];
8736	mtx_lock(&lun->lun_lock);
8737	switch(msg->pr.pr_info.action) {
8738	case CTL_PR_REG_KEY:
8739		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8740			lun->pr_key_count++;
8741		lun->pr_keys[msg->pr.pr_info.residx] =
8742		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8743		lun->PRGeneration++;
8744		break;
8745
8746	case CTL_PR_UNREG_KEY:
8747		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8748		lun->pr_key_count--;
8749
8750		/* XXX Need to see if the reservation has been released */
8751		/* if so do we need to generate UA? */
8752		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8753			lun->flags &= ~CTL_LUN_PR_RESERVED;
8754			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8755
8756			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8757			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8758			 && lun->pr_key_count) {
8759				/*
8760				 * If the reservation is a registrants
8761				 * only type we need to generate a UA
8762				 * for other registered inits.  The
8763				 * sense code should be RESERVATIONS
8764				 * RELEASED
8765				 */
8766
8767				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8768					if (lun->pr_keys[i+
8769					    persis_offset] == 0)
8770						continue;
8771
8772					lun->pending_ua[i] |=
8773						CTL_UA_RES_RELEASE;
8774				}
8775			}
8776			lun->res_type = 0;
8777		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8778			if (lun->pr_key_count==0) {
8779				lun->flags &= ~CTL_LUN_PR_RESERVED;
8780				lun->res_type = 0;
8781				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8782			}
8783		}
8784		lun->PRGeneration++;
8785		break;
8786
8787	case CTL_PR_RESERVE:
8788		lun->flags |= CTL_LUN_PR_RESERVED;
8789		lun->res_type = msg->pr.pr_info.res_type;
8790		lun->pr_res_idx = msg->pr.pr_info.residx;
8791
8792		break;
8793
8794	case CTL_PR_RELEASE:
8795		/*
8796		 * if this isn't an exclusive access res generate UA for all
8797		 * other registrants.
8798		 */
8799		if (lun->res_type != SPR_TYPE_EX_AC
8800		 && lun->res_type != SPR_TYPE_WR_EX) {
8801			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8802				if (lun->pr_keys[i+persis_offset] != 0)
8803					lun->pending_ua[i] |=
8804						CTL_UA_RES_RELEASE;
8805		}
8806
8807		lun->flags &= ~CTL_LUN_PR_RESERVED;
8808		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8809		lun->res_type = 0;
8810		break;
8811
8812	case CTL_PR_PREEMPT:
8813		ctl_pro_preempt_other(lun, msg);
8814		break;
8815	case CTL_PR_CLEAR:
8816		lun->flags &= ~CTL_LUN_PR_RESERVED;
8817		lun->res_type = 0;
8818		lun->pr_key_count = 0;
8819		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8820
8821		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8822			if (lun->pr_keys[i] == 0)
8823				continue;
8824			if (!persis_offset
8825			 && i < CTL_MAX_INITIATORS)
8826				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8827			else if (persis_offset
8828			      && i >= persis_offset)
8829				lun->pending_ua[i-persis_offset] |=
8830					CTL_UA_RES_PREEMPT;
8831			lun->pr_keys[i] = 0;
8832		}
8833		lun->PRGeneration++;
8834		break;
8835	}
8836
8837	mtx_unlock(&lun->lun_lock);
8838}
8839
8840int
8841ctl_read_write(struct ctl_scsiio *ctsio)
8842{
8843	struct ctl_lun *lun;
8844	struct ctl_lba_len_flags *lbalen;
8845	uint64_t lba;
8846	uint32_t num_blocks;
8847	int flags, retval;
8848	int isread;
8849
8850	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8851
8852	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8853
8854	flags = 0;
8855	retval = CTL_RETVAL_COMPLETE;
8856
8857	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8858	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8859	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8860		uint32_t residx;
8861
8862		/*
8863		 * XXX KDM need a lock here.
8864		 */
8865		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8866		if ((lun->res_type == SPR_TYPE_EX_AC
8867		  && residx != lun->pr_res_idx)
8868		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8869		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8870		  && lun->pr_keys[residx] == 0)) {
8871			ctl_set_reservation_conflict(ctsio);
8872			ctl_done((union ctl_io *)ctsio);
8873			return (CTL_RETVAL_COMPLETE);
8874	        }
8875	}
8876
8877	switch (ctsio->cdb[0]) {
8878	case READ_6:
8879	case WRITE_6: {
8880		struct scsi_rw_6 *cdb;
8881
8882		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8883
8884		lba = scsi_3btoul(cdb->addr);
8885		/* only 5 bits are valid in the most significant address byte */
8886		lba &= 0x1fffff;
8887		num_blocks = cdb->length;
8888		/*
8889		 * This is correct according to SBC-2.
8890		 */
8891		if (num_blocks == 0)
8892			num_blocks = 256;
8893		break;
8894	}
8895	case READ_10:
8896	case WRITE_10: {
8897		struct scsi_rw_10 *cdb;
8898
8899		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8900		if (cdb->byte2 & SRW10_FUA)
8901			flags |= CTL_LLF_FUA;
8902		if (cdb->byte2 & SRW10_DPO)
8903			flags |= CTL_LLF_DPO;
8904		lba = scsi_4btoul(cdb->addr);
8905		num_blocks = scsi_2btoul(cdb->length);
8906		break;
8907	}
8908	case WRITE_VERIFY_10: {
8909		struct scsi_write_verify_10 *cdb;
8910
8911		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8912		flags |= CTL_LLF_FUA;
8913		if (cdb->byte2 & SWV_DPO)
8914			flags |= CTL_LLF_DPO;
8915		lba = scsi_4btoul(cdb->addr);
8916		num_blocks = scsi_2btoul(cdb->length);
8917		break;
8918	}
8919	case READ_12:
8920	case WRITE_12: {
8921		struct scsi_rw_12 *cdb;
8922
8923		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8924		if (cdb->byte2 & SRW12_FUA)
8925			flags |= CTL_LLF_FUA;
8926		if (cdb->byte2 & SRW12_DPO)
8927			flags |= CTL_LLF_DPO;
8928		lba = scsi_4btoul(cdb->addr);
8929		num_blocks = scsi_4btoul(cdb->length);
8930		break;
8931	}
8932	case WRITE_VERIFY_12: {
8933		struct scsi_write_verify_12 *cdb;
8934
8935		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8936		flags |= CTL_LLF_FUA;
8937		if (cdb->byte2 & SWV_DPO)
8938			flags |= CTL_LLF_DPO;
8939		lba = scsi_4btoul(cdb->addr);
8940		num_blocks = scsi_4btoul(cdb->length);
8941		break;
8942	}
8943	case READ_16:
8944	case WRITE_16: {
8945		struct scsi_rw_16 *cdb;
8946
8947		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8948		if (cdb->byte2 & SRW12_FUA)
8949			flags |= CTL_LLF_FUA;
8950		if (cdb->byte2 & SRW12_DPO)
8951			flags |= CTL_LLF_DPO;
8952		lba = scsi_8btou64(cdb->addr);
8953		num_blocks = scsi_4btoul(cdb->length);
8954		break;
8955	}
8956	case WRITE_ATOMIC_16: {
8957		struct scsi_rw_16 *cdb;
8958
8959		if (lun->be_lun->atomicblock == 0) {
8960			ctl_set_invalid_opcode(ctsio);
8961			ctl_done((union ctl_io *)ctsio);
8962			return (CTL_RETVAL_COMPLETE);
8963		}
8964
8965		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8966		if (cdb->byte2 & SRW12_FUA)
8967			flags |= CTL_LLF_FUA;
8968		if (cdb->byte2 & SRW12_DPO)
8969			flags |= CTL_LLF_DPO;
8970		lba = scsi_8btou64(cdb->addr);
8971		num_blocks = scsi_4btoul(cdb->length);
8972		if (num_blocks > lun->be_lun->atomicblock) {
8973			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8974			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8975			    /*bit*/ 0);
8976			ctl_done((union ctl_io *)ctsio);
8977			return (CTL_RETVAL_COMPLETE);
8978		}
8979		break;
8980	}
8981	case WRITE_VERIFY_16: {
8982		struct scsi_write_verify_16 *cdb;
8983
8984		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8985		flags |= CTL_LLF_FUA;
8986		if (cdb->byte2 & SWV_DPO)
8987			flags |= CTL_LLF_DPO;
8988		lba = scsi_8btou64(cdb->addr);
8989		num_blocks = scsi_4btoul(cdb->length);
8990		break;
8991	}
8992	default:
8993		/*
8994		 * We got a command we don't support.  This shouldn't
8995		 * happen, commands should be filtered out above us.
8996		 */
8997		ctl_set_invalid_opcode(ctsio);
8998		ctl_done((union ctl_io *)ctsio);
8999
9000		return (CTL_RETVAL_COMPLETE);
9001		break; /* NOTREACHED */
9002	}
9003
9004	/*
9005	 * The first check is to make sure we're in bounds, the second
9006	 * check is to catch wrap-around problems.  If the lba + num blocks
9007	 * is less than the lba, then we've wrapped around and the block
9008	 * range is invalid anyway.
9009	 */
9010	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9011	 || ((lba + num_blocks) < lba)) {
9012		ctl_set_lba_out_of_range(ctsio);
9013		ctl_done((union ctl_io *)ctsio);
9014		return (CTL_RETVAL_COMPLETE);
9015	}
9016
9017	/*
9018	 * According to SBC-3, a transfer length of 0 is not an error.
9019	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9020	 * translates to 256 blocks for those commands.
9021	 */
9022	if (num_blocks == 0) {
9023		ctl_set_success(ctsio);
9024		ctl_done((union ctl_io *)ctsio);
9025		return (CTL_RETVAL_COMPLETE);
9026	}
9027
9028	/* Set FUA and/or DPO if caches are disabled. */
9029	if (isread) {
9030		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9031		    SCP_RCD) != 0)
9032			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9033	} else {
9034		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9035		    SCP_WCE) == 0)
9036			flags |= CTL_LLF_FUA;
9037	}
9038
9039	lbalen = (struct ctl_lba_len_flags *)
9040	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9041	lbalen->lba = lba;
9042	lbalen->len = num_blocks;
9043	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9044
9045	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9046	ctsio->kern_rel_offset = 0;
9047
9048	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9049
9050	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9051
9052	return (retval);
9053}
9054
9055static int
9056ctl_cnw_cont(union ctl_io *io)
9057{
9058	struct ctl_scsiio *ctsio;
9059	struct ctl_lun *lun;
9060	struct ctl_lba_len_flags *lbalen;
9061	int retval;
9062
9063	ctsio = &io->scsiio;
9064	ctsio->io_hdr.status = CTL_STATUS_NONE;
9065	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9066	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9067	lbalen = (struct ctl_lba_len_flags *)
9068	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9069	lbalen->flags &= ~CTL_LLF_COMPARE;
9070	lbalen->flags |= CTL_LLF_WRITE;
9071
9072	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9073	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9074	return (retval);
9075}
9076
9077int
9078ctl_cnw(struct ctl_scsiio *ctsio)
9079{
9080	struct ctl_lun *lun;
9081	struct ctl_lba_len_flags *lbalen;
9082	uint64_t lba;
9083	uint32_t num_blocks;
9084	int flags, retval;
9085
9086	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9087
9088	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9089
9090	flags = 0;
9091	retval = CTL_RETVAL_COMPLETE;
9092
9093	switch (ctsio->cdb[0]) {
9094	case COMPARE_AND_WRITE: {
9095		struct scsi_compare_and_write *cdb;
9096
9097		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9098		if (cdb->byte2 & SRW10_FUA)
9099			flags |= CTL_LLF_FUA;
9100		if (cdb->byte2 & SRW10_DPO)
9101			flags |= CTL_LLF_DPO;
9102		lba = scsi_8btou64(cdb->addr);
9103		num_blocks = cdb->length;
9104		break;
9105	}
9106	default:
9107		/*
9108		 * We got a command we don't support.  This shouldn't
9109		 * happen, commands should be filtered out above us.
9110		 */
9111		ctl_set_invalid_opcode(ctsio);
9112		ctl_done((union ctl_io *)ctsio);
9113
9114		return (CTL_RETVAL_COMPLETE);
9115		break; /* NOTREACHED */
9116	}
9117
9118	/*
9119	 * The first check is to make sure we're in bounds, the second
9120	 * check is to catch wrap-around problems.  If the lba + num blocks
9121	 * is less than the lba, then we've wrapped around and the block
9122	 * range is invalid anyway.
9123	 */
9124	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9125	 || ((lba + num_blocks) < lba)) {
9126		ctl_set_lba_out_of_range(ctsio);
9127		ctl_done((union ctl_io *)ctsio);
9128		return (CTL_RETVAL_COMPLETE);
9129	}
9130
9131	/*
9132	 * According to SBC-3, a transfer length of 0 is not an error.
9133	 */
9134	if (num_blocks == 0) {
9135		ctl_set_success(ctsio);
9136		ctl_done((union ctl_io *)ctsio);
9137		return (CTL_RETVAL_COMPLETE);
9138	}
9139
9140	/* Set FUA if write cache is disabled. */
9141	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9142	    SCP_WCE) == 0)
9143		flags |= CTL_LLF_FUA;
9144
9145	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9146	ctsio->kern_rel_offset = 0;
9147
9148	/*
9149	 * Set the IO_CONT flag, so that if this I/O gets passed to
9150	 * ctl_data_submit_done(), it'll get passed back to
9151	 * ctl_ctl_cnw_cont() for further processing.
9152	 */
9153	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9154	ctsio->io_cont = ctl_cnw_cont;
9155
9156	lbalen = (struct ctl_lba_len_flags *)
9157	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9158	lbalen->lba = lba;
9159	lbalen->len = num_blocks;
9160	lbalen->flags = CTL_LLF_COMPARE | flags;
9161
9162	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9163	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9164	return (retval);
9165}
9166
9167int
9168ctl_verify(struct ctl_scsiio *ctsio)
9169{
9170	struct ctl_lun *lun;
9171	struct ctl_lba_len_flags *lbalen;
9172	uint64_t lba;
9173	uint32_t num_blocks;
9174	int bytchk, flags;
9175	int retval;
9176
9177	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9178
9179	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9180
9181	bytchk = 0;
9182	flags = CTL_LLF_FUA;
9183	retval = CTL_RETVAL_COMPLETE;
9184
9185	switch (ctsio->cdb[0]) {
9186	case VERIFY_10: {
9187		struct scsi_verify_10 *cdb;
9188
9189		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9190		if (cdb->byte2 & SVFY_BYTCHK)
9191			bytchk = 1;
9192		if (cdb->byte2 & SVFY_DPO)
9193			flags |= CTL_LLF_DPO;
9194		lba = scsi_4btoul(cdb->addr);
9195		num_blocks = scsi_2btoul(cdb->length);
9196		break;
9197	}
9198	case VERIFY_12: {
9199		struct scsi_verify_12 *cdb;
9200
9201		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9202		if (cdb->byte2 & SVFY_BYTCHK)
9203			bytchk = 1;
9204		if (cdb->byte2 & SVFY_DPO)
9205			flags |= CTL_LLF_DPO;
9206		lba = scsi_4btoul(cdb->addr);
9207		num_blocks = scsi_4btoul(cdb->length);
9208		break;
9209	}
9210	case VERIFY_16: {
9211		struct scsi_rw_16 *cdb;
9212
9213		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9214		if (cdb->byte2 & SVFY_BYTCHK)
9215			bytchk = 1;
9216		if (cdb->byte2 & SVFY_DPO)
9217			flags |= CTL_LLF_DPO;
9218		lba = scsi_8btou64(cdb->addr);
9219		num_blocks = scsi_4btoul(cdb->length);
9220		break;
9221	}
9222	default:
9223		/*
9224		 * We got a command we don't support.  This shouldn't
9225		 * happen, commands should be filtered out above us.
9226		 */
9227		ctl_set_invalid_opcode(ctsio);
9228		ctl_done((union ctl_io *)ctsio);
9229		return (CTL_RETVAL_COMPLETE);
9230	}
9231
9232	/*
9233	 * The first check is to make sure we're in bounds, the second
9234	 * check is to catch wrap-around problems.  If the lba + num blocks
9235	 * is less than the lba, then we've wrapped around and the block
9236	 * range is invalid anyway.
9237	 */
9238	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9239	 || ((lba + num_blocks) < lba)) {
9240		ctl_set_lba_out_of_range(ctsio);
9241		ctl_done((union ctl_io *)ctsio);
9242		return (CTL_RETVAL_COMPLETE);
9243	}
9244
9245	/*
9246	 * According to SBC-3, a transfer length of 0 is not an error.
9247	 */
9248	if (num_blocks == 0) {
9249		ctl_set_success(ctsio);
9250		ctl_done((union ctl_io *)ctsio);
9251		return (CTL_RETVAL_COMPLETE);
9252	}
9253
9254	lbalen = (struct ctl_lba_len_flags *)
9255	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9256	lbalen->lba = lba;
9257	lbalen->len = num_blocks;
9258	if (bytchk) {
9259		lbalen->flags = CTL_LLF_COMPARE | flags;
9260		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9261	} else {
9262		lbalen->flags = CTL_LLF_VERIFY | flags;
9263		ctsio->kern_total_len = 0;
9264	}
9265	ctsio->kern_rel_offset = 0;
9266
9267	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9268	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9269	return (retval);
9270}
9271
9272int
9273ctl_report_luns(struct ctl_scsiio *ctsio)
9274{
9275	struct scsi_report_luns *cdb;
9276	struct scsi_report_luns_data *lun_data;
9277	struct ctl_lun *lun, *request_lun;
9278	int num_luns, retval;
9279	uint32_t alloc_len, lun_datalen;
9280	int num_filled, well_known;
9281	uint32_t initidx, targ_lun_id, lun_id;
9282
9283	retval = CTL_RETVAL_COMPLETE;
9284	well_known = 0;
9285
9286	cdb = (struct scsi_report_luns *)ctsio->cdb;
9287
9288	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9289
9290	mtx_lock(&control_softc->ctl_lock);
9291	num_luns = control_softc->num_luns;
9292	mtx_unlock(&control_softc->ctl_lock);
9293
9294	switch (cdb->select_report) {
9295	case RPL_REPORT_DEFAULT:
9296	case RPL_REPORT_ALL:
9297		break;
9298	case RPL_REPORT_WELLKNOWN:
9299		well_known = 1;
9300		num_luns = 0;
9301		break;
9302	default:
9303		ctl_set_invalid_field(ctsio,
9304				      /*sks_valid*/ 1,
9305				      /*command*/ 1,
9306				      /*field*/ 2,
9307				      /*bit_valid*/ 0,
9308				      /*bit*/ 0);
9309		ctl_done((union ctl_io *)ctsio);
9310		return (retval);
9311		break; /* NOTREACHED */
9312	}
9313
9314	alloc_len = scsi_4btoul(cdb->length);
9315	/*
9316	 * The initiator has to allocate at least 16 bytes for this request,
9317	 * so he can at least get the header and the first LUN.  Otherwise
9318	 * we reject the request (per SPC-3 rev 14, section 6.21).
9319	 */
9320	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9321	    sizeof(struct scsi_report_luns_lundata))) {
9322		ctl_set_invalid_field(ctsio,
9323				      /*sks_valid*/ 1,
9324				      /*command*/ 1,
9325				      /*field*/ 6,
9326				      /*bit_valid*/ 0,
9327				      /*bit*/ 0);
9328		ctl_done((union ctl_io *)ctsio);
9329		return (retval);
9330	}
9331
9332	request_lun = (struct ctl_lun *)
9333		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9334
9335	lun_datalen = sizeof(*lun_data) +
9336		(num_luns * sizeof(struct scsi_report_luns_lundata));
9337
9338	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9339	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9340	ctsio->kern_sg_entries = 0;
9341
9342	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9343
9344	mtx_lock(&control_softc->ctl_lock);
9345	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9346		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9347		if (lun_id >= CTL_MAX_LUNS)
9348			continue;
9349		lun = control_softc->ctl_luns[lun_id];
9350		if (lun == NULL)
9351			continue;
9352
9353		if (targ_lun_id <= 0xff) {
9354			/*
9355			 * Peripheral addressing method, bus number 0.
9356			 */
9357			lun_data->luns[num_filled].lundata[0] =
9358				RPL_LUNDATA_ATYP_PERIPH;
9359			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9360			num_filled++;
9361		} else if (targ_lun_id <= 0x3fff) {
9362			/*
9363			 * Flat addressing method.
9364			 */
9365			lun_data->luns[num_filled].lundata[0] =
9366				RPL_LUNDATA_ATYP_FLAT |
9367				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9368#ifdef OLDCTLHEADERS
9369				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9370				(targ_lun_id & SRLD_BUS_LUN_MASK);
9371#endif
9372			lun_data->luns[num_filled].lundata[1] =
9373#ifdef OLDCTLHEADERS
9374				targ_lun_id >> SRLD_BUS_LUN_BITS;
9375#endif
9376				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9377			num_filled++;
9378		} else {
9379			printf("ctl_report_luns: bogus LUN number %jd, "
9380			       "skipping\n", (intmax_t)targ_lun_id);
9381		}
9382		/*
9383		 * According to SPC-3, rev 14 section 6.21:
9384		 *
9385		 * "The execution of a REPORT LUNS command to any valid and
9386		 * installed logical unit shall clear the REPORTED LUNS DATA
9387		 * HAS CHANGED unit attention condition for all logical
9388		 * units of that target with respect to the requesting
9389		 * initiator. A valid and installed logical unit is one
9390		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9391		 * INQUIRY data (see 6.4.2)."
9392		 *
9393		 * If request_lun is NULL, the LUN this report luns command
9394		 * was issued to is either disabled or doesn't exist. In that
9395		 * case, we shouldn't clear any pending lun change unit
9396		 * attention.
9397		 */
9398		if (request_lun != NULL) {
9399			mtx_lock(&lun->lun_lock);
9400			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9401			mtx_unlock(&lun->lun_lock);
9402		}
9403	}
9404	mtx_unlock(&control_softc->ctl_lock);
9405
9406	/*
9407	 * It's quite possible that we've returned fewer LUNs than we allocated
9408	 * space for.  Trim it.
9409	 */
9410	lun_datalen = sizeof(*lun_data) +
9411		(num_filled * sizeof(struct scsi_report_luns_lundata));
9412
9413	if (lun_datalen < alloc_len) {
9414		ctsio->residual = alloc_len - lun_datalen;
9415		ctsio->kern_data_len = lun_datalen;
9416		ctsio->kern_total_len = lun_datalen;
9417	} else {
9418		ctsio->residual = 0;
9419		ctsio->kern_data_len = alloc_len;
9420		ctsio->kern_total_len = alloc_len;
9421	}
9422	ctsio->kern_data_resid = 0;
9423	ctsio->kern_rel_offset = 0;
9424	ctsio->kern_sg_entries = 0;
9425
9426	/*
9427	 * We set this to the actual data length, regardless of how much
9428	 * space we actually have to return results.  If the user looks at
9429	 * this value, he'll know whether or not he allocated enough space
9430	 * and reissue the command if necessary.  We don't support well
9431	 * known logical units, so if the user asks for that, return none.
9432	 */
9433	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9434
9435	/*
9436	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9437	 * this request.
9438	 */
9439	ctsio->scsi_status = SCSI_STATUS_OK;
9440
9441	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9442	ctsio->be_move_done = ctl_config_move_done;
9443	ctl_datamove((union ctl_io *)ctsio);
9444
9445	return (retval);
9446}
9447
9448int
9449ctl_request_sense(struct ctl_scsiio *ctsio)
9450{
9451	struct scsi_request_sense *cdb;
9452	struct scsi_sense_data *sense_ptr;
9453	struct ctl_lun *lun;
9454	uint32_t initidx;
9455	int have_error;
9456	scsi_sense_data_type sense_format;
9457
9458	cdb = (struct scsi_request_sense *)ctsio->cdb;
9459
9460	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9461
9462	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9463
9464	/*
9465	 * Determine which sense format the user wants.
9466	 */
9467	if (cdb->byte2 & SRS_DESC)
9468		sense_format = SSD_TYPE_DESC;
9469	else
9470		sense_format = SSD_TYPE_FIXED;
9471
9472	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9473	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9474	ctsio->kern_sg_entries = 0;
9475
9476	/*
9477	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9478	 * larger than the largest allowed value for the length field in the
9479	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9480	 */
9481	ctsio->residual = 0;
9482	ctsio->kern_data_len = cdb->length;
9483	ctsio->kern_total_len = cdb->length;
9484
9485	ctsio->kern_data_resid = 0;
9486	ctsio->kern_rel_offset = 0;
9487	ctsio->kern_sg_entries = 0;
9488
9489	/*
9490	 * If we don't have a LUN, we don't have any pending sense.
9491	 */
9492	if (lun == NULL)
9493		goto no_sense;
9494
9495	have_error = 0;
9496	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9497	/*
9498	 * Check for pending sense, and then for pending unit attentions.
9499	 * Pending sense gets returned first, then pending unit attentions.
9500	 */
9501	mtx_lock(&lun->lun_lock);
9502#ifdef CTL_WITH_CA
9503	if (ctl_is_set(lun->have_ca, initidx)) {
9504		scsi_sense_data_type stored_format;
9505
9506		/*
9507		 * Check to see which sense format was used for the stored
9508		 * sense data.
9509		 */
9510		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9511
9512		/*
9513		 * If the user requested a different sense format than the
9514		 * one we stored, then we need to convert it to the other
9515		 * format.  If we're going from descriptor to fixed format
9516		 * sense data, we may lose things in translation, depending
9517		 * on what options were used.
9518		 *
9519		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9520		 * for some reason we'll just copy it out as-is.
9521		 */
9522		if ((stored_format == SSD_TYPE_FIXED)
9523		 && (sense_format == SSD_TYPE_DESC))
9524			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9525			    &lun->pending_sense[initidx],
9526			    (struct scsi_sense_data_desc *)sense_ptr);
9527		else if ((stored_format == SSD_TYPE_DESC)
9528		      && (sense_format == SSD_TYPE_FIXED))
9529			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9530			    &lun->pending_sense[initidx],
9531			    (struct scsi_sense_data_fixed *)sense_ptr);
9532		else
9533			memcpy(sense_ptr, &lun->pending_sense[initidx],
9534			       ctl_min(sizeof(*sense_ptr),
9535			       sizeof(lun->pending_sense[initidx])));
9536
9537		ctl_clear_mask(lun->have_ca, initidx);
9538		have_error = 1;
9539	} else
9540#endif
9541	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9542		ctl_ua_type ua_type;
9543
9544		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9545				       sense_ptr, sense_format);
9546		if (ua_type != CTL_UA_NONE)
9547			have_error = 1;
9548	}
9549	mtx_unlock(&lun->lun_lock);
9550
9551	/*
9552	 * We already have a pending error, return it.
9553	 */
9554	if (have_error != 0) {
9555		/*
9556		 * We report the SCSI status as OK, since the status of the
9557		 * request sense command itself is OK.
9558		 */
9559		ctsio->scsi_status = SCSI_STATUS_OK;
9560
9561		/*
9562		 * We report 0 for the sense length, because we aren't doing
9563		 * autosense in this case.  We're reporting sense as
9564		 * parameter data.
9565		 */
9566		ctsio->sense_len = 0;
9567		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9568		ctsio->be_move_done = ctl_config_move_done;
9569		ctl_datamove((union ctl_io *)ctsio);
9570
9571		return (CTL_RETVAL_COMPLETE);
9572	}
9573
9574no_sense:
9575
9576	/*
9577	 * No sense information to report, so we report that everything is
9578	 * okay.
9579	 */
9580	ctl_set_sense_data(sense_ptr,
9581			   lun,
9582			   sense_format,
9583			   /*current_error*/ 1,
9584			   /*sense_key*/ SSD_KEY_NO_SENSE,
9585			   /*asc*/ 0x00,
9586			   /*ascq*/ 0x00,
9587			   SSD_ELEM_NONE);
9588
9589	ctsio->scsi_status = SCSI_STATUS_OK;
9590
9591	/*
9592	 * We report 0 for the sense length, because we aren't doing
9593	 * autosense in this case.  We're reporting sense as parameter data.
9594	 */
9595	ctsio->sense_len = 0;
9596	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9597	ctsio->be_move_done = ctl_config_move_done;
9598	ctl_datamove((union ctl_io *)ctsio);
9599
9600	return (CTL_RETVAL_COMPLETE);
9601}
9602
9603int
9604ctl_tur(struct ctl_scsiio *ctsio)
9605{
9606	struct ctl_lun *lun;
9607
9608	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9609
9610	CTL_DEBUG_PRINT(("ctl_tur\n"));
9611
9612	if (lun == NULL)
9613		return (EINVAL);
9614
9615	ctsio->scsi_status = SCSI_STATUS_OK;
9616	ctsio->io_hdr.status = CTL_SUCCESS;
9617
9618	ctl_done((union ctl_io *)ctsio);
9619
9620	return (CTL_RETVAL_COMPLETE);
9621}
9622
9623#ifdef notyet
9624static int
9625ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9626{
9627
9628}
9629#endif
9630
9631static int
9632ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9633{
9634	struct scsi_vpd_supported_pages *pages;
9635	int sup_page_size;
9636	struct ctl_lun *lun;
9637
9638	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9639
9640	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9641	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9642	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9643	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9644	ctsio->kern_sg_entries = 0;
9645
9646	if (sup_page_size < alloc_len) {
9647		ctsio->residual = alloc_len - sup_page_size;
9648		ctsio->kern_data_len = sup_page_size;
9649		ctsio->kern_total_len = sup_page_size;
9650	} else {
9651		ctsio->residual = 0;
9652		ctsio->kern_data_len = alloc_len;
9653		ctsio->kern_total_len = alloc_len;
9654	}
9655	ctsio->kern_data_resid = 0;
9656	ctsio->kern_rel_offset = 0;
9657	ctsio->kern_sg_entries = 0;
9658
9659	/*
9660	 * The control device is always connected.  The disk device, on the
9661	 * other hand, may not be online all the time.  Need to change this
9662	 * to figure out whether the disk device is actually online or not.
9663	 */
9664	if (lun != NULL)
9665		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9666				lun->be_lun->lun_type;
9667	else
9668		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9669
9670	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9671	/* Supported VPD pages */
9672	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9673	/* Serial Number */
9674	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9675	/* Device Identification */
9676	pages->page_list[2] = SVPD_DEVICE_ID;
9677	/* Extended INQUIRY Data */
9678	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9679	/* Mode Page Policy */
9680	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9681	/* SCSI Ports */
9682	pages->page_list[5] = SVPD_SCSI_PORTS;
9683	/* Third-party Copy */
9684	pages->page_list[6] = SVPD_SCSI_TPC;
9685	/* Block limits */
9686	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9687	/* Block Device Characteristics */
9688	pages->page_list[8] = SVPD_BDC;
9689	/* Logical Block Provisioning */
9690	pages->page_list[9] = SVPD_LBP;
9691
9692	ctsio->scsi_status = SCSI_STATUS_OK;
9693
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
9701static int
9702ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9703{
9704	struct scsi_vpd_unit_serial_number *sn_ptr;
9705	struct ctl_lun *lun;
9706
9707	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9708
9709	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9710	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9711	ctsio->kern_sg_entries = 0;
9712
9713	if (sizeof(*sn_ptr) < alloc_len) {
9714		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9715		ctsio->kern_data_len = sizeof(*sn_ptr);
9716		ctsio->kern_total_len = sizeof(*sn_ptr);
9717	} else {
9718		ctsio->residual = 0;
9719		ctsio->kern_data_len = alloc_len;
9720		ctsio->kern_total_len = alloc_len;
9721	}
9722	ctsio->kern_data_resid = 0;
9723	ctsio->kern_rel_offset = 0;
9724	ctsio->kern_sg_entries = 0;
9725
9726	/*
9727	 * The control device is always connected.  The disk device, on the
9728	 * other hand, may not be online all the time.  Need to change this
9729	 * to figure out whether the disk device is actually online or not.
9730	 */
9731	if (lun != NULL)
9732		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9733				  lun->be_lun->lun_type;
9734	else
9735		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9736
9737	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9738	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9739	/*
9740	 * If we don't have a LUN, we just leave the serial number as
9741	 * all spaces.
9742	 */
9743	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9744	if (lun != NULL) {
9745		strncpy((char *)sn_ptr->serial_num,
9746			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9747	}
9748	ctsio->scsi_status = SCSI_STATUS_OK;
9749
9750	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9751	ctsio->be_move_done = ctl_config_move_done;
9752	ctl_datamove((union ctl_io *)ctsio);
9753
9754	return (CTL_RETVAL_COMPLETE);
9755}
9756
9757
9758static int
9759ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9760{
9761	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9762	struct ctl_lun *lun;
9763	int data_len;
9764
9765	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9766
9767	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9768	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9769	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9770	ctsio->kern_sg_entries = 0;
9771
9772	if (data_len < alloc_len) {
9773		ctsio->residual = alloc_len - data_len;
9774		ctsio->kern_data_len = data_len;
9775		ctsio->kern_total_len = data_len;
9776	} else {
9777		ctsio->residual = 0;
9778		ctsio->kern_data_len = alloc_len;
9779		ctsio->kern_total_len = alloc_len;
9780	}
9781	ctsio->kern_data_resid = 0;
9782	ctsio->kern_rel_offset = 0;
9783	ctsio->kern_sg_entries = 0;
9784
9785	/*
9786	 * The control device is always connected.  The disk device, on the
9787	 * other hand, may not be online all the time.
9788	 */
9789	if (lun != NULL)
9790		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9791				     lun->be_lun->lun_type;
9792	else
9793		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9794	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9795	eid_ptr->page_length = data_len - 4;
9796	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9797	eid_ptr->flags3 = SVPD_EID_V_SUP;
9798
9799	ctsio->scsi_status = SCSI_STATUS_OK;
9800	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9801	ctsio->be_move_done = ctl_config_move_done;
9802	ctl_datamove((union ctl_io *)ctsio);
9803
9804	return (CTL_RETVAL_COMPLETE);
9805}
9806
9807static int
9808ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9809{
9810	struct scsi_vpd_mode_page_policy *mpp_ptr;
9811	struct ctl_lun *lun;
9812	int data_len;
9813
9814	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9815
9816	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9817	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9818
9819	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9820	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9821	ctsio->kern_sg_entries = 0;
9822
9823	if (data_len < alloc_len) {
9824		ctsio->residual = alloc_len - data_len;
9825		ctsio->kern_data_len = data_len;
9826		ctsio->kern_total_len = data_len;
9827	} else {
9828		ctsio->residual = 0;
9829		ctsio->kern_data_len = alloc_len;
9830		ctsio->kern_total_len = alloc_len;
9831	}
9832	ctsio->kern_data_resid = 0;
9833	ctsio->kern_rel_offset = 0;
9834	ctsio->kern_sg_entries = 0;
9835
9836	/*
9837	 * The control device is always connected.  The disk device, on the
9838	 * other hand, may not be online all the time.
9839	 */
9840	if (lun != NULL)
9841		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9842				     lun->be_lun->lun_type;
9843	else
9844		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9845	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9846	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9847	mpp_ptr->descr[0].page_code = 0x3f;
9848	mpp_ptr->descr[0].subpage_code = 0xff;
9849	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9850
9851	ctsio->scsi_status = SCSI_STATUS_OK;
9852	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9853	ctsio->be_move_done = ctl_config_move_done;
9854	ctl_datamove((union ctl_io *)ctsio);
9855
9856	return (CTL_RETVAL_COMPLETE);
9857}
9858
9859static int
9860ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9861{
9862	struct scsi_vpd_device_id *devid_ptr;
9863	struct scsi_vpd_id_descriptor *desc;
9864	struct ctl_softc *ctl_softc;
9865	struct ctl_lun *lun;
9866	struct ctl_port *port;
9867	int data_len;
9868	uint8_t proto;
9869
9870	ctl_softc = control_softc;
9871
9872	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9873	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9874
9875	data_len = sizeof(struct scsi_vpd_device_id) +
9876	    sizeof(struct scsi_vpd_id_descriptor) +
9877		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9878	    sizeof(struct scsi_vpd_id_descriptor) +
9879		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9880	if (lun && lun->lun_devid)
9881		data_len += lun->lun_devid->len;
9882	if (port->port_devid)
9883		data_len += port->port_devid->len;
9884	if (port->target_devid)
9885		data_len += port->target_devid->len;
9886
9887	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9888	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9889	ctsio->kern_sg_entries = 0;
9890
9891	if (data_len < alloc_len) {
9892		ctsio->residual = alloc_len - data_len;
9893		ctsio->kern_data_len = data_len;
9894		ctsio->kern_total_len = data_len;
9895	} else {
9896		ctsio->residual = 0;
9897		ctsio->kern_data_len = alloc_len;
9898		ctsio->kern_total_len = alloc_len;
9899	}
9900	ctsio->kern_data_resid = 0;
9901	ctsio->kern_rel_offset = 0;
9902	ctsio->kern_sg_entries = 0;
9903
9904	/*
9905	 * The control device is always connected.  The disk device, on the
9906	 * other hand, may not be online all the time.
9907	 */
9908	if (lun != NULL)
9909		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9910				     lun->be_lun->lun_type;
9911	else
9912		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9913	devid_ptr->page_code = SVPD_DEVICE_ID;
9914	scsi_ulto2b(data_len - 4, devid_ptr->length);
9915
9916	if (port->port_type == CTL_PORT_FC)
9917		proto = SCSI_PROTO_FC << 4;
9918	else if (port->port_type == CTL_PORT_ISCSI)
9919		proto = SCSI_PROTO_ISCSI << 4;
9920	else
9921		proto = SCSI_PROTO_SPI << 4;
9922	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9923
9924	/*
9925	 * We're using a LUN association here.  i.e., this device ID is a
9926	 * per-LUN identifier.
9927	 */
9928	if (lun && lun->lun_devid) {
9929		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9930		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9931		    lun->lun_devid->len);
9932	}
9933
9934	/*
9935	 * This is for the WWPN which is a port association.
9936	 */
9937	if (port->port_devid) {
9938		memcpy(desc, port->port_devid->data, port->port_devid->len);
9939		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9940		    port->port_devid->len);
9941	}
9942
9943	/*
9944	 * This is for the Relative Target Port(type 4h) identifier
9945	 */
9946	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9947	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9948	    SVPD_ID_TYPE_RELTARG;
9949	desc->length = 4;
9950	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9951	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9952	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9953
9954	/*
9955	 * This is for the Target Port Group(type 5h) identifier
9956	 */
9957	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9958	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9959	    SVPD_ID_TYPE_TPORTGRP;
9960	desc->length = 4;
9961	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9962	    &desc->identifier[2]);
9963	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9964	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9965
9966	/*
9967	 * This is for the Target identifier
9968	 */
9969	if (port->target_devid) {
9970		memcpy(desc, port->target_devid->data, port->target_devid->len);
9971	}
9972
9973	ctsio->scsi_status = SCSI_STATUS_OK;
9974	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9975	ctsio->be_move_done = ctl_config_move_done;
9976	ctl_datamove((union ctl_io *)ctsio);
9977
9978	return (CTL_RETVAL_COMPLETE);
9979}
9980
9981static int
9982ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9983{
9984	struct ctl_softc *softc = control_softc;
9985	struct scsi_vpd_scsi_ports *sp;
9986	struct scsi_vpd_port_designation *pd;
9987	struct scsi_vpd_port_designation_cont *pdc;
9988	struct ctl_lun *lun;
9989	struct ctl_port *port;
9990	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9991	int num_target_port_groups, single;
9992
9993	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9994
9995	single = ctl_is_single;
9996	if (single)
9997		num_target_port_groups = 1;
9998	else
9999		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10000	num_target_ports = 0;
10001	iid_len = 0;
10002	id_len = 0;
10003	mtx_lock(&softc->ctl_lock);
10004	STAILQ_FOREACH(port, &softc->port_list, links) {
10005		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10006			continue;
10007		if (lun != NULL &&
10008		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10009		    CTL_MAX_LUNS)
10010			continue;
10011		num_target_ports++;
10012		if (port->init_devid)
10013			iid_len += port->init_devid->len;
10014		if (port->port_devid)
10015			id_len += port->port_devid->len;
10016	}
10017	mtx_unlock(&softc->ctl_lock);
10018
10019	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10020	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10021	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10022	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10023	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10024	ctsio->kern_sg_entries = 0;
10025
10026	if (data_len < alloc_len) {
10027		ctsio->residual = alloc_len - data_len;
10028		ctsio->kern_data_len = data_len;
10029		ctsio->kern_total_len = data_len;
10030	} else {
10031		ctsio->residual = 0;
10032		ctsio->kern_data_len = alloc_len;
10033		ctsio->kern_total_len = alloc_len;
10034	}
10035	ctsio->kern_data_resid = 0;
10036	ctsio->kern_rel_offset = 0;
10037	ctsio->kern_sg_entries = 0;
10038
10039	/*
10040	 * The control device is always connected.  The disk device, on the
10041	 * other hand, may not be online all the time.  Need to change this
10042	 * to figure out whether the disk device is actually online or not.
10043	 */
10044	if (lun != NULL)
10045		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10046				  lun->be_lun->lun_type;
10047	else
10048		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10049
10050	sp->page_code = SVPD_SCSI_PORTS;
10051	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10052	    sp->page_length);
10053	pd = &sp->design[0];
10054
10055	mtx_lock(&softc->ctl_lock);
10056	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10057		pg = 0;
10058	else
10059		pg = 1;
10060	for (g = 0; g < num_target_port_groups; g++) {
10061		STAILQ_FOREACH(port, &softc->port_list, links) {
10062			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10063				continue;
10064			if (lun != NULL &&
10065			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10066			    CTL_MAX_LUNS)
10067				continue;
10068			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10069			scsi_ulto2b(p, pd->relative_port_id);
10070			if (port->init_devid && g == pg) {
10071				iid_len = port->init_devid->len;
10072				memcpy(pd->initiator_transportid,
10073				    port->init_devid->data, port->init_devid->len);
10074			} else
10075				iid_len = 0;
10076			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10077			pdc = (struct scsi_vpd_port_designation_cont *)
10078			    (&pd->initiator_transportid[iid_len]);
10079			if (port->port_devid && g == pg) {
10080				id_len = port->port_devid->len;
10081				memcpy(pdc->target_port_descriptors,
10082				    port->port_devid->data, port->port_devid->len);
10083			} else
10084				id_len = 0;
10085			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10086			pd = (struct scsi_vpd_port_designation *)
10087			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10088		}
10089	}
10090	mtx_unlock(&softc->ctl_lock);
10091
10092	ctsio->scsi_status = SCSI_STATUS_OK;
10093	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10094	ctsio->be_move_done = ctl_config_move_done;
10095	ctl_datamove((union ctl_io *)ctsio);
10096
10097	return (CTL_RETVAL_COMPLETE);
10098}
10099
10100static int
10101ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10102{
10103	struct scsi_vpd_block_limits *bl_ptr;
10104	struct ctl_lun *lun;
10105	int bs;
10106
10107	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10108
10109	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10110	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10111	ctsio->kern_sg_entries = 0;
10112
10113	if (sizeof(*bl_ptr) < alloc_len) {
10114		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10115		ctsio->kern_data_len = sizeof(*bl_ptr);
10116		ctsio->kern_total_len = sizeof(*bl_ptr);
10117	} else {
10118		ctsio->residual = 0;
10119		ctsio->kern_data_len = alloc_len;
10120		ctsio->kern_total_len = alloc_len;
10121	}
10122	ctsio->kern_data_resid = 0;
10123	ctsio->kern_rel_offset = 0;
10124	ctsio->kern_sg_entries = 0;
10125
10126	/*
10127	 * The control device is always connected.  The disk device, on the
10128	 * other hand, may not be online all the time.  Need to change this
10129	 * to figure out whether the disk device is actually online or not.
10130	 */
10131	if (lun != NULL)
10132		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10133				  lun->be_lun->lun_type;
10134	else
10135		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10136
10137	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10138	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10139	bl_ptr->max_cmp_write_len = 0xff;
10140	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10141	if (lun != NULL) {
10142		bs = lun->be_lun->blocksize;
10143		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10144		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10145			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10146			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10147			if (lun->be_lun->pblockexp != 0) {
10148				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10149				    bl_ptr->opt_unmap_grain);
10150				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10151				    bl_ptr->unmap_grain_align);
10152			}
10153		}
10154		scsi_ulto4b(lun->be_lun->atomicblock,
10155		    bl_ptr->max_atomic_transfer_length);
10156		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10157		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10158	}
10159	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10160
10161	ctsio->scsi_status = SCSI_STATUS_OK;
10162	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10163	ctsio->be_move_done = ctl_config_move_done;
10164	ctl_datamove((union ctl_io *)ctsio);
10165
10166	return (CTL_RETVAL_COMPLETE);
10167}
10168
10169static int
10170ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10171{
10172	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10173	struct ctl_lun *lun;
10174
10175	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10176
10177	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10178	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10179	ctsio->kern_sg_entries = 0;
10180
10181	if (sizeof(*bdc_ptr) < alloc_len) {
10182		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10183		ctsio->kern_data_len = sizeof(*bdc_ptr);
10184		ctsio->kern_total_len = sizeof(*bdc_ptr);
10185	} else {
10186		ctsio->residual = 0;
10187		ctsio->kern_data_len = alloc_len;
10188		ctsio->kern_total_len = alloc_len;
10189	}
10190	ctsio->kern_data_resid = 0;
10191	ctsio->kern_rel_offset = 0;
10192	ctsio->kern_sg_entries = 0;
10193
10194	/*
10195	 * The control device is always connected.  The disk device, on the
10196	 * other hand, may not be online all the time.  Need to change this
10197	 * to figure out whether the disk device is actually online or not.
10198	 */
10199	if (lun != NULL)
10200		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10201				  lun->be_lun->lun_type;
10202	else
10203		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10204	bdc_ptr->page_code = SVPD_BDC;
10205	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10206	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10207	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10208
10209	ctsio->scsi_status = SCSI_STATUS_OK;
10210	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10211	ctsio->be_move_done = ctl_config_move_done;
10212	ctl_datamove((union ctl_io *)ctsio);
10213
10214	return (CTL_RETVAL_COMPLETE);
10215}
10216
10217static int
10218ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10219{
10220	struct scsi_vpd_logical_block_prov *lbp_ptr;
10221	struct ctl_lun *lun;
10222
10223	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10224
10225	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10226	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10227	ctsio->kern_sg_entries = 0;
10228
10229	if (sizeof(*lbp_ptr) < alloc_len) {
10230		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10231		ctsio->kern_data_len = sizeof(*lbp_ptr);
10232		ctsio->kern_total_len = sizeof(*lbp_ptr);
10233	} else {
10234		ctsio->residual = 0;
10235		ctsio->kern_data_len = alloc_len;
10236		ctsio->kern_total_len = alloc_len;
10237	}
10238	ctsio->kern_data_resid = 0;
10239	ctsio->kern_rel_offset = 0;
10240	ctsio->kern_sg_entries = 0;
10241
10242	/*
10243	 * The control device is always connected.  The disk device, on the
10244	 * other hand, may not be online all the time.  Need to change this
10245	 * to figure out whether the disk device is actually online or not.
10246	 */
10247	if (lun != NULL)
10248		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10249				  lun->be_lun->lun_type;
10250	else
10251		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10252
10253	lbp_ptr->page_code = SVPD_LBP;
10254	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10255	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10256		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10257		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10258		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10259	}
10260
10261	ctsio->scsi_status = SCSI_STATUS_OK;
10262	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10263	ctsio->be_move_done = ctl_config_move_done;
10264	ctl_datamove((union ctl_io *)ctsio);
10265
10266	return (CTL_RETVAL_COMPLETE);
10267}
10268
10269static int
10270ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10271{
10272	struct scsi_inquiry *cdb;
10273	struct ctl_lun *lun;
10274	int alloc_len, retval;
10275
10276	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10277	cdb = (struct scsi_inquiry *)ctsio->cdb;
10278
10279	retval = CTL_RETVAL_COMPLETE;
10280
10281	alloc_len = scsi_2btoul(cdb->length);
10282
10283	switch (cdb->page_code) {
10284	case SVPD_SUPPORTED_PAGES:
10285		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10286		break;
10287	case SVPD_UNIT_SERIAL_NUMBER:
10288		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10289		break;
10290	case SVPD_DEVICE_ID:
10291		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10292		break;
10293	case SVPD_EXTENDED_INQUIRY_DATA:
10294		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10295		break;
10296	case SVPD_MODE_PAGE_POLICY:
10297		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10298		break;
10299	case SVPD_SCSI_PORTS:
10300		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10301		break;
10302	case SVPD_SCSI_TPC:
10303		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10304		break;
10305	case SVPD_BLOCK_LIMITS:
10306		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10307		break;
10308	case SVPD_BDC:
10309		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10310		break;
10311	case SVPD_LBP:
10312		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10313		break;
10314	default:
10315		ctl_set_invalid_field(ctsio,
10316				      /*sks_valid*/ 1,
10317				      /*command*/ 1,
10318				      /*field*/ 2,
10319				      /*bit_valid*/ 0,
10320				      /*bit*/ 0);
10321		ctl_done((union ctl_io *)ctsio);
10322		retval = CTL_RETVAL_COMPLETE;
10323		break;
10324	}
10325
10326	return (retval);
10327}
10328
10329static int
10330ctl_inquiry_std(struct ctl_scsiio *ctsio)
10331{
10332	struct scsi_inquiry_data *inq_ptr;
10333	struct scsi_inquiry *cdb;
10334	struct ctl_softc *ctl_softc;
10335	struct ctl_lun *lun;
10336	char *val;
10337	uint32_t alloc_len, data_len;
10338	ctl_port_type port_type;
10339
10340	ctl_softc = control_softc;
10341
10342	/*
10343	 * Figure out whether we're talking to a Fibre Channel port or not.
10344	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10345	 * SCSI front ends.
10346	 */
10347	port_type = ctl_softc->ctl_ports[
10348	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10349	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10350		port_type = CTL_PORT_SCSI;
10351
10352	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10353	cdb = (struct scsi_inquiry *)ctsio->cdb;
10354	alloc_len = scsi_2btoul(cdb->length);
10355
10356	/*
10357	 * We malloc the full inquiry data size here and fill it
10358	 * in.  If the user only asks for less, we'll give him
10359	 * that much.
10360	 */
10361	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10362	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10363	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10364	ctsio->kern_sg_entries = 0;
10365	ctsio->kern_data_resid = 0;
10366	ctsio->kern_rel_offset = 0;
10367
10368	if (data_len < alloc_len) {
10369		ctsio->residual = alloc_len - data_len;
10370		ctsio->kern_data_len = data_len;
10371		ctsio->kern_total_len = data_len;
10372	} else {
10373		ctsio->residual = 0;
10374		ctsio->kern_data_len = alloc_len;
10375		ctsio->kern_total_len = alloc_len;
10376	}
10377
10378	/*
10379	 * If we have a LUN configured, report it as connected.  Otherwise,
10380	 * report that it is offline or no device is supported, depending
10381	 * on the value of inquiry_pq_no_lun.
10382	 *
10383	 * According to the spec (SPC-4 r34), the peripheral qualifier
10384	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10385	 *
10386	 * "A peripheral device having the specified peripheral device type
10387	 * is not connected to this logical unit. However, the device
10388	 * server is capable of supporting the specified peripheral device
10389	 * type on this logical unit."
10390	 *
10391	 * According to the same spec, the peripheral qualifier
10392	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10393	 *
10394	 * "The device server is not capable of supporting a peripheral
10395	 * device on this logical unit. For this peripheral qualifier the
10396	 * peripheral device type shall be set to 1Fh. All other peripheral
10397	 * device type values are reserved for this peripheral qualifier."
10398	 *
10399	 * Given the text, it would seem that we probably want to report that
10400	 * the LUN is offline here.  There is no LUN connected, but we can
10401	 * support a LUN at the given LUN number.
10402	 *
10403	 * In the real world, though, it sounds like things are a little
10404	 * different:
10405	 *
10406	 * - Linux, when presented with a LUN with the offline peripheral
10407	 *   qualifier, will create an sg driver instance for it.  So when
10408	 *   you attach it to CTL, you wind up with a ton of sg driver
10409	 *   instances.  (One for every LUN that Linux bothered to probe.)
10410	 *   Linux does this despite the fact that it issues a REPORT LUNs
10411	 *   to LUN 0 to get the inventory of supported LUNs.
10412	 *
10413	 * - There is other anecdotal evidence (from Emulex folks) about
10414	 *   arrays that use the offline peripheral qualifier for LUNs that
10415	 *   are on the "passive" path in an active/passive array.
10416	 *
10417	 * So the solution is provide a hopefully reasonable default
10418	 * (return bad/no LUN) and allow the user to change the behavior
10419	 * with a tunable/sysctl variable.
10420	 */
10421	if (lun != NULL)
10422		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10423				  lun->be_lun->lun_type;
10424	else if (ctl_softc->inquiry_pq_no_lun == 0)
10425		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10426	else
10427		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10428
10429	/* RMB in byte 2 is 0 */
10430	inq_ptr->version = SCSI_REV_SPC4;
10431
10432	/*
10433	 * According to SAM-3, even if a device only supports a single
10434	 * level of LUN addressing, it should still set the HISUP bit:
10435	 *
10436	 * 4.9.1 Logical unit numbers overview
10437	 *
10438	 * All logical unit number formats described in this standard are
10439	 * hierarchical in structure even when only a single level in that
10440	 * hierarchy is used. The HISUP bit shall be set to one in the
10441	 * standard INQUIRY data (see SPC-2) when any logical unit number
10442	 * format described in this standard is used.  Non-hierarchical
10443	 * formats are outside the scope of this standard.
10444	 *
10445	 * Therefore we set the HiSup bit here.
10446	 *
10447	 * The reponse format is 2, per SPC-3.
10448	 */
10449	inq_ptr->response_format = SID_HiSup | 2;
10450
10451	inq_ptr->additional_length = data_len -
10452	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10453	CTL_DEBUG_PRINT(("additional_length = %d\n",
10454			 inq_ptr->additional_length));
10455
10456	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10457	/* 16 bit addressing */
10458	if (port_type == CTL_PORT_SCSI)
10459		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10460	/* XXX set the SID_MultiP bit here if we're actually going to
10461	   respond on multiple ports */
10462	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10463
10464	/* 16 bit data bus, synchronous transfers */
10465	if (port_type == CTL_PORT_SCSI)
10466		inq_ptr->flags = SID_WBus16 | SID_Sync;
10467	/*
10468	 * XXX KDM do we want to support tagged queueing on the control
10469	 * device at all?
10470	 */
10471	if ((lun == NULL)
10472	 || (lun->be_lun->lun_type != T_PROCESSOR))
10473		inq_ptr->flags |= SID_CmdQue;
10474	/*
10475	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10476	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10477	 * name and 4 bytes for the revision.
10478	 */
10479	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10480	    "vendor")) == NULL) {
10481		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10482	} else {
10483		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10484		strncpy(inq_ptr->vendor, val,
10485		    min(sizeof(inq_ptr->vendor), strlen(val)));
10486	}
10487	if (lun == NULL) {
10488		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10489		    sizeof(inq_ptr->product));
10490	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10491		switch (lun->be_lun->lun_type) {
10492		case T_DIRECT:
10493			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10494			    sizeof(inq_ptr->product));
10495			break;
10496		case T_PROCESSOR:
10497			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10498			    sizeof(inq_ptr->product));
10499			break;
10500		default:
10501			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10502			    sizeof(inq_ptr->product));
10503			break;
10504		}
10505	} else {
10506		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10507		strncpy(inq_ptr->product, val,
10508		    min(sizeof(inq_ptr->product), strlen(val)));
10509	}
10510
10511	/*
10512	 * XXX make this a macro somewhere so it automatically gets
10513	 * incremented when we make changes.
10514	 */
10515	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10516	    "revision")) == NULL) {
10517		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10518	} else {
10519		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10520		strncpy(inq_ptr->revision, val,
10521		    min(sizeof(inq_ptr->revision), strlen(val)));
10522	}
10523
10524	/*
10525	 * For parallel SCSI, we support double transition and single
10526	 * transition clocking.  We also support QAS (Quick Arbitration
10527	 * and Selection) and Information Unit transfers on both the
10528	 * control and array devices.
10529	 */
10530	if (port_type == CTL_PORT_SCSI)
10531		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10532				    SID_SPI_IUS;
10533
10534	/* SAM-5 (no version claimed) */
10535	scsi_ulto2b(0x00A0, inq_ptr->version1);
10536	/* SPC-4 (no version claimed) */
10537	scsi_ulto2b(0x0460, inq_ptr->version2);
10538	if (port_type == CTL_PORT_FC) {
10539		/* FCP-2 ANSI INCITS.350:2003 */
10540		scsi_ulto2b(0x0917, inq_ptr->version3);
10541	} else if (port_type == CTL_PORT_SCSI) {
10542		/* SPI-4 ANSI INCITS.362:200x */
10543		scsi_ulto2b(0x0B56, inq_ptr->version3);
10544	} else if (port_type == CTL_PORT_ISCSI) {
10545		/* iSCSI (no version claimed) */
10546		scsi_ulto2b(0x0960, inq_ptr->version3);
10547	} else if (port_type == CTL_PORT_SAS) {
10548		/* SAS (no version claimed) */
10549		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10550	}
10551
10552	if (lun == NULL) {
10553		/* SBC-4 (no version claimed) */
10554		scsi_ulto2b(0x0600, inq_ptr->version4);
10555	} else {
10556		switch (lun->be_lun->lun_type) {
10557		case T_DIRECT:
10558			/* SBC-4 (no version claimed) */
10559			scsi_ulto2b(0x0600, inq_ptr->version4);
10560			break;
10561		case T_PROCESSOR:
10562		default:
10563			break;
10564		}
10565	}
10566
10567	ctsio->scsi_status = SCSI_STATUS_OK;
10568	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10569	ctsio->be_move_done = ctl_config_move_done;
10570	ctl_datamove((union ctl_io *)ctsio);
10571	return (CTL_RETVAL_COMPLETE);
10572}
10573
10574int
10575ctl_inquiry(struct ctl_scsiio *ctsio)
10576{
10577	struct scsi_inquiry *cdb;
10578	int retval;
10579
10580	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10581
10582	cdb = (struct scsi_inquiry *)ctsio->cdb;
10583	if (cdb->byte2 & SI_EVPD)
10584		retval = ctl_inquiry_evpd(ctsio);
10585	else if (cdb->page_code == 0)
10586		retval = ctl_inquiry_std(ctsio);
10587	else {
10588		ctl_set_invalid_field(ctsio,
10589				      /*sks_valid*/ 1,
10590				      /*command*/ 1,
10591				      /*field*/ 2,
10592				      /*bit_valid*/ 0,
10593				      /*bit*/ 0);
10594		ctl_done((union ctl_io *)ctsio);
10595		return (CTL_RETVAL_COMPLETE);
10596	}
10597
10598	return (retval);
10599}
10600
10601/*
10602 * For known CDB types, parse the LBA and length.
10603 */
10604static int
10605ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10606{
10607	if (io->io_hdr.io_type != CTL_IO_SCSI)
10608		return (1);
10609
10610	switch (io->scsiio.cdb[0]) {
10611	case COMPARE_AND_WRITE: {
10612		struct scsi_compare_and_write *cdb;
10613
10614		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10615
10616		*lba = scsi_8btou64(cdb->addr);
10617		*len = cdb->length;
10618		break;
10619	}
10620	case READ_6:
10621	case WRITE_6: {
10622		struct scsi_rw_6 *cdb;
10623
10624		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10625
10626		*lba = scsi_3btoul(cdb->addr);
10627		/* only 5 bits are valid in the most significant address byte */
10628		*lba &= 0x1fffff;
10629		*len = cdb->length;
10630		break;
10631	}
10632	case READ_10:
10633	case WRITE_10: {
10634		struct scsi_rw_10 *cdb;
10635
10636		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10637
10638		*lba = scsi_4btoul(cdb->addr);
10639		*len = scsi_2btoul(cdb->length);
10640		break;
10641	}
10642	case WRITE_VERIFY_10: {
10643		struct scsi_write_verify_10 *cdb;
10644
10645		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10646
10647		*lba = scsi_4btoul(cdb->addr);
10648		*len = scsi_2btoul(cdb->length);
10649		break;
10650	}
10651	case READ_12:
10652	case WRITE_12: {
10653		struct scsi_rw_12 *cdb;
10654
10655		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10656
10657		*lba = scsi_4btoul(cdb->addr);
10658		*len = scsi_4btoul(cdb->length);
10659		break;
10660	}
10661	case WRITE_VERIFY_12: {
10662		struct scsi_write_verify_12 *cdb;
10663
10664		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10665
10666		*lba = scsi_4btoul(cdb->addr);
10667		*len = scsi_4btoul(cdb->length);
10668		break;
10669	}
10670	case READ_16:
10671	case WRITE_16:
10672	case WRITE_ATOMIC_16: {
10673		struct scsi_rw_16 *cdb;
10674
10675		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10676
10677		*lba = scsi_8btou64(cdb->addr);
10678		*len = scsi_4btoul(cdb->length);
10679		break;
10680	}
10681	case WRITE_VERIFY_16: {
10682		struct scsi_write_verify_16 *cdb;
10683
10684		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10685
10686		*lba = scsi_8btou64(cdb->addr);
10687		*len = scsi_4btoul(cdb->length);
10688		break;
10689	}
10690	case WRITE_SAME_10: {
10691		struct scsi_write_same_10 *cdb;
10692
10693		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10694
10695		*lba = scsi_4btoul(cdb->addr);
10696		*len = scsi_2btoul(cdb->length);
10697		break;
10698	}
10699	case WRITE_SAME_16: {
10700		struct scsi_write_same_16 *cdb;
10701
10702		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10703
10704		*lba = scsi_8btou64(cdb->addr);
10705		*len = scsi_4btoul(cdb->length);
10706		break;
10707	}
10708	case VERIFY_10: {
10709		struct scsi_verify_10 *cdb;
10710
10711		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10712
10713		*lba = scsi_4btoul(cdb->addr);
10714		*len = scsi_2btoul(cdb->length);
10715		break;
10716	}
10717	case VERIFY_12: {
10718		struct scsi_verify_12 *cdb;
10719
10720		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10721
10722		*lba = scsi_4btoul(cdb->addr);
10723		*len = scsi_4btoul(cdb->length);
10724		break;
10725	}
10726	case VERIFY_16: {
10727		struct scsi_verify_16 *cdb;
10728
10729		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10730
10731		*lba = scsi_8btou64(cdb->addr);
10732		*len = scsi_4btoul(cdb->length);
10733		break;
10734	}
10735	case UNMAP: {
10736		*lba = 0;
10737		*len = UINT64_MAX;
10738		break;
10739	}
10740	default:
10741		return (1);
10742		break; /* NOTREACHED */
10743	}
10744
10745	return (0);
10746}
10747
10748static ctl_action
10749ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10750{
10751	uint64_t endlba1, endlba2;
10752
10753	endlba1 = lba1 + len1 - 1;
10754	endlba2 = lba2 + len2 - 1;
10755
10756	if ((endlba1 < lba2)
10757	 || (endlba2 < lba1))
10758		return (CTL_ACTION_PASS);
10759	else
10760		return (CTL_ACTION_BLOCK);
10761}
10762
10763static int
10764ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10765{
10766	struct ctl_ptr_len_flags *ptrlen;
10767	struct scsi_unmap_desc *buf, *end, *range;
10768	uint64_t lba;
10769	uint32_t len;
10770
10771	/* If not UNMAP -- go other way. */
10772	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10773	    io->scsiio.cdb[0] != UNMAP)
10774		return (CTL_ACTION_ERROR);
10775
10776	/* If UNMAP without data -- block and wait for data. */
10777	ptrlen = (struct ctl_ptr_len_flags *)
10778	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10779	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10780	    ptrlen->ptr == NULL)
10781		return (CTL_ACTION_BLOCK);
10782
10783	/* UNMAP with data -- check for collision. */
10784	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10785	end = buf + ptrlen->len / sizeof(*buf);
10786	for (range = buf; range < end; range++) {
10787		lba = scsi_8btou64(range->lba);
10788		len = scsi_4btoul(range->length);
10789		if ((lba < lba2 + len2) && (lba + len > lba2))
10790			return (CTL_ACTION_BLOCK);
10791	}
10792	return (CTL_ACTION_PASS);
10793}
10794
10795static ctl_action
10796ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10797{
10798	uint64_t lba1, lba2;
10799	uint64_t len1, len2;
10800	int retval;
10801
10802	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10803		return (CTL_ACTION_ERROR);
10804
10805	retval = ctl_extent_check_unmap(io2, lba1, len1);
10806	if (retval != CTL_ACTION_ERROR)
10807		return (retval);
10808
10809	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10810		return (CTL_ACTION_ERROR);
10811
10812	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10813}
10814
10815static ctl_action
10816ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10817    union ctl_io *ooa_io)
10818{
10819	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10820	ctl_serialize_action *serialize_row;
10821
10822	/*
10823	 * The initiator attempted multiple untagged commands at the same
10824	 * time.  Can't do that.
10825	 */
10826	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10827	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10828	 && ((pending_io->io_hdr.nexus.targ_port ==
10829	      ooa_io->io_hdr.nexus.targ_port)
10830	  && (pending_io->io_hdr.nexus.initid.id ==
10831	      ooa_io->io_hdr.nexus.initid.id))
10832	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10833		return (CTL_ACTION_OVERLAP);
10834
10835	/*
10836	 * The initiator attempted to send multiple tagged commands with
10837	 * the same ID.  (It's fine if different initiators have the same
10838	 * tag ID.)
10839	 *
10840	 * Even if all of those conditions are true, we don't kill the I/O
10841	 * if the command ahead of us has been aborted.  We won't end up
10842	 * sending it to the FETD, and it's perfectly legal to resend a
10843	 * command with the same tag number as long as the previous
10844	 * instance of this tag number has been aborted somehow.
10845	 */
10846	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10847	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10848	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10849	 && ((pending_io->io_hdr.nexus.targ_port ==
10850	      ooa_io->io_hdr.nexus.targ_port)
10851	  && (pending_io->io_hdr.nexus.initid.id ==
10852	      ooa_io->io_hdr.nexus.initid.id))
10853	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10854		return (CTL_ACTION_OVERLAP_TAG);
10855
10856	/*
10857	 * If we get a head of queue tag, SAM-3 says that we should
10858	 * immediately execute it.
10859	 *
10860	 * What happens if this command would normally block for some other
10861	 * reason?  e.g. a request sense with a head of queue tag
10862	 * immediately after a write.  Normally that would block, but this
10863	 * will result in its getting executed immediately...
10864	 *
10865	 * We currently return "pass" instead of "skip", so we'll end up
10866	 * going through the rest of the queue to check for overlapped tags.
10867	 *
10868	 * XXX KDM check for other types of blockage first??
10869	 */
10870	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10871		return (CTL_ACTION_PASS);
10872
10873	/*
10874	 * Ordered tags have to block until all items ahead of them
10875	 * have completed.  If we get called with an ordered tag, we always
10876	 * block, if something else is ahead of us in the queue.
10877	 */
10878	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10879		return (CTL_ACTION_BLOCK);
10880
10881	/*
10882	 * Simple tags get blocked until all head of queue and ordered tags
10883	 * ahead of them have completed.  I'm lumping untagged commands in
10884	 * with simple tags here.  XXX KDM is that the right thing to do?
10885	 */
10886	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10887	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10888	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10889	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10890		return (CTL_ACTION_BLOCK);
10891
10892	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10893	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10894
10895	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10896
10897	switch (serialize_row[pending_entry->seridx]) {
10898	case CTL_SER_BLOCK:
10899		return (CTL_ACTION_BLOCK);
10900	case CTL_SER_EXTENT:
10901		return (ctl_extent_check(pending_io, ooa_io));
10902	case CTL_SER_EXTENTOPT:
10903		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10904		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10905			return (ctl_extent_check(pending_io, ooa_io));
10906		/* FALLTHROUGH */
10907	case CTL_SER_PASS:
10908		return (CTL_ACTION_PASS);
10909	case CTL_SER_BLOCKOPT:
10910		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10911		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10912			return (CTL_ACTION_BLOCK);
10913		return (CTL_ACTION_PASS);
10914	case CTL_SER_SKIP:
10915		return (CTL_ACTION_SKIP);
10916	default:
10917		panic("invalid serialization value %d",
10918		      serialize_row[pending_entry->seridx]);
10919	}
10920
10921	return (CTL_ACTION_ERROR);
10922}
10923
10924/*
10925 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10926 * Assumptions:
10927 * - pending_io is generally either incoming, or on the blocked queue
10928 * - starting I/O is the I/O we want to start the check with.
10929 */
10930static ctl_action
10931ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10932	      union ctl_io *starting_io)
10933{
10934	union ctl_io *ooa_io;
10935	ctl_action action;
10936
10937	mtx_assert(&lun->lun_lock, MA_OWNED);
10938
10939	/*
10940	 * Run back along the OOA queue, starting with the current
10941	 * blocked I/O and going through every I/O before it on the
10942	 * queue.  If starting_io is NULL, we'll just end up returning
10943	 * CTL_ACTION_PASS.
10944	 */
10945	for (ooa_io = starting_io; ooa_io != NULL;
10946	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10947	     ooa_links)){
10948
10949		/*
10950		 * This routine just checks to see whether
10951		 * cur_blocked is blocked by ooa_io, which is ahead
10952		 * of it in the queue.  It doesn't queue/dequeue
10953		 * cur_blocked.
10954		 */
10955		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10956		switch (action) {
10957		case CTL_ACTION_BLOCK:
10958		case CTL_ACTION_OVERLAP:
10959		case CTL_ACTION_OVERLAP_TAG:
10960		case CTL_ACTION_SKIP:
10961		case CTL_ACTION_ERROR:
10962			return (action);
10963			break; /* NOTREACHED */
10964		case CTL_ACTION_PASS:
10965			break;
10966		default:
10967			panic("invalid action %d", action);
10968			break;  /* NOTREACHED */
10969		}
10970	}
10971
10972	return (CTL_ACTION_PASS);
10973}
10974
10975/*
10976 * Assumptions:
10977 * - An I/O has just completed, and has been removed from the per-LUN OOA
10978 *   queue, so some items on the blocked queue may now be unblocked.
10979 */
10980static int
10981ctl_check_blocked(struct ctl_lun *lun)
10982{
10983	union ctl_io *cur_blocked, *next_blocked;
10984
10985	mtx_assert(&lun->lun_lock, MA_OWNED);
10986
10987	/*
10988	 * Run forward from the head of the blocked queue, checking each
10989	 * entry against the I/Os prior to it on the OOA queue to see if
10990	 * there is still any blockage.
10991	 *
10992	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10993	 * with our removing a variable on it while it is traversing the
10994	 * list.
10995	 */
10996	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10997	     cur_blocked != NULL; cur_blocked = next_blocked) {
10998		union ctl_io *prev_ooa;
10999		ctl_action action;
11000
11001		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11002							  blocked_links);
11003
11004		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11005						      ctl_ooaq, ooa_links);
11006
11007		/*
11008		 * If cur_blocked happens to be the first item in the OOA
11009		 * queue now, prev_ooa will be NULL, and the action
11010		 * returned will just be CTL_ACTION_PASS.
11011		 */
11012		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11013
11014		switch (action) {
11015		case CTL_ACTION_BLOCK:
11016			/* Nothing to do here, still blocked */
11017			break;
11018		case CTL_ACTION_OVERLAP:
11019		case CTL_ACTION_OVERLAP_TAG:
11020			/*
11021			 * This shouldn't happen!  In theory we've already
11022			 * checked this command for overlap...
11023			 */
11024			break;
11025		case CTL_ACTION_PASS:
11026		case CTL_ACTION_SKIP: {
11027			struct ctl_softc *softc;
11028			const struct ctl_cmd_entry *entry;
11029			uint32_t initidx;
11030			int isc_retval;
11031
11032			/*
11033			 * The skip case shouldn't happen, this transaction
11034			 * should have never made it onto the blocked queue.
11035			 */
11036			/*
11037			 * This I/O is no longer blocked, we can remove it
11038			 * from the blocked queue.  Since this is a TAILQ
11039			 * (doubly linked list), we can do O(1) removals
11040			 * from any place on the list.
11041			 */
11042			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11043				     blocked_links);
11044			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11045
11046			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11047				/*
11048				 * Need to send IO back to original side to
11049				 * run
11050				 */
11051				union ctl_ha_msg msg_info;
11052
11053				msg_info.hdr.original_sc =
11054					cur_blocked->io_hdr.original_sc;
11055				msg_info.hdr.serializing_sc = cur_blocked;
11056				msg_info.hdr.msg_type = CTL_MSG_R2R;
11057				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11058				     &msg_info, sizeof(msg_info), 0)) >
11059				     CTL_HA_STATUS_SUCCESS) {
11060					printf("CTL:Check Blocked error from "
11061					       "ctl_ha_msg_send %d\n",
11062					       isc_retval);
11063				}
11064				break;
11065			}
11066			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11067			softc = control_softc;
11068
11069			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11070
11071			/*
11072			 * Check this I/O for LUN state changes that may
11073			 * have happened while this command was blocked.
11074			 * The LUN state may have been changed by a command
11075			 * ahead of us in the queue, so we need to re-check
11076			 * for any states that can be caused by SCSI
11077			 * commands.
11078			 */
11079			if (ctl_scsiio_lun_check(softc, lun, entry,
11080						 &cur_blocked->scsiio) == 0) {
11081				cur_blocked->io_hdr.flags |=
11082				                      CTL_FLAG_IS_WAS_ON_RTR;
11083				ctl_enqueue_rtr(cur_blocked);
11084			} else
11085				ctl_done(cur_blocked);
11086			break;
11087		}
11088		default:
11089			/*
11090			 * This probably shouldn't happen -- we shouldn't
11091			 * get CTL_ACTION_ERROR, or anything else.
11092			 */
11093			break;
11094		}
11095	}
11096
11097	return (CTL_RETVAL_COMPLETE);
11098}
11099
11100/*
11101 * This routine (with one exception) checks LUN flags that can be set by
11102 * commands ahead of us in the OOA queue.  These flags have to be checked
11103 * when a command initially comes in, and when we pull a command off the
11104 * blocked queue and are preparing to execute it.  The reason we have to
11105 * check these flags for commands on the blocked queue is that the LUN
11106 * state may have been changed by a command ahead of us while we're on the
11107 * blocked queue.
11108 *
11109 * Ordering is somewhat important with these checks, so please pay
11110 * careful attention to the placement of any new checks.
11111 */
11112static int
11113ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11114    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11115{
11116	int retval;
11117	uint32_t residx;
11118
11119	retval = 0;
11120
11121	mtx_assert(&lun->lun_lock, MA_OWNED);
11122
11123	/*
11124	 * If this shelf is a secondary shelf controller, we have to reject
11125	 * any media access commands.
11126	 */
11127#if 0
11128	/* No longer needed for HA */
11129	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11130	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11131		ctl_set_lun_standby(ctsio);
11132		retval = 1;
11133		goto bailout;
11134	}
11135#endif
11136
11137	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11138		if (lun->flags & CTL_LUN_READONLY) {
11139			ctl_set_sense(ctsio, /*current_error*/ 1,
11140			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11141			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11142			retval = 1;
11143			goto bailout;
11144		}
11145		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11146		    .eca_and_aen & SCP_SWP) != 0) {
11147			ctl_set_sense(ctsio, /*current_error*/ 1,
11148			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11149			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11150			retval = 1;
11151			goto bailout;
11152		}
11153	}
11154
11155	/*
11156	 * Check for a reservation conflict.  If this command isn't allowed
11157	 * even on reserved LUNs, and if this initiator isn't the one who
11158	 * reserved us, reject the command with a reservation conflict.
11159	 */
11160	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11161	if ((lun->flags & CTL_LUN_RESERVED)
11162	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11163		if (lun->res_idx != residx) {
11164			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11165			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11166			retval = 1;
11167			goto bailout;
11168		}
11169	}
11170
11171	if ((lun->flags & CTL_LUN_PR_RESERVED)
11172	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11173		/*
11174		 * if we aren't registered or it's a res holder type
11175		 * reservation and this isn't the res holder then set a
11176		 * conflict.
11177		 * NOTE: Commands which might be allowed on write exclusive
11178		 * type reservations are checked in the particular command
11179		 * for a conflict. Read and SSU are the only ones.
11180		 */
11181		if (lun->pr_keys[residx] == 0
11182		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11183			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11184			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11185			retval = 1;
11186			goto bailout;
11187		}
11188
11189	}
11190
11191	if ((lun->flags & CTL_LUN_OFFLINE)
11192	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11193		ctl_set_lun_not_ready(ctsio);
11194		retval = 1;
11195		goto bailout;
11196	}
11197
11198	/*
11199	 * If the LUN is stopped, see if this particular command is allowed
11200	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11201	 */
11202	if ((lun->flags & CTL_LUN_STOPPED)
11203	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11204		/* "Logical unit not ready, initializing cmd. required" */
11205		ctl_set_lun_stopped(ctsio);
11206		retval = 1;
11207		goto bailout;
11208	}
11209
11210	if ((lun->flags & CTL_LUN_INOPERABLE)
11211	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11212		/* "Medium format corrupted" */
11213		ctl_set_medium_format_corrupted(ctsio);
11214		retval = 1;
11215		goto bailout;
11216	}
11217
11218bailout:
11219	return (retval);
11220
11221}
11222
11223static void
11224ctl_failover_io(union ctl_io *io, int have_lock)
11225{
11226	ctl_set_busy(&io->scsiio);
11227	ctl_done(io);
11228}
11229
11230static void
11231ctl_failover(void)
11232{
11233	struct ctl_lun *lun;
11234	struct ctl_softc *ctl_softc;
11235	union ctl_io *next_io, *pending_io;
11236	union ctl_io *io;
11237	int lun_idx;
11238	int i;
11239
11240	ctl_softc = control_softc;
11241
11242	mtx_lock(&ctl_softc->ctl_lock);
11243	/*
11244	 * Remove any cmds from the other SC from the rtr queue.  These
11245	 * will obviously only be for LUNs for which we're the primary.
11246	 * We can't send status or get/send data for these commands.
11247	 * Since they haven't been executed yet, we can just remove them.
11248	 * We'll either abort them or delete them below, depending on
11249	 * which HA mode we're in.
11250	 */
11251#ifdef notyet
11252	mtx_lock(&ctl_softc->queue_lock);
11253	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11254	     io != NULL; io = next_io) {
11255		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11256		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11257			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11258				      ctl_io_hdr, links);
11259	}
11260	mtx_unlock(&ctl_softc->queue_lock);
11261#endif
11262
11263	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11264		lun = ctl_softc->ctl_luns[lun_idx];
11265		if (lun==NULL)
11266			continue;
11267
11268		/*
11269		 * Processor LUNs are primary on both sides.
11270		 * XXX will this always be true?
11271		 */
11272		if (lun->be_lun->lun_type == T_PROCESSOR)
11273			continue;
11274
11275		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11276		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11277			printf("FAILOVER: primary lun %d\n", lun_idx);
11278		        /*
11279			 * Remove all commands from the other SC. First from the
11280			 * blocked queue then from the ooa queue. Once we have
11281			 * removed them. Call ctl_check_blocked to see if there
11282			 * is anything that can run.
11283			 */
11284			for (io = (union ctl_io *)TAILQ_FIRST(
11285			     &lun->blocked_queue); io != NULL; io = next_io) {
11286
11287		        	next_io = (union ctl_io *)TAILQ_NEXT(
11288				    &io->io_hdr, blocked_links);
11289
11290				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11291					TAILQ_REMOVE(&lun->blocked_queue,
11292						     &io->io_hdr,blocked_links);
11293					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11294					TAILQ_REMOVE(&lun->ooa_queue,
11295						     &io->io_hdr, ooa_links);
11296
11297					ctl_free_io(io);
11298				}
11299			}
11300
11301			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11302	     		     io != NULL; io = next_io) {
11303
11304		        	next_io = (union ctl_io *)TAILQ_NEXT(
11305				    &io->io_hdr, ooa_links);
11306
11307				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11308
11309					TAILQ_REMOVE(&lun->ooa_queue,
11310						&io->io_hdr,
11311					     	ooa_links);
11312
11313					ctl_free_io(io);
11314				}
11315			}
11316			ctl_check_blocked(lun);
11317		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11318			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11319
11320			printf("FAILOVER: primary lun %d\n", lun_idx);
11321			/*
11322			 * Abort all commands from the other SC.  We can't
11323			 * send status back for them now.  These should get
11324			 * cleaned up when they are completed or come out
11325			 * for a datamove operation.
11326			 */
11327			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11328	     		     io != NULL; io = next_io) {
11329		        	next_io = (union ctl_io *)TAILQ_NEXT(
11330					&io->io_hdr, ooa_links);
11331
11332				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11333					io->io_hdr.flags |= CTL_FLAG_ABORT;
11334			}
11335		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11336			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11337
11338			printf("FAILOVER: secondary lun %d\n", lun_idx);
11339
11340			lun->flags |= CTL_LUN_PRIMARY_SC;
11341
11342			/*
11343			 * We send all I/O that was sent to this controller
11344			 * and redirected to the other side back with
11345			 * busy status, and have the initiator retry it.
11346			 * Figuring out how much data has been transferred,
11347			 * etc. and picking up where we left off would be
11348			 * very tricky.
11349			 *
11350			 * XXX KDM need to remove I/O from the blocked
11351			 * queue as well!
11352			 */
11353			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11354			     &lun->ooa_queue); pending_io != NULL;
11355			     pending_io = next_io) {
11356
11357				next_io =  (union ctl_io *)TAILQ_NEXT(
11358					&pending_io->io_hdr, ooa_links);
11359
11360				pending_io->io_hdr.flags &=
11361					~CTL_FLAG_SENT_2OTHER_SC;
11362
11363				if (pending_io->io_hdr.flags &
11364				    CTL_FLAG_IO_ACTIVE) {
11365					pending_io->io_hdr.flags |=
11366						CTL_FLAG_FAILOVER;
11367				} else {
11368					ctl_set_busy(&pending_io->scsiio);
11369					ctl_done(pending_io);
11370				}
11371			}
11372
11373			/*
11374			 * Build Unit Attention
11375			 */
11376			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11377				lun->pending_ua[i] |=
11378				                     CTL_UA_ASYM_ACC_CHANGE;
11379			}
11380		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11381			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11382			printf("FAILOVER: secondary lun %d\n", lun_idx);
11383			/*
11384			 * if the first io on the OOA is not on the RtR queue
11385			 * add it.
11386			 */
11387			lun->flags |= CTL_LUN_PRIMARY_SC;
11388
11389			pending_io = (union ctl_io *)TAILQ_FIRST(
11390			    &lun->ooa_queue);
11391			if (pending_io==NULL) {
11392				printf("Nothing on OOA queue\n");
11393				continue;
11394			}
11395
11396			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11397			if ((pending_io->io_hdr.flags &
11398			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11399				pending_io->io_hdr.flags |=
11400				    CTL_FLAG_IS_WAS_ON_RTR;
11401				ctl_enqueue_rtr(pending_io);
11402			}
11403#if 0
11404			else
11405			{
11406				printf("Tag 0x%04x is running\n",
11407				      pending_io->scsiio.tag_num);
11408			}
11409#endif
11410
11411			next_io = (union ctl_io *)TAILQ_NEXT(
11412			    &pending_io->io_hdr, ooa_links);
11413			for (pending_io=next_io; pending_io != NULL;
11414			     pending_io = next_io) {
11415				pending_io->io_hdr.flags &=
11416				    ~CTL_FLAG_SENT_2OTHER_SC;
11417				next_io = (union ctl_io *)TAILQ_NEXT(
11418					&pending_io->io_hdr, ooa_links);
11419				if (pending_io->io_hdr.flags &
11420				    CTL_FLAG_IS_WAS_ON_RTR) {
11421#if 0
11422				        printf("Tag 0x%04x is running\n",
11423				      		pending_io->scsiio.tag_num);
11424#endif
11425					continue;
11426				}
11427
11428				switch (ctl_check_ooa(lun, pending_io,
11429			            (union ctl_io *)TAILQ_PREV(
11430				    &pending_io->io_hdr, ctl_ooaq,
11431				    ooa_links))) {
11432
11433				case CTL_ACTION_BLOCK:
11434					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11435							  &pending_io->io_hdr,
11436							  blocked_links);
11437					pending_io->io_hdr.flags |=
11438					    CTL_FLAG_BLOCKED;
11439					break;
11440				case CTL_ACTION_PASS:
11441				case CTL_ACTION_SKIP:
11442					pending_io->io_hdr.flags |=
11443					    CTL_FLAG_IS_WAS_ON_RTR;
11444					ctl_enqueue_rtr(pending_io);
11445					break;
11446				case CTL_ACTION_OVERLAP:
11447					ctl_set_overlapped_cmd(
11448					    (struct ctl_scsiio *)pending_io);
11449					ctl_done(pending_io);
11450					break;
11451				case CTL_ACTION_OVERLAP_TAG:
11452					ctl_set_overlapped_tag(
11453					    (struct ctl_scsiio *)pending_io,
11454					    pending_io->scsiio.tag_num & 0xff);
11455					ctl_done(pending_io);
11456					break;
11457				case CTL_ACTION_ERROR:
11458				default:
11459					ctl_set_internal_failure(
11460						(struct ctl_scsiio *)pending_io,
11461						0,  // sks_valid
11462						0); //retry count
11463					ctl_done(pending_io);
11464					break;
11465				}
11466			}
11467
11468			/*
11469			 * Build Unit Attention
11470			 */
11471			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11472				lun->pending_ua[i] |=
11473				                     CTL_UA_ASYM_ACC_CHANGE;
11474			}
11475		} else {
11476			panic("Unhandled HA mode failover, LUN flags = %#x, "
11477			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11478		}
11479	}
11480	ctl_pause_rtr = 0;
11481	mtx_unlock(&ctl_softc->ctl_lock);
11482}
11483
11484static int
11485ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11486{
11487	struct ctl_lun *lun;
11488	const struct ctl_cmd_entry *entry;
11489	uint32_t initidx, targ_lun;
11490	int retval;
11491
11492	retval = 0;
11493
11494	lun = NULL;
11495
11496	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11497	if ((targ_lun < CTL_MAX_LUNS)
11498	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11499		lun = ctl_softc->ctl_luns[targ_lun];
11500		/*
11501		 * If the LUN is invalid, pretend that it doesn't exist.
11502		 * It will go away as soon as all pending I/O has been
11503		 * completed.
11504		 */
11505		if (lun->flags & CTL_LUN_DISABLED) {
11506			lun = NULL;
11507		} else {
11508			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11509			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11510				lun->be_lun;
11511			if (lun->be_lun->lun_type == T_PROCESSOR) {
11512				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11513			}
11514
11515			/*
11516			 * Every I/O goes into the OOA queue for a
11517			 * particular LUN, and stays there until completion.
11518			 */
11519			mtx_lock(&lun->lun_lock);
11520			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11521			    ooa_links);
11522		}
11523	} else {
11524		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11525		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11526	}
11527
11528	/* Get command entry and return error if it is unsuppotyed. */
11529	entry = ctl_validate_command(ctsio);
11530	if (entry == NULL) {
11531		if (lun)
11532			mtx_unlock(&lun->lun_lock);
11533		return (retval);
11534	}
11535
11536	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11537	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11538
11539	/*
11540	 * Check to see whether we can send this command to LUNs that don't
11541	 * exist.  This should pretty much only be the case for inquiry
11542	 * and request sense.  Further checks, below, really require having
11543	 * a LUN, so we can't really check the command anymore.  Just put
11544	 * it on the rtr queue.
11545	 */
11546	if (lun == NULL) {
11547		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11548			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11549			ctl_enqueue_rtr((union ctl_io *)ctsio);
11550			return (retval);
11551		}
11552
11553		ctl_set_unsupported_lun(ctsio);
11554		ctl_done((union ctl_io *)ctsio);
11555		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11556		return (retval);
11557	} else {
11558		/*
11559		 * Make sure we support this particular command on this LUN.
11560		 * e.g., we don't support writes to the control LUN.
11561		 */
11562		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11563			mtx_unlock(&lun->lun_lock);
11564			ctl_set_invalid_opcode(ctsio);
11565			ctl_done((union ctl_io *)ctsio);
11566			return (retval);
11567		}
11568	}
11569
11570	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11571
11572#ifdef CTL_WITH_CA
11573	/*
11574	 * If we've got a request sense, it'll clear the contingent
11575	 * allegiance condition.  Otherwise, if we have a CA condition for
11576	 * this initiator, clear it, because it sent down a command other
11577	 * than request sense.
11578	 */
11579	if ((ctsio->cdb[0] != REQUEST_SENSE)
11580	 && (ctl_is_set(lun->have_ca, initidx)))
11581		ctl_clear_mask(lun->have_ca, initidx);
11582#endif
11583
11584	/*
11585	 * If the command has this flag set, it handles its own unit
11586	 * attention reporting, we shouldn't do anything.  Otherwise we
11587	 * check for any pending unit attentions, and send them back to the
11588	 * initiator.  We only do this when a command initially comes in,
11589	 * not when we pull it off the blocked queue.
11590	 *
11591	 * According to SAM-3, section 5.3.2, the order that things get
11592	 * presented back to the host is basically unit attentions caused
11593	 * by some sort of reset event, busy status, reservation conflicts
11594	 * or task set full, and finally any other status.
11595	 *
11596	 * One issue here is that some of the unit attentions we report
11597	 * don't fall into the "reset" category (e.g. "reported luns data
11598	 * has changed").  So reporting it here, before the reservation
11599	 * check, may be technically wrong.  I guess the only thing to do
11600	 * would be to check for and report the reset events here, and then
11601	 * check for the other unit attention types after we check for a
11602	 * reservation conflict.
11603	 *
11604	 * XXX KDM need to fix this
11605	 */
11606	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11607		ctl_ua_type ua_type;
11608
11609		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11610			scsi_sense_data_type sense_format;
11611
11612			if (lun != NULL)
11613				sense_format = (lun->flags &
11614				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11615				    SSD_TYPE_FIXED;
11616			else
11617				sense_format = SSD_TYPE_FIXED;
11618
11619			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11620			    &ctsio->sense_data, sense_format);
11621			if (ua_type != CTL_UA_NONE) {
11622				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11623				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11624						       CTL_AUTOSENSE;
11625				ctsio->sense_len = SSD_FULL_SIZE;
11626				mtx_unlock(&lun->lun_lock);
11627				ctl_done((union ctl_io *)ctsio);
11628				return (retval);
11629			}
11630		}
11631	}
11632
11633
11634	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11635		mtx_unlock(&lun->lun_lock);
11636		ctl_done((union ctl_io *)ctsio);
11637		return (retval);
11638	}
11639
11640	/*
11641	 * XXX CHD this is where we want to send IO to other side if
11642	 * this LUN is secondary on this SC. We will need to make a copy
11643	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11644	 * the copy we send as FROM_OTHER.
11645	 * We also need to stuff the address of the original IO so we can
11646	 * find it easily. Something similar will need be done on the other
11647	 * side so when we are done we can find the copy.
11648	 */
11649	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11650		union ctl_ha_msg msg_info;
11651		int isc_retval;
11652
11653		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11654
11655		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11656		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11657#if 0
11658		printf("1. ctsio %p\n", ctsio);
11659#endif
11660		msg_info.hdr.serializing_sc = NULL;
11661		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11662		msg_info.scsi.tag_num = ctsio->tag_num;
11663		msg_info.scsi.tag_type = ctsio->tag_type;
11664		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11665
11666		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11667
11668		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11669		    (void *)&msg_info, sizeof(msg_info), 0)) >
11670		    CTL_HA_STATUS_SUCCESS) {
11671			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11672			       isc_retval);
11673			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11674		} else {
11675#if 0
11676			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11677#endif
11678		}
11679
11680		/*
11681		 * XXX KDM this I/O is off the incoming queue, but hasn't
11682		 * been inserted on any other queue.  We may need to come
11683		 * up with a holding queue while we wait for serialization
11684		 * so that we have an idea of what we're waiting for from
11685		 * the other side.
11686		 */
11687		mtx_unlock(&lun->lun_lock);
11688		return (retval);
11689	}
11690
11691	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11692			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11693			      ctl_ooaq, ooa_links))) {
11694	case CTL_ACTION_BLOCK:
11695		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11696		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11697				  blocked_links);
11698		mtx_unlock(&lun->lun_lock);
11699		return (retval);
11700	case CTL_ACTION_PASS:
11701	case CTL_ACTION_SKIP:
11702		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11703		mtx_unlock(&lun->lun_lock);
11704		ctl_enqueue_rtr((union ctl_io *)ctsio);
11705		break;
11706	case CTL_ACTION_OVERLAP:
11707		mtx_unlock(&lun->lun_lock);
11708		ctl_set_overlapped_cmd(ctsio);
11709		ctl_done((union ctl_io *)ctsio);
11710		break;
11711	case CTL_ACTION_OVERLAP_TAG:
11712		mtx_unlock(&lun->lun_lock);
11713		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11714		ctl_done((union ctl_io *)ctsio);
11715		break;
11716	case CTL_ACTION_ERROR:
11717	default:
11718		mtx_unlock(&lun->lun_lock);
11719		ctl_set_internal_failure(ctsio,
11720					 /*sks_valid*/ 0,
11721					 /*retry_count*/ 0);
11722		ctl_done((union ctl_io *)ctsio);
11723		break;
11724	}
11725	return (retval);
11726}
11727
11728const struct ctl_cmd_entry *
11729ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11730{
11731	const struct ctl_cmd_entry *entry;
11732	int service_action;
11733
11734	entry = &ctl_cmd_table[ctsio->cdb[0]];
11735	if (sa)
11736		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11737	if (entry->flags & CTL_CMD_FLAG_SA5) {
11738		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11739		entry = &((const struct ctl_cmd_entry *)
11740		    entry->execute)[service_action];
11741	}
11742	return (entry);
11743}
11744
11745const struct ctl_cmd_entry *
11746ctl_validate_command(struct ctl_scsiio *ctsio)
11747{
11748	const struct ctl_cmd_entry *entry;
11749	int i, sa;
11750	uint8_t diff;
11751
11752	entry = ctl_get_cmd_entry(ctsio, &sa);
11753	if (entry->execute == NULL) {
11754		if (sa)
11755			ctl_set_invalid_field(ctsio,
11756					      /*sks_valid*/ 1,
11757					      /*command*/ 1,
11758					      /*field*/ 1,
11759					      /*bit_valid*/ 1,
11760					      /*bit*/ 4);
11761		else
11762			ctl_set_invalid_opcode(ctsio);
11763		ctl_done((union ctl_io *)ctsio);
11764		return (NULL);
11765	}
11766	KASSERT(entry->length > 0,
11767	    ("Not defined length for command 0x%02x/0x%02x",
11768	     ctsio->cdb[0], ctsio->cdb[1]));
11769	for (i = 1; i < entry->length; i++) {
11770		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11771		if (diff == 0)
11772			continue;
11773		ctl_set_invalid_field(ctsio,
11774				      /*sks_valid*/ 1,
11775				      /*command*/ 1,
11776				      /*field*/ i,
11777				      /*bit_valid*/ 1,
11778				      /*bit*/ fls(diff) - 1);
11779		ctl_done((union ctl_io *)ctsio);
11780		return (NULL);
11781	}
11782	return (entry);
11783}
11784
11785static int
11786ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11787{
11788
11789	switch (lun_type) {
11790	case T_PROCESSOR:
11791		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11792		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11793			return (0);
11794		break;
11795	case T_DIRECT:
11796		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11797		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11798			return (0);
11799		break;
11800	default:
11801		return (0);
11802	}
11803	return (1);
11804}
11805
11806static int
11807ctl_scsiio(struct ctl_scsiio *ctsio)
11808{
11809	int retval;
11810	const struct ctl_cmd_entry *entry;
11811
11812	retval = CTL_RETVAL_COMPLETE;
11813
11814	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11815
11816	entry = ctl_get_cmd_entry(ctsio, NULL);
11817
11818	/*
11819	 * If this I/O has been aborted, just send it straight to
11820	 * ctl_done() without executing it.
11821	 */
11822	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11823		ctl_done((union ctl_io *)ctsio);
11824		goto bailout;
11825	}
11826
11827	/*
11828	 * All the checks should have been handled by ctl_scsiio_precheck().
11829	 * We should be clear now to just execute the I/O.
11830	 */
11831	retval = entry->execute(ctsio);
11832
11833bailout:
11834	return (retval);
11835}
11836
11837/*
11838 * Since we only implement one target right now, a bus reset simply resets
11839 * our single target.
11840 */
11841static int
11842ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11843{
11844	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11845}
11846
11847static int
11848ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11849		 ctl_ua_type ua_type)
11850{
11851	struct ctl_lun *lun;
11852	int retval;
11853
11854	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11855		union ctl_ha_msg msg_info;
11856
11857		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11858		msg_info.hdr.nexus = io->io_hdr.nexus;
11859		if (ua_type==CTL_UA_TARG_RESET)
11860			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11861		else
11862			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11863		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11864		msg_info.hdr.original_sc = NULL;
11865		msg_info.hdr.serializing_sc = NULL;
11866		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11867		    (void *)&msg_info, sizeof(msg_info), 0)) {
11868		}
11869	}
11870	retval = 0;
11871
11872	mtx_lock(&ctl_softc->ctl_lock);
11873	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11874		retval += ctl_lun_reset(lun, io, ua_type);
11875	mtx_unlock(&ctl_softc->ctl_lock);
11876
11877	return (retval);
11878}
11879
11880/*
11881 * The LUN should always be set.  The I/O is optional, and is used to
11882 * distinguish between I/Os sent by this initiator, and by other
11883 * initiators.  We set unit attention for initiators other than this one.
11884 * SAM-3 is vague on this point.  It does say that a unit attention should
11885 * be established for other initiators when a LUN is reset (see section
11886 * 5.7.3), but it doesn't specifically say that the unit attention should
11887 * be established for this particular initiator when a LUN is reset.  Here
11888 * is the relevant text, from SAM-3 rev 8:
11889 *
11890 * 5.7.2 When a SCSI initiator port aborts its own tasks
11891 *
11892 * When a SCSI initiator port causes its own task(s) to be aborted, no
11893 * notification that the task(s) have been aborted shall be returned to
11894 * the SCSI initiator port other than the completion response for the
11895 * command or task management function action that caused the task(s) to
11896 * be aborted and notification(s) associated with related effects of the
11897 * action (e.g., a reset unit attention condition).
11898 *
11899 * XXX KDM for now, we're setting unit attention for all initiators.
11900 */
11901static int
11902ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11903{
11904	union ctl_io *xio;
11905#if 0
11906	uint32_t initindex;
11907#endif
11908	int i;
11909
11910	mtx_lock(&lun->lun_lock);
11911	/*
11912	 * Run through the OOA queue and abort each I/O.
11913	 */
11914#if 0
11915	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11916#endif
11917	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11918	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11919		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11920	}
11921
11922	/*
11923	 * This version sets unit attention for every
11924	 */
11925#if 0
11926	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11927	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11928		if (initindex == i)
11929			continue;
11930		lun->pending_ua[i] |= ua_type;
11931	}
11932#endif
11933
11934	/*
11935	 * A reset (any kind, really) clears reservations established with
11936	 * RESERVE/RELEASE.  It does not clear reservations established
11937	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11938	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11939	 * reservations made with the RESERVE/RELEASE commands, because
11940	 * those commands are obsolete in SPC-3.
11941	 */
11942	lun->flags &= ~CTL_LUN_RESERVED;
11943
11944	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11945#ifdef CTL_WITH_CA
11946		ctl_clear_mask(lun->have_ca, i);
11947#endif
11948		lun->pending_ua[i] |= ua_type;
11949	}
11950	mtx_unlock(&lun->lun_lock);
11951
11952	return (0);
11953}
11954
11955static void
11956ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11957    int other_sc)
11958{
11959	union ctl_io *xio;
11960
11961	mtx_assert(&lun->lun_lock, MA_OWNED);
11962
11963	/*
11964	 * Run through the OOA queue and attempt to find the given I/O.
11965	 * The target port, initiator ID, tag type and tag number have to
11966	 * match the values that we got from the initiator.  If we have an
11967	 * untagged command to abort, simply abort the first untagged command
11968	 * we come to.  We only allow one untagged command at a time of course.
11969	 */
11970	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11971	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11972
11973		if ((targ_port == UINT32_MAX ||
11974		     targ_port == xio->io_hdr.nexus.targ_port) &&
11975		    (init_id == UINT32_MAX ||
11976		     init_id == xio->io_hdr.nexus.initid.id)) {
11977			if (targ_port != xio->io_hdr.nexus.targ_port ||
11978			    init_id != xio->io_hdr.nexus.initid.id)
11979				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11980			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11981			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11982				union ctl_ha_msg msg_info;
11983
11984				msg_info.hdr.nexus = xio->io_hdr.nexus;
11985				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11986				msg_info.task.tag_num = xio->scsiio.tag_num;
11987				msg_info.task.tag_type = xio->scsiio.tag_type;
11988				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11989				msg_info.hdr.original_sc = NULL;
11990				msg_info.hdr.serializing_sc = NULL;
11991				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11992				    (void *)&msg_info, sizeof(msg_info), 0);
11993			}
11994		}
11995	}
11996}
11997
11998static int
11999ctl_abort_task_set(union ctl_io *io)
12000{
12001	struct ctl_softc *softc = control_softc;
12002	struct ctl_lun *lun;
12003	uint32_t targ_lun;
12004
12005	/*
12006	 * Look up the LUN.
12007	 */
12008	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12009	mtx_lock(&softc->ctl_lock);
12010	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12011		lun = softc->ctl_luns[targ_lun];
12012	else {
12013		mtx_unlock(&softc->ctl_lock);
12014		return (1);
12015	}
12016
12017	mtx_lock(&lun->lun_lock);
12018	mtx_unlock(&softc->ctl_lock);
12019	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12020		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12021		    io->io_hdr.nexus.initid.id,
12022		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12023	} else { /* CTL_TASK_CLEAR_TASK_SET */
12024		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12025		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12026	}
12027	mtx_unlock(&lun->lun_lock);
12028	return (0);
12029}
12030
12031static int
12032ctl_i_t_nexus_reset(union ctl_io *io)
12033{
12034	struct ctl_softc *softc = control_softc;
12035	struct ctl_lun *lun;
12036	uint32_t initindex, residx;
12037
12038	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12039	residx = ctl_get_resindex(&io->io_hdr.nexus);
12040	mtx_lock(&softc->ctl_lock);
12041	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12042		mtx_lock(&lun->lun_lock);
12043		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12044		    io->io_hdr.nexus.initid.id,
12045		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12046#ifdef CTL_WITH_CA
12047		ctl_clear_mask(lun->have_ca, initindex);
12048#endif
12049		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12050			lun->flags &= ~CTL_LUN_RESERVED;
12051		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12052		mtx_unlock(&lun->lun_lock);
12053	}
12054	mtx_unlock(&softc->ctl_lock);
12055	return (0);
12056}
12057
12058static int
12059ctl_abort_task(union ctl_io *io)
12060{
12061	union ctl_io *xio;
12062	struct ctl_lun *lun;
12063	struct ctl_softc *ctl_softc;
12064#if 0
12065	struct sbuf sb;
12066	char printbuf[128];
12067#endif
12068	int found;
12069	uint32_t targ_lun;
12070
12071	ctl_softc = control_softc;
12072	found = 0;
12073
12074	/*
12075	 * Look up the LUN.
12076	 */
12077	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12078	mtx_lock(&ctl_softc->ctl_lock);
12079	if ((targ_lun < CTL_MAX_LUNS)
12080	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12081		lun = ctl_softc->ctl_luns[targ_lun];
12082	else {
12083		mtx_unlock(&ctl_softc->ctl_lock);
12084		return (1);
12085	}
12086
12087#if 0
12088	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12089	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12090#endif
12091
12092	mtx_lock(&lun->lun_lock);
12093	mtx_unlock(&ctl_softc->ctl_lock);
12094	/*
12095	 * Run through the OOA queue and attempt to find the given I/O.
12096	 * The target port, initiator ID, tag type and tag number have to
12097	 * match the values that we got from the initiator.  If we have an
12098	 * untagged command to abort, simply abort the first untagged command
12099	 * we come to.  We only allow one untagged command at a time of course.
12100	 */
12101#if 0
12102	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12103#endif
12104	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12105	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12106#if 0
12107		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12108
12109		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12110			    lun->lun, xio->scsiio.tag_num,
12111			    xio->scsiio.tag_type,
12112			    (xio->io_hdr.blocked_links.tqe_prev
12113			    == NULL) ? "" : " BLOCKED",
12114			    (xio->io_hdr.flags &
12115			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12116			    (xio->io_hdr.flags &
12117			    CTL_FLAG_ABORT) ? " ABORT" : "",
12118			    (xio->io_hdr.flags &
12119			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12120		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12121		sbuf_finish(&sb);
12122		printf("%s\n", sbuf_data(&sb));
12123#endif
12124
12125		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12126		 && (xio->io_hdr.nexus.initid.id ==
12127		     io->io_hdr.nexus.initid.id)) {
12128			/*
12129			 * If the abort says that the task is untagged, the
12130			 * task in the queue must be untagged.  Otherwise,
12131			 * we just check to see whether the tag numbers
12132			 * match.  This is because the QLogic firmware
12133			 * doesn't pass back the tag type in an abort
12134			 * request.
12135			 */
12136#if 0
12137			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12138			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12139			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12140#endif
12141			/*
12142			 * XXX KDM we've got problems with FC, because it
12143			 * doesn't send down a tag type with aborts.  So we
12144			 * can only really go by the tag number...
12145			 * This may cause problems with parallel SCSI.
12146			 * Need to figure that out!!
12147			 */
12148			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12149				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12150				found = 1;
12151				if ((io->io_hdr.flags &
12152				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12153				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12154					union ctl_ha_msg msg_info;
12155
12156					io->io_hdr.flags |=
12157					                CTL_FLAG_SENT_2OTHER_SC;
12158					msg_info.hdr.nexus = io->io_hdr.nexus;
12159					msg_info.task.task_action =
12160						CTL_TASK_ABORT_TASK;
12161					msg_info.task.tag_num =
12162						io->taskio.tag_num;
12163					msg_info.task.tag_type =
12164						io->taskio.tag_type;
12165					msg_info.hdr.msg_type =
12166						CTL_MSG_MANAGE_TASKS;
12167					msg_info.hdr.original_sc = NULL;
12168					msg_info.hdr.serializing_sc = NULL;
12169#if 0
12170					printf("Sent Abort to other side\n");
12171#endif
12172					if (CTL_HA_STATUS_SUCCESS !=
12173					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12174		    				(void *)&msg_info,
12175						sizeof(msg_info), 0)) {
12176					}
12177				}
12178#if 0
12179				printf("ctl_abort_task: found I/O to abort\n");
12180#endif
12181				break;
12182			}
12183		}
12184	}
12185	mtx_unlock(&lun->lun_lock);
12186
12187	if (found == 0) {
12188		/*
12189		 * This isn't really an error.  It's entirely possible for
12190		 * the abort and command completion to cross on the wire.
12191		 * This is more of an informative/diagnostic error.
12192		 */
12193#if 0
12194		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12195		       "%d:%d:%d:%d tag %d type %d\n",
12196		       io->io_hdr.nexus.initid.id,
12197		       io->io_hdr.nexus.targ_port,
12198		       io->io_hdr.nexus.targ_target.id,
12199		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12200		       io->taskio.tag_type);
12201#endif
12202	}
12203	return (0);
12204}
12205
12206static void
12207ctl_run_task(union ctl_io *io)
12208{
12209	struct ctl_softc *ctl_softc = control_softc;
12210	int retval = 1;
12211	const char *task_desc;
12212
12213	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12214
12215	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12216	    ("ctl_run_task: Unextected io_type %d\n",
12217	     io->io_hdr.io_type));
12218
12219	task_desc = ctl_scsi_task_string(&io->taskio);
12220	if (task_desc != NULL) {
12221#ifdef NEEDTOPORT
12222		csevent_log(CSC_CTL | CSC_SHELF_SW |
12223			    CTL_TASK_REPORT,
12224			    csevent_LogType_Trace,
12225			    csevent_Severity_Information,
12226			    csevent_AlertLevel_Green,
12227			    csevent_FRU_Firmware,
12228			    csevent_FRU_Unknown,
12229			    "CTL: received task: %s",task_desc);
12230#endif
12231	} else {
12232#ifdef NEEDTOPORT
12233		csevent_log(CSC_CTL | CSC_SHELF_SW |
12234			    CTL_TASK_REPORT,
12235			    csevent_LogType_Trace,
12236			    csevent_Severity_Information,
12237			    csevent_AlertLevel_Green,
12238			    csevent_FRU_Firmware,
12239			    csevent_FRU_Unknown,
12240			    "CTL: received unknown task "
12241			    "type: %d (%#x)",
12242			    io->taskio.task_action,
12243			    io->taskio.task_action);
12244#endif
12245	}
12246	switch (io->taskio.task_action) {
12247	case CTL_TASK_ABORT_TASK:
12248		retval = ctl_abort_task(io);
12249		break;
12250	case CTL_TASK_ABORT_TASK_SET:
12251	case CTL_TASK_CLEAR_TASK_SET:
12252		retval = ctl_abort_task_set(io);
12253		break;
12254	case CTL_TASK_CLEAR_ACA:
12255		break;
12256	case CTL_TASK_I_T_NEXUS_RESET:
12257		retval = ctl_i_t_nexus_reset(io);
12258		break;
12259	case CTL_TASK_LUN_RESET: {
12260		struct ctl_lun *lun;
12261		uint32_t targ_lun;
12262
12263		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12264		mtx_lock(&ctl_softc->ctl_lock);
12265		if ((targ_lun < CTL_MAX_LUNS)
12266		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12267			lun = ctl_softc->ctl_luns[targ_lun];
12268		else {
12269			mtx_unlock(&ctl_softc->ctl_lock);
12270			retval = 1;
12271			break;
12272		}
12273
12274		if (!(io->io_hdr.flags &
12275		    CTL_FLAG_FROM_OTHER_SC)) {
12276			union ctl_ha_msg msg_info;
12277
12278			io->io_hdr.flags |=
12279				CTL_FLAG_SENT_2OTHER_SC;
12280			msg_info.hdr.msg_type =
12281				CTL_MSG_MANAGE_TASKS;
12282			msg_info.hdr.nexus = io->io_hdr.nexus;
12283			msg_info.task.task_action =
12284				CTL_TASK_LUN_RESET;
12285			msg_info.hdr.original_sc = NULL;
12286			msg_info.hdr.serializing_sc = NULL;
12287			if (CTL_HA_STATUS_SUCCESS !=
12288			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12289			    (void *)&msg_info,
12290			    sizeof(msg_info), 0)) {
12291			}
12292		}
12293
12294		retval = ctl_lun_reset(lun, io,
12295				       CTL_UA_LUN_RESET);
12296		mtx_unlock(&ctl_softc->ctl_lock);
12297		break;
12298	}
12299	case CTL_TASK_TARGET_RESET:
12300		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12301		break;
12302	case CTL_TASK_BUS_RESET:
12303		retval = ctl_bus_reset(ctl_softc, io);
12304		break;
12305	case CTL_TASK_PORT_LOGIN:
12306		break;
12307	case CTL_TASK_PORT_LOGOUT:
12308		break;
12309	default:
12310		printf("ctl_run_task: got unknown task management event %d\n",
12311		       io->taskio.task_action);
12312		break;
12313	}
12314	if (retval == 0)
12315		io->io_hdr.status = CTL_SUCCESS;
12316	else
12317		io->io_hdr.status = CTL_ERROR;
12318	ctl_done(io);
12319}
12320
12321/*
12322 * For HA operation.  Handle commands that come in from the other
12323 * controller.
12324 */
12325static void
12326ctl_handle_isc(union ctl_io *io)
12327{
12328	int free_io;
12329	struct ctl_lun *lun;
12330	struct ctl_softc *ctl_softc;
12331	uint32_t targ_lun;
12332
12333	ctl_softc = control_softc;
12334
12335	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12336	lun = ctl_softc->ctl_luns[targ_lun];
12337
12338	switch (io->io_hdr.msg_type) {
12339	case CTL_MSG_SERIALIZE:
12340		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12341		break;
12342	case CTL_MSG_R2R: {
12343		const struct ctl_cmd_entry *entry;
12344
12345		/*
12346		 * This is only used in SER_ONLY mode.
12347		 */
12348		free_io = 0;
12349		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12350		mtx_lock(&lun->lun_lock);
12351		if (ctl_scsiio_lun_check(ctl_softc, lun,
12352		    entry, (struct ctl_scsiio *)io) != 0) {
12353			mtx_unlock(&lun->lun_lock);
12354			ctl_done(io);
12355			break;
12356		}
12357		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12358		mtx_unlock(&lun->lun_lock);
12359		ctl_enqueue_rtr(io);
12360		break;
12361	}
12362	case CTL_MSG_FINISH_IO:
12363		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12364			free_io = 0;
12365			ctl_done(io);
12366		} else {
12367			free_io = 1;
12368			mtx_lock(&lun->lun_lock);
12369			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12370				     ooa_links);
12371			ctl_check_blocked(lun);
12372			mtx_unlock(&lun->lun_lock);
12373		}
12374		break;
12375	case CTL_MSG_PERS_ACTION:
12376		ctl_hndl_per_res_out_on_other_sc(
12377			(union ctl_ha_msg *)&io->presio.pr_msg);
12378		free_io = 1;
12379		break;
12380	case CTL_MSG_BAD_JUJU:
12381		free_io = 0;
12382		ctl_done(io);
12383		break;
12384	case CTL_MSG_DATAMOVE:
12385		/* Only used in XFER mode */
12386		free_io = 0;
12387		ctl_datamove_remote(io);
12388		break;
12389	case CTL_MSG_DATAMOVE_DONE:
12390		/* Only used in XFER mode */
12391		free_io = 0;
12392		io->scsiio.be_move_done(io);
12393		break;
12394	default:
12395		free_io = 1;
12396		printf("%s: Invalid message type %d\n",
12397		       __func__, io->io_hdr.msg_type);
12398		break;
12399	}
12400	if (free_io)
12401		ctl_free_io(io);
12402
12403}
12404
12405
12406/*
12407 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12408 * there is no match.
12409 */
12410static ctl_lun_error_pattern
12411ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12412{
12413	const struct ctl_cmd_entry *entry;
12414	ctl_lun_error_pattern filtered_pattern, pattern;
12415
12416	pattern = desc->error_pattern;
12417
12418	/*
12419	 * XXX KDM we need more data passed into this function to match a
12420	 * custom pattern, and we actually need to implement custom pattern
12421	 * matching.
12422	 */
12423	if (pattern & CTL_LUN_PAT_CMD)
12424		return (CTL_LUN_PAT_CMD);
12425
12426	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12427		return (CTL_LUN_PAT_ANY);
12428
12429	entry = ctl_get_cmd_entry(ctsio, NULL);
12430
12431	filtered_pattern = entry->pattern & pattern;
12432
12433	/*
12434	 * If the user requested specific flags in the pattern (e.g.
12435	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12436	 * flags.
12437	 *
12438	 * If the user did not specify any flags, it doesn't matter whether
12439	 * or not the command supports the flags.
12440	 */
12441	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12442	     (pattern & ~CTL_LUN_PAT_MASK))
12443		return (CTL_LUN_PAT_NONE);
12444
12445	/*
12446	 * If the user asked for a range check, see if the requested LBA
12447	 * range overlaps with this command's LBA range.
12448	 */
12449	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12450		uint64_t lba1;
12451		uint64_t len1;
12452		ctl_action action;
12453		int retval;
12454
12455		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12456		if (retval != 0)
12457			return (CTL_LUN_PAT_NONE);
12458
12459		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12460					      desc->lba_range.len);
12461		/*
12462		 * A "pass" means that the LBA ranges don't overlap, so
12463		 * this doesn't match the user's range criteria.
12464		 */
12465		if (action == CTL_ACTION_PASS)
12466			return (CTL_LUN_PAT_NONE);
12467	}
12468
12469	return (filtered_pattern);
12470}
12471
12472static void
12473ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12474{
12475	struct ctl_error_desc *desc, *desc2;
12476
12477	mtx_assert(&lun->lun_lock, MA_OWNED);
12478
12479	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12480		ctl_lun_error_pattern pattern;
12481		/*
12482		 * Check to see whether this particular command matches
12483		 * the pattern in the descriptor.
12484		 */
12485		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12486		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12487			continue;
12488
12489		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12490		case CTL_LUN_INJ_ABORTED:
12491			ctl_set_aborted(&io->scsiio);
12492			break;
12493		case CTL_LUN_INJ_MEDIUM_ERR:
12494			ctl_set_medium_error(&io->scsiio);
12495			break;
12496		case CTL_LUN_INJ_UA:
12497			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12498			 * OCCURRED */
12499			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12500			break;
12501		case CTL_LUN_INJ_CUSTOM:
12502			/*
12503			 * We're assuming the user knows what he is doing.
12504			 * Just copy the sense information without doing
12505			 * checks.
12506			 */
12507			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12508			      ctl_min(sizeof(desc->custom_sense),
12509				      sizeof(io->scsiio.sense_data)));
12510			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12511			io->scsiio.sense_len = SSD_FULL_SIZE;
12512			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12513			break;
12514		case CTL_LUN_INJ_NONE:
12515		default:
12516			/*
12517			 * If this is an error injection type we don't know
12518			 * about, clear the continuous flag (if it is set)
12519			 * so it will get deleted below.
12520			 */
12521			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12522			break;
12523		}
12524		/*
12525		 * By default, each error injection action is a one-shot
12526		 */
12527		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12528			continue;
12529
12530		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12531
12532		free(desc, M_CTL);
12533	}
12534}
12535
12536#ifdef CTL_IO_DELAY
12537static void
12538ctl_datamove_timer_wakeup(void *arg)
12539{
12540	union ctl_io *io;
12541
12542	io = (union ctl_io *)arg;
12543
12544	ctl_datamove(io);
12545}
12546#endif /* CTL_IO_DELAY */
12547
12548void
12549ctl_datamove(union ctl_io *io)
12550{
12551	void (*fe_datamove)(union ctl_io *io);
12552
12553	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12554
12555	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12556
12557#ifdef CTL_TIME_IO
12558	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12559		char str[256];
12560		char path_str[64];
12561		struct sbuf sb;
12562
12563		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12564		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12565
12566		sbuf_cat(&sb, path_str);
12567		switch (io->io_hdr.io_type) {
12568		case CTL_IO_SCSI:
12569			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12570			sbuf_printf(&sb, "\n");
12571			sbuf_cat(&sb, path_str);
12572			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12573				    io->scsiio.tag_num, io->scsiio.tag_type);
12574			break;
12575		case CTL_IO_TASK:
12576			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12577				    "Tag Type: %d\n", io->taskio.task_action,
12578				    io->taskio.tag_num, io->taskio.tag_type);
12579			break;
12580		default:
12581			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12582			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12583			break;
12584		}
12585		sbuf_cat(&sb, path_str);
12586		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12587			    (intmax_t)time_uptime - io->io_hdr.start_time);
12588		sbuf_finish(&sb);
12589		printf("%s", sbuf_data(&sb));
12590	}
12591#endif /* CTL_TIME_IO */
12592
12593#ifdef CTL_IO_DELAY
12594	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12595		struct ctl_lun *lun;
12596
12597		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12598
12599		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12600	} else {
12601		struct ctl_lun *lun;
12602
12603		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12604		if ((lun != NULL)
12605		 && (lun->delay_info.datamove_delay > 0)) {
12606			struct callout *callout;
12607
12608			callout = (struct callout *)&io->io_hdr.timer_bytes;
12609			callout_init(callout, /*mpsafe*/ 1);
12610			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12611			callout_reset(callout,
12612				      lun->delay_info.datamove_delay * hz,
12613				      ctl_datamove_timer_wakeup, io);
12614			if (lun->delay_info.datamove_type ==
12615			    CTL_DELAY_TYPE_ONESHOT)
12616				lun->delay_info.datamove_delay = 0;
12617			return;
12618		}
12619	}
12620#endif
12621
12622	/*
12623	 * This command has been aborted.  Set the port status, so we fail
12624	 * the data move.
12625	 */
12626	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12627		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12628		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12629		       io->io_hdr.nexus.targ_port,
12630		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12631		       io->io_hdr.nexus.targ_lun);
12632		io->io_hdr.port_status = 31337;
12633		/*
12634		 * Note that the backend, in this case, will get the
12635		 * callback in its context.  In other cases it may get
12636		 * called in the frontend's interrupt thread context.
12637		 */
12638		io->scsiio.be_move_done(io);
12639		return;
12640	}
12641
12642	/* Don't confuse frontend with zero length data move. */
12643	if (io->scsiio.kern_data_len == 0) {
12644		io->scsiio.be_move_done(io);
12645		return;
12646	}
12647
12648	/*
12649	 * If we're in XFER mode and this I/O is from the other shelf
12650	 * controller, we need to send the DMA to the other side to
12651	 * actually transfer the data to/from the host.  In serialize only
12652	 * mode the transfer happens below CTL and ctl_datamove() is only
12653	 * called on the machine that originally received the I/O.
12654	 */
12655	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12656	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12657		union ctl_ha_msg msg;
12658		uint32_t sg_entries_sent;
12659		int do_sg_copy;
12660		int i;
12661
12662		memset(&msg, 0, sizeof(msg));
12663		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12664		msg.hdr.original_sc = io->io_hdr.original_sc;
12665		msg.hdr.serializing_sc = io;
12666		msg.hdr.nexus = io->io_hdr.nexus;
12667		msg.dt.flags = io->io_hdr.flags;
12668		/*
12669		 * We convert everything into a S/G list here.  We can't
12670		 * pass by reference, only by value between controllers.
12671		 * So we can't pass a pointer to the S/G list, only as many
12672		 * S/G entries as we can fit in here.  If it's possible for
12673		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12674		 * then we need to break this up into multiple transfers.
12675		 */
12676		if (io->scsiio.kern_sg_entries == 0) {
12677			msg.dt.kern_sg_entries = 1;
12678			/*
12679			 * If this is in cached memory, flush the cache
12680			 * before we send the DMA request to the other
12681			 * controller.  We want to do this in either the
12682			 * read or the write case.  The read case is
12683			 * straightforward.  In the write case, we want to
12684			 * make sure nothing is in the local cache that
12685			 * could overwrite the DMAed data.
12686			 */
12687			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12688				/*
12689				 * XXX KDM use bus_dmamap_sync() here.
12690				 */
12691			}
12692
12693			/*
12694			 * Convert to a physical address if this is a
12695			 * virtual address.
12696			 */
12697			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12698				msg.dt.sg_list[0].addr =
12699					io->scsiio.kern_data_ptr;
12700			} else {
12701				/*
12702				 * XXX KDM use busdma here!
12703				 */
12704#if 0
12705				msg.dt.sg_list[0].addr = (void *)
12706					vtophys(io->scsiio.kern_data_ptr);
12707#endif
12708			}
12709
12710			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12711			do_sg_copy = 0;
12712		} else {
12713			struct ctl_sg_entry *sgl;
12714
12715			do_sg_copy = 1;
12716			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12717			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12718			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12719				/*
12720				 * XXX KDM use bus_dmamap_sync() here.
12721				 */
12722			}
12723		}
12724
12725		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12726		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12727		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12728		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12729		msg.dt.sg_sequence = 0;
12730
12731		/*
12732		 * Loop until we've sent all of the S/G entries.  On the
12733		 * other end, we'll recompose these S/G entries into one
12734		 * contiguous list before passing it to the
12735		 */
12736		for (sg_entries_sent = 0; sg_entries_sent <
12737		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12738			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12739				sizeof(msg.dt.sg_list[0])),
12740				msg.dt.kern_sg_entries - sg_entries_sent);
12741
12742			if (do_sg_copy != 0) {
12743				struct ctl_sg_entry *sgl;
12744				int j;
12745
12746				sgl = (struct ctl_sg_entry *)
12747					io->scsiio.kern_data_ptr;
12748				/*
12749				 * If this is in cached memory, flush the cache
12750				 * before we send the DMA request to the other
12751				 * controller.  We want to do this in either
12752				 * the * read or the write case.  The read
12753				 * case is straightforward.  In the write
12754				 * case, we want to make sure nothing is
12755				 * in the local cache that could overwrite
12756				 * the DMAed data.
12757				 */
12758
12759				for (i = sg_entries_sent, j = 0;
12760				     i < msg.dt.cur_sg_entries; i++, j++) {
12761					if ((io->io_hdr.flags &
12762					     CTL_FLAG_NO_DATASYNC) == 0) {
12763						/*
12764						 * XXX KDM use bus_dmamap_sync()
12765						 */
12766					}
12767					if ((io->io_hdr.flags &
12768					     CTL_FLAG_BUS_ADDR) == 0) {
12769						/*
12770						 * XXX KDM use busdma.
12771						 */
12772#if 0
12773						msg.dt.sg_list[j].addr =(void *)
12774						       vtophys(sgl[i].addr);
12775#endif
12776					} else {
12777						msg.dt.sg_list[j].addr =
12778							sgl[i].addr;
12779					}
12780					msg.dt.sg_list[j].len = sgl[i].len;
12781				}
12782			}
12783
12784			sg_entries_sent += msg.dt.cur_sg_entries;
12785			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12786				msg.dt.sg_last = 1;
12787			else
12788				msg.dt.sg_last = 0;
12789
12790			/*
12791			 * XXX KDM drop and reacquire the lock here?
12792			 */
12793			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12794			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12795				/*
12796				 * XXX do something here.
12797				 */
12798			}
12799
12800			msg.dt.sent_sg_entries = sg_entries_sent;
12801		}
12802		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12803		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12804			ctl_failover_io(io, /*have_lock*/ 0);
12805
12806	} else {
12807
12808		/*
12809		 * Lookup the fe_datamove() function for this particular
12810		 * front end.
12811		 */
12812		fe_datamove =
12813		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12814
12815		fe_datamove(io);
12816	}
12817}
12818
12819static void
12820ctl_send_datamove_done(union ctl_io *io, int have_lock)
12821{
12822	union ctl_ha_msg msg;
12823	int isc_status;
12824
12825	memset(&msg, 0, sizeof(msg));
12826
12827	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12828	msg.hdr.original_sc = io;
12829	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12830	msg.hdr.nexus = io->io_hdr.nexus;
12831	msg.hdr.status = io->io_hdr.status;
12832	msg.scsi.tag_num = io->scsiio.tag_num;
12833	msg.scsi.tag_type = io->scsiio.tag_type;
12834	msg.scsi.scsi_status = io->scsiio.scsi_status;
12835	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12836	       sizeof(io->scsiio.sense_data));
12837	msg.scsi.sense_len = io->scsiio.sense_len;
12838	msg.scsi.sense_residual = io->scsiio.sense_residual;
12839	msg.scsi.fetd_status = io->io_hdr.port_status;
12840	msg.scsi.residual = io->scsiio.residual;
12841	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12842
12843	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12844		ctl_failover_io(io, /*have_lock*/ have_lock);
12845		return;
12846	}
12847
12848	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12849	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12850		/* XXX do something if this fails */
12851	}
12852
12853}
12854
12855/*
12856 * The DMA to the remote side is done, now we need to tell the other side
12857 * we're done so it can continue with its data movement.
12858 */
12859static void
12860ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12861{
12862	union ctl_io *io;
12863
12864	io = rq->context;
12865
12866	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12867		printf("%s: ISC DMA write failed with error %d", __func__,
12868		       rq->ret);
12869		ctl_set_internal_failure(&io->scsiio,
12870					 /*sks_valid*/ 1,
12871					 /*retry_count*/ rq->ret);
12872	}
12873
12874	ctl_dt_req_free(rq);
12875
12876	/*
12877	 * In this case, we had to malloc the memory locally.  Free it.
12878	 */
12879	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12880		int i;
12881		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12882			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12883	}
12884	/*
12885	 * The data is in local and remote memory, so now we need to send
12886	 * status (good or back) back to the other side.
12887	 */
12888	ctl_send_datamove_done(io, /*have_lock*/ 0);
12889}
12890
12891/*
12892 * We've moved the data from the host/controller into local memory.  Now we
12893 * need to push it over to the remote controller's memory.
12894 */
12895static int
12896ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12897{
12898	int retval;
12899
12900	retval = 0;
12901
12902	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12903					  ctl_datamove_remote_write_cb);
12904
12905	return (retval);
12906}
12907
12908static void
12909ctl_datamove_remote_write(union ctl_io *io)
12910{
12911	int retval;
12912	void (*fe_datamove)(union ctl_io *io);
12913
12914	/*
12915	 * - Get the data from the host/HBA into local memory.
12916	 * - DMA memory from the local controller to the remote controller.
12917	 * - Send status back to the remote controller.
12918	 */
12919
12920	retval = ctl_datamove_remote_sgl_setup(io);
12921	if (retval != 0)
12922		return;
12923
12924	/* Switch the pointer over so the FETD knows what to do */
12925	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12926
12927	/*
12928	 * Use a custom move done callback, since we need to send completion
12929	 * back to the other controller, not to the backend on this side.
12930	 */
12931	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12932
12933	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12934
12935	fe_datamove(io);
12936
12937	return;
12938
12939}
12940
12941static int
12942ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12943{
12944#if 0
12945	char str[256];
12946	char path_str[64];
12947	struct sbuf sb;
12948#endif
12949
12950	/*
12951	 * In this case, we had to malloc the memory locally.  Free it.
12952	 */
12953	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12954		int i;
12955		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12956			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12957	}
12958
12959#if 0
12960	scsi_path_string(io, path_str, sizeof(path_str));
12961	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12962	sbuf_cat(&sb, path_str);
12963	scsi_command_string(&io->scsiio, NULL, &sb);
12964	sbuf_printf(&sb, "\n");
12965	sbuf_cat(&sb, path_str);
12966	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12967		    io->scsiio.tag_num, io->scsiio.tag_type);
12968	sbuf_cat(&sb, path_str);
12969	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12970		    io->io_hdr.flags, io->io_hdr.status);
12971	sbuf_finish(&sb);
12972	printk("%s", sbuf_data(&sb));
12973#endif
12974
12975
12976	/*
12977	 * The read is done, now we need to send status (good or bad) back
12978	 * to the other side.
12979	 */
12980	ctl_send_datamove_done(io, /*have_lock*/ 0);
12981
12982	return (0);
12983}
12984
12985static void
12986ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12987{
12988	union ctl_io *io;
12989	void (*fe_datamove)(union ctl_io *io);
12990
12991	io = rq->context;
12992
12993	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12994		printf("%s: ISC DMA read failed with error %d", __func__,
12995		       rq->ret);
12996		ctl_set_internal_failure(&io->scsiio,
12997					 /*sks_valid*/ 1,
12998					 /*retry_count*/ rq->ret);
12999	}
13000
13001	ctl_dt_req_free(rq);
13002
13003	/* Switch the pointer over so the FETD knows what to do */
13004	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13005
13006	/*
13007	 * Use a custom move done callback, since we need to send completion
13008	 * back to the other controller, not to the backend on this side.
13009	 */
13010	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13011
13012	/* XXX KDM add checks like the ones in ctl_datamove? */
13013
13014	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13015
13016	fe_datamove(io);
13017}
13018
13019static int
13020ctl_datamove_remote_sgl_setup(union ctl_io *io)
13021{
13022	struct ctl_sg_entry *local_sglist, *remote_sglist;
13023	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13024	struct ctl_softc *softc;
13025	int retval;
13026	int i;
13027
13028	retval = 0;
13029	softc = control_softc;
13030
13031	local_sglist = io->io_hdr.local_sglist;
13032	local_dma_sglist = io->io_hdr.local_dma_sglist;
13033	remote_sglist = io->io_hdr.remote_sglist;
13034	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13035
13036	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13037		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13038			local_sglist[i].len = remote_sglist[i].len;
13039
13040			/*
13041			 * XXX Detect the situation where the RS-level I/O
13042			 * redirector on the other side has already read the
13043			 * data off of the AOR RS on this side, and
13044			 * transferred it to remote (mirror) memory on the
13045			 * other side.  Since we already have the data in
13046			 * memory here, we just need to use it.
13047			 *
13048			 * XXX KDM this can probably be removed once we
13049			 * get the cache device code in and take the
13050			 * current AOR implementation out.
13051			 */
13052#ifdef NEEDTOPORT
13053			if ((remote_sglist[i].addr >=
13054			     (void *)vtophys(softc->mirr->addr))
13055			 && (remote_sglist[i].addr <
13056			     ((void *)vtophys(softc->mirr->addr) +
13057			     CacheMirrorOffset))) {
13058				local_sglist[i].addr = remote_sglist[i].addr -
13059					CacheMirrorOffset;
13060				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13061				     CTL_FLAG_DATA_IN)
13062					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13063			} else {
13064				local_sglist[i].addr = remote_sglist[i].addr +
13065					CacheMirrorOffset;
13066			}
13067#endif
13068#if 0
13069			printf("%s: local %p, remote %p, len %d\n",
13070			       __func__, local_sglist[i].addr,
13071			       remote_sglist[i].addr, local_sglist[i].len);
13072#endif
13073		}
13074	} else {
13075		uint32_t len_to_go;
13076
13077		/*
13078		 * In this case, we don't have automatically allocated
13079		 * memory for this I/O on this controller.  This typically
13080		 * happens with internal CTL I/O -- e.g. inquiry, mode
13081		 * sense, etc.  Anything coming from RAIDCore will have
13082		 * a mirror area available.
13083		 */
13084		len_to_go = io->scsiio.kern_data_len;
13085
13086		/*
13087		 * Clear the no datasync flag, we have to use malloced
13088		 * buffers.
13089		 */
13090		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13091
13092		/*
13093		 * The difficult thing here is that the size of the various
13094		 * S/G segments may be different than the size from the
13095		 * remote controller.  That'll make it harder when DMAing
13096		 * the data back to the other side.
13097		 */
13098		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13099		     sizeof(io->io_hdr.remote_sglist[0])) &&
13100		     (len_to_go > 0); i++) {
13101			local_sglist[i].len = ctl_min(len_to_go, 131072);
13102			CTL_SIZE_8B(local_dma_sglist[i].len,
13103				    local_sglist[i].len);
13104			local_sglist[i].addr =
13105				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13106
13107			local_dma_sglist[i].addr = local_sglist[i].addr;
13108
13109			if (local_sglist[i].addr == NULL) {
13110				int j;
13111
13112				printf("malloc failed for %zd bytes!",
13113				       local_dma_sglist[i].len);
13114				for (j = 0; j < i; j++) {
13115					free(local_sglist[j].addr, M_CTL);
13116				}
13117				ctl_set_internal_failure(&io->scsiio,
13118							 /*sks_valid*/ 1,
13119							 /*retry_count*/ 4857);
13120				retval = 1;
13121				goto bailout_error;
13122
13123			}
13124			/* XXX KDM do we need a sync here? */
13125
13126			len_to_go -= local_sglist[i].len;
13127		}
13128		/*
13129		 * Reset the number of S/G entries accordingly.  The
13130		 * original number of S/G entries is available in
13131		 * rem_sg_entries.
13132		 */
13133		io->scsiio.kern_sg_entries = i;
13134
13135#if 0
13136		printf("%s: kern_sg_entries = %d\n", __func__,
13137		       io->scsiio.kern_sg_entries);
13138		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13139			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13140			       local_sglist[i].addr, local_sglist[i].len,
13141			       local_dma_sglist[i].len);
13142#endif
13143	}
13144
13145
13146	return (retval);
13147
13148bailout_error:
13149
13150	ctl_send_datamove_done(io, /*have_lock*/ 0);
13151
13152	return (retval);
13153}
13154
13155static int
13156ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13157			 ctl_ha_dt_cb callback)
13158{
13159	struct ctl_ha_dt_req *rq;
13160	struct ctl_sg_entry *remote_sglist, *local_sglist;
13161	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13162	uint32_t local_used, remote_used, total_used;
13163	int retval;
13164	int i, j;
13165
13166	retval = 0;
13167
13168	rq = ctl_dt_req_alloc();
13169
13170	/*
13171	 * If we failed to allocate the request, and if the DMA didn't fail
13172	 * anyway, set busy status.  This is just a resource allocation
13173	 * failure.
13174	 */
13175	if ((rq == NULL)
13176	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13177		ctl_set_busy(&io->scsiio);
13178
13179	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13180
13181		if (rq != NULL)
13182			ctl_dt_req_free(rq);
13183
13184		/*
13185		 * The data move failed.  We need to return status back
13186		 * to the other controller.  No point in trying to DMA
13187		 * data to the remote controller.
13188		 */
13189
13190		ctl_send_datamove_done(io, /*have_lock*/ 0);
13191
13192		retval = 1;
13193
13194		goto bailout;
13195	}
13196
13197	local_sglist = io->io_hdr.local_sglist;
13198	local_dma_sglist = io->io_hdr.local_dma_sglist;
13199	remote_sglist = io->io_hdr.remote_sglist;
13200	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13201	local_used = 0;
13202	remote_used = 0;
13203	total_used = 0;
13204
13205	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13206		rq->ret = CTL_HA_STATUS_SUCCESS;
13207		rq->context = io;
13208		callback(rq);
13209		goto bailout;
13210	}
13211
13212	/*
13213	 * Pull/push the data over the wire from/to the other controller.
13214	 * This takes into account the possibility that the local and
13215	 * remote sglists may not be identical in terms of the size of
13216	 * the elements and the number of elements.
13217	 *
13218	 * One fundamental assumption here is that the length allocated for
13219	 * both the local and remote sglists is identical.  Otherwise, we've
13220	 * essentially got a coding error of some sort.
13221	 */
13222	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13223		int isc_ret;
13224		uint32_t cur_len, dma_length;
13225		uint8_t *tmp_ptr;
13226
13227		rq->id = CTL_HA_DATA_CTL;
13228		rq->command = command;
13229		rq->context = io;
13230
13231		/*
13232		 * Both pointers should be aligned.  But it is possible
13233		 * that the allocation length is not.  They should both
13234		 * also have enough slack left over at the end, though,
13235		 * to round up to the next 8 byte boundary.
13236		 */
13237		cur_len = ctl_min(local_sglist[i].len - local_used,
13238				  remote_sglist[j].len - remote_used);
13239
13240		/*
13241		 * In this case, we have a size issue and need to decrease
13242		 * the size, except in the case where we actually have less
13243		 * than 8 bytes left.  In that case, we need to increase
13244		 * the DMA length to get the last bit.
13245		 */
13246		if ((cur_len & 0x7) != 0) {
13247			if (cur_len > 0x7) {
13248				cur_len = cur_len - (cur_len & 0x7);
13249				dma_length = cur_len;
13250			} else {
13251				CTL_SIZE_8B(dma_length, cur_len);
13252			}
13253
13254		} else
13255			dma_length = cur_len;
13256
13257		/*
13258		 * If we had to allocate memory for this I/O, instead of using
13259		 * the non-cached mirror memory, we'll need to flush the cache
13260		 * before trying to DMA to the other controller.
13261		 *
13262		 * We could end up doing this multiple times for the same
13263		 * segment if we have a larger local segment than remote
13264		 * segment.  That shouldn't be an issue.
13265		 */
13266		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13267			/*
13268			 * XXX KDM use bus_dmamap_sync() here.
13269			 */
13270		}
13271
13272		rq->size = dma_length;
13273
13274		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13275		tmp_ptr += local_used;
13276
13277		/* Use physical addresses when talking to ISC hardware */
13278		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13279			/* XXX KDM use busdma */
13280#if 0
13281			rq->local = vtophys(tmp_ptr);
13282#endif
13283		} else
13284			rq->local = tmp_ptr;
13285
13286		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13287		tmp_ptr += remote_used;
13288		rq->remote = tmp_ptr;
13289
13290		rq->callback = NULL;
13291
13292		local_used += cur_len;
13293		if (local_used >= local_sglist[i].len) {
13294			i++;
13295			local_used = 0;
13296		}
13297
13298		remote_used += cur_len;
13299		if (remote_used >= remote_sglist[j].len) {
13300			j++;
13301			remote_used = 0;
13302		}
13303		total_used += cur_len;
13304
13305		if (total_used >= io->scsiio.kern_data_len)
13306			rq->callback = callback;
13307
13308		if ((rq->size & 0x7) != 0) {
13309			printf("%s: warning: size %d is not on 8b boundary\n",
13310			       __func__, rq->size);
13311		}
13312		if (((uintptr_t)rq->local & 0x7) != 0) {
13313			printf("%s: warning: local %p not on 8b boundary\n",
13314			       __func__, rq->local);
13315		}
13316		if (((uintptr_t)rq->remote & 0x7) != 0) {
13317			printf("%s: warning: remote %p not on 8b boundary\n",
13318			       __func__, rq->local);
13319		}
13320#if 0
13321		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13322		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13323		       rq->local, rq->remote, rq->size);
13324#endif
13325
13326		isc_ret = ctl_dt_single(rq);
13327		if (isc_ret == CTL_HA_STATUS_WAIT)
13328			continue;
13329
13330		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13331			rq->ret = CTL_HA_STATUS_SUCCESS;
13332		} else {
13333			rq->ret = isc_ret;
13334		}
13335		callback(rq);
13336		goto bailout;
13337	}
13338
13339bailout:
13340	return (retval);
13341
13342}
13343
13344static void
13345ctl_datamove_remote_read(union ctl_io *io)
13346{
13347	int retval;
13348	int i;
13349
13350	/*
13351	 * This will send an error to the other controller in the case of a
13352	 * failure.
13353	 */
13354	retval = ctl_datamove_remote_sgl_setup(io);
13355	if (retval != 0)
13356		return;
13357
13358	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13359					  ctl_datamove_remote_read_cb);
13360	if ((retval != 0)
13361	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13362		/*
13363		 * Make sure we free memory if there was an error..  The
13364		 * ctl_datamove_remote_xfer() function will send the
13365		 * datamove done message, or call the callback with an
13366		 * error if there is a problem.
13367		 */
13368		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13369			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13370	}
13371
13372	return;
13373}
13374
13375/*
13376 * Process a datamove request from the other controller.  This is used for
13377 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13378 * first.  Once that is complete, the data gets DMAed into the remote
13379 * controller's memory.  For reads, we DMA from the remote controller's
13380 * memory into our memory first, and then move it out to the FETD.
13381 */
13382static void
13383ctl_datamove_remote(union ctl_io *io)
13384{
13385	struct ctl_softc *softc;
13386
13387	softc = control_softc;
13388
13389	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13390
13391	/*
13392	 * Note that we look for an aborted I/O here, but don't do some of
13393	 * the other checks that ctl_datamove() normally does.
13394	 * We don't need to run the datamove delay code, since that should
13395	 * have been done if need be on the other controller.
13396	 */
13397	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13398		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13399		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13400		       io->io_hdr.nexus.targ_port,
13401		       io->io_hdr.nexus.targ_target.id,
13402		       io->io_hdr.nexus.targ_lun);
13403		io->io_hdr.port_status = 31338;
13404		ctl_send_datamove_done(io, /*have_lock*/ 0);
13405		return;
13406	}
13407
13408	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13409		ctl_datamove_remote_write(io);
13410	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13411		ctl_datamove_remote_read(io);
13412	} else {
13413		union ctl_ha_msg msg;
13414		struct scsi_sense_data *sense;
13415		uint8_t sks[3];
13416		int retry_count;
13417
13418		memset(&msg, 0, sizeof(msg));
13419
13420		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13421		msg.hdr.status = CTL_SCSI_ERROR;
13422		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13423
13424		retry_count = 4243;
13425
13426		sense = &msg.scsi.sense_data;
13427		sks[0] = SSD_SCS_VALID;
13428		sks[1] = (retry_count >> 8) & 0xff;
13429		sks[2] = retry_count & 0xff;
13430
13431		/* "Internal target failure" */
13432		scsi_set_sense_data(sense,
13433				    /*sense_format*/ SSD_TYPE_NONE,
13434				    /*current_error*/ 1,
13435				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13436				    /*asc*/ 0x44,
13437				    /*ascq*/ 0x00,
13438				    /*type*/ SSD_ELEM_SKS,
13439				    /*size*/ sizeof(sks),
13440				    /*data*/ sks,
13441				    SSD_ELEM_NONE);
13442
13443		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13444		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13445			ctl_failover_io(io, /*have_lock*/ 1);
13446			return;
13447		}
13448
13449		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13450		    CTL_HA_STATUS_SUCCESS) {
13451			/* XXX KDM what to do if this fails? */
13452		}
13453		return;
13454	}
13455
13456}
13457
13458static int
13459ctl_process_done(union ctl_io *io)
13460{
13461	struct ctl_lun *lun;
13462	struct ctl_softc *ctl_softc;
13463	void (*fe_done)(union ctl_io *io);
13464	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13465
13466	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13467
13468	fe_done =
13469	    control_softc->ctl_ports[targ_port]->fe_done;
13470
13471#ifdef CTL_TIME_IO
13472	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13473		char str[256];
13474		char path_str[64];
13475		struct sbuf sb;
13476
13477		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13478		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13479
13480		sbuf_cat(&sb, path_str);
13481		switch (io->io_hdr.io_type) {
13482		case CTL_IO_SCSI:
13483			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13484			sbuf_printf(&sb, "\n");
13485			sbuf_cat(&sb, path_str);
13486			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13487				    io->scsiio.tag_num, io->scsiio.tag_type);
13488			break;
13489		case CTL_IO_TASK:
13490			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13491				    "Tag Type: %d\n", io->taskio.task_action,
13492				    io->taskio.tag_num, io->taskio.tag_type);
13493			break;
13494		default:
13495			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13496			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13497			break;
13498		}
13499		sbuf_cat(&sb, path_str);
13500		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13501			    (intmax_t)time_uptime - io->io_hdr.start_time);
13502		sbuf_finish(&sb);
13503		printf("%s", sbuf_data(&sb));
13504	}
13505#endif /* CTL_TIME_IO */
13506
13507	switch (io->io_hdr.io_type) {
13508	case CTL_IO_SCSI:
13509		break;
13510	case CTL_IO_TASK:
13511		if (bootverbose || verbose > 0)
13512			ctl_io_error_print(io, NULL);
13513		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13514			ctl_free_io(io);
13515		else
13516			fe_done(io);
13517		return (CTL_RETVAL_COMPLETE);
13518		break;
13519	default:
13520		printf("ctl_process_done: invalid io type %d\n",
13521		       io->io_hdr.io_type);
13522		panic("ctl_process_done: invalid io type %d\n",
13523		      io->io_hdr.io_type);
13524		break; /* NOTREACHED */
13525	}
13526
13527	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13528	if (lun == NULL) {
13529		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13530				 io->io_hdr.nexus.targ_mapped_lun));
13531		fe_done(io);
13532		goto bailout;
13533	}
13534	ctl_softc = lun->ctl_softc;
13535
13536	mtx_lock(&lun->lun_lock);
13537
13538	/*
13539	 * Check to see if we have any errors to inject here.  We only
13540	 * inject errors for commands that don't already have errors set.
13541	 */
13542	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13543	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13544		ctl_inject_error(lun, io);
13545
13546	/*
13547	 * XXX KDM how do we treat commands that aren't completed
13548	 * successfully?
13549	 *
13550	 * XXX KDM should we also track I/O latency?
13551	 */
13552	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13553	    io->io_hdr.io_type == CTL_IO_SCSI) {
13554#ifdef CTL_TIME_IO
13555		struct bintime cur_bt;
13556#endif
13557		int type;
13558
13559		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13560		    CTL_FLAG_DATA_IN)
13561			type = CTL_STATS_READ;
13562		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13563		    CTL_FLAG_DATA_OUT)
13564			type = CTL_STATS_WRITE;
13565		else
13566			type = CTL_STATS_NO_IO;
13567
13568		lun->stats.ports[targ_port].bytes[type] +=
13569		    io->scsiio.kern_total_len;
13570		lun->stats.ports[targ_port].operations[type]++;
13571#ifdef CTL_TIME_IO
13572		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13573		   &io->io_hdr.dma_bt);
13574		lun->stats.ports[targ_port].num_dmas[type] +=
13575		    io->io_hdr.num_dmas;
13576		getbintime(&cur_bt);
13577		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13578		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13579#endif
13580	}
13581
13582	/*
13583	 * Remove this from the OOA queue.
13584	 */
13585	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13586
13587	/*
13588	 * Run through the blocked queue on this LUN and see if anything
13589	 * has become unblocked, now that this transaction is done.
13590	 */
13591	ctl_check_blocked(lun);
13592
13593	/*
13594	 * If the LUN has been invalidated, free it if there is nothing
13595	 * left on its OOA queue.
13596	 */
13597	if ((lun->flags & CTL_LUN_INVALID)
13598	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13599		mtx_unlock(&lun->lun_lock);
13600		mtx_lock(&ctl_softc->ctl_lock);
13601		ctl_free_lun(lun);
13602		mtx_unlock(&ctl_softc->ctl_lock);
13603	} else
13604		mtx_unlock(&lun->lun_lock);
13605
13606	/*
13607	 * If this command has been aborted, make sure we set the status
13608	 * properly.  The FETD is responsible for freeing the I/O and doing
13609	 * whatever it needs to do to clean up its state.
13610	 */
13611	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13612		ctl_set_task_aborted(&io->scsiio);
13613
13614	/*
13615	 * We print out status for every task management command.  For SCSI
13616	 * commands, we filter out any unit attention errors; they happen
13617	 * on every boot, and would clutter up the log.  Note:  task
13618	 * management commands aren't printed here, they are printed above,
13619	 * since they should never even make it down here.
13620	 */
13621	switch (io->io_hdr.io_type) {
13622	case CTL_IO_SCSI: {
13623		int error_code, sense_key, asc, ascq;
13624
13625		sense_key = 0;
13626
13627		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13628		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13629			/*
13630			 * Since this is just for printing, no need to
13631			 * show errors here.
13632			 */
13633			scsi_extract_sense_len(&io->scsiio.sense_data,
13634					       io->scsiio.sense_len,
13635					       &error_code,
13636					       &sense_key,
13637					       &asc,
13638					       &ascq,
13639					       /*show_errors*/ 0);
13640		}
13641
13642		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13643		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13644		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13645		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13646
13647			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13648				ctl_softc->skipped_prints++;
13649			} else {
13650				uint32_t skipped_prints;
13651
13652				skipped_prints = ctl_softc->skipped_prints;
13653
13654				ctl_softc->skipped_prints = 0;
13655				ctl_softc->last_print_jiffies = time_uptime;
13656
13657				if (skipped_prints > 0) {
13658#ifdef NEEDTOPORT
13659					csevent_log(CSC_CTL | CSC_SHELF_SW |
13660					    CTL_ERROR_REPORT,
13661					    csevent_LogType_Trace,
13662					    csevent_Severity_Information,
13663					    csevent_AlertLevel_Green,
13664					    csevent_FRU_Firmware,
13665					    csevent_FRU_Unknown,
13666					    "High CTL error volume, %d prints "
13667					    "skipped", skipped_prints);
13668#endif
13669				}
13670				if (bootverbose || verbose > 0)
13671					ctl_io_error_print(io, NULL);
13672			}
13673		}
13674		break;
13675	}
13676	case CTL_IO_TASK:
13677		if (bootverbose || verbose > 0)
13678			ctl_io_error_print(io, NULL);
13679		break;
13680	default:
13681		break;
13682	}
13683
13684	/*
13685	 * Tell the FETD or the other shelf controller we're done with this
13686	 * command.  Note that only SCSI commands get to this point.  Task
13687	 * management commands are completed above.
13688	 *
13689	 * We only send status to the other controller if we're in XFER
13690	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13691	 * received the I/O (from CTL's perspective), and so the status is
13692	 * generated there.
13693	 *
13694	 * XXX KDM if we hold the lock here, we could cause a deadlock
13695	 * if the frontend comes back in in this context to queue
13696	 * something.
13697	 */
13698	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13699	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13700		union ctl_ha_msg msg;
13701
13702		memset(&msg, 0, sizeof(msg));
13703		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13704		msg.hdr.original_sc = io->io_hdr.original_sc;
13705		msg.hdr.nexus = io->io_hdr.nexus;
13706		msg.hdr.status = io->io_hdr.status;
13707		msg.scsi.scsi_status = io->scsiio.scsi_status;
13708		msg.scsi.tag_num = io->scsiio.tag_num;
13709		msg.scsi.tag_type = io->scsiio.tag_type;
13710		msg.scsi.sense_len = io->scsiio.sense_len;
13711		msg.scsi.sense_residual = io->scsiio.sense_residual;
13712		msg.scsi.residual = io->scsiio.residual;
13713		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13714		       sizeof(io->scsiio.sense_data));
13715		/*
13716		 * We copy this whether or not this is an I/O-related
13717		 * command.  Otherwise, we'd have to go and check to see
13718		 * whether it's a read/write command, and it really isn't
13719		 * worth it.
13720		 */
13721		memcpy(&msg.scsi.lbalen,
13722		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13723		       sizeof(msg.scsi.lbalen));
13724
13725		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13726				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13727			/* XXX do something here */
13728		}
13729
13730		ctl_free_io(io);
13731	} else
13732		fe_done(io);
13733
13734bailout:
13735
13736	return (CTL_RETVAL_COMPLETE);
13737}
13738
13739#ifdef CTL_WITH_CA
13740/*
13741 * Front end should call this if it doesn't do autosense.  When the request
13742 * sense comes back in from the initiator, we'll dequeue this and send it.
13743 */
13744int
13745ctl_queue_sense(union ctl_io *io)
13746{
13747	struct ctl_lun *lun;
13748	struct ctl_softc *ctl_softc;
13749	uint32_t initidx, targ_lun;
13750
13751	ctl_softc = control_softc;
13752
13753	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13754
13755	/*
13756	 * LUN lookup will likely move to the ctl_work_thread() once we
13757	 * have our new queueing infrastructure (that doesn't put things on
13758	 * a per-LUN queue initially).  That is so that we can handle
13759	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13760	 * can't deal with that right now.
13761	 */
13762	mtx_lock(&ctl_softc->ctl_lock);
13763
13764	/*
13765	 * If we don't have a LUN for this, just toss the sense
13766	 * information.
13767	 */
13768	targ_lun = io->io_hdr.nexus.targ_lun;
13769	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13770	if ((targ_lun < CTL_MAX_LUNS)
13771	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13772		lun = ctl_softc->ctl_luns[targ_lun];
13773	else
13774		goto bailout;
13775
13776	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13777
13778	mtx_lock(&lun->lun_lock);
13779	/*
13780	 * Already have CA set for this LUN...toss the sense information.
13781	 */
13782	if (ctl_is_set(lun->have_ca, initidx)) {
13783		mtx_unlock(&lun->lun_lock);
13784		goto bailout;
13785	}
13786
13787	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13788	       ctl_min(sizeof(lun->pending_sense[initidx]),
13789	       sizeof(io->scsiio.sense_data)));
13790	ctl_set_mask(lun->have_ca, initidx);
13791	mtx_unlock(&lun->lun_lock);
13792
13793bailout:
13794	mtx_unlock(&ctl_softc->ctl_lock);
13795
13796	ctl_free_io(io);
13797
13798	return (CTL_RETVAL_COMPLETE);
13799}
13800#endif
13801
13802/*
13803 * Primary command inlet from frontend ports.  All SCSI and task I/O
13804 * requests must go through this function.
13805 */
13806int
13807ctl_queue(union ctl_io *io)
13808{
13809	struct ctl_softc *ctl_softc;
13810
13811	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13812
13813	ctl_softc = control_softc;
13814
13815#ifdef CTL_TIME_IO
13816	io->io_hdr.start_time = time_uptime;
13817	getbintime(&io->io_hdr.start_bt);
13818#endif /* CTL_TIME_IO */
13819
13820	/* Map FE-specific LUN ID into global one. */
13821	io->io_hdr.nexus.targ_mapped_lun =
13822	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13823
13824	switch (io->io_hdr.io_type) {
13825	case CTL_IO_SCSI:
13826	case CTL_IO_TASK:
13827		ctl_enqueue_incoming(io);
13828		break;
13829	default:
13830		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13831		return (EINVAL);
13832	}
13833
13834	return (CTL_RETVAL_COMPLETE);
13835}
13836
13837#ifdef CTL_IO_DELAY
13838static void
13839ctl_done_timer_wakeup(void *arg)
13840{
13841	union ctl_io *io;
13842
13843	io = (union ctl_io *)arg;
13844	ctl_done(io);
13845}
13846#endif /* CTL_IO_DELAY */
13847
13848void
13849ctl_done(union ctl_io *io)
13850{
13851	struct ctl_softc *ctl_softc;
13852
13853	ctl_softc = control_softc;
13854
13855	/*
13856	 * Enable this to catch duplicate completion issues.
13857	 */
13858#if 0
13859	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13860		printf("%s: type %d msg %d cdb %x iptl: "
13861		       "%d:%d:%d:%d tag 0x%04x "
13862		       "flag %#x status %x\n",
13863			__func__,
13864			io->io_hdr.io_type,
13865			io->io_hdr.msg_type,
13866			io->scsiio.cdb[0],
13867			io->io_hdr.nexus.initid.id,
13868			io->io_hdr.nexus.targ_port,
13869			io->io_hdr.nexus.targ_target.id,
13870			io->io_hdr.nexus.targ_lun,
13871			(io->io_hdr.io_type ==
13872			CTL_IO_TASK) ?
13873			io->taskio.tag_num :
13874			io->scsiio.tag_num,
13875		        io->io_hdr.flags,
13876			io->io_hdr.status);
13877	} else
13878		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13879#endif
13880
13881	/*
13882	 * This is an internal copy of an I/O, and should not go through
13883	 * the normal done processing logic.
13884	 */
13885	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13886		return;
13887
13888	/*
13889	 * We need to send a msg to the serializing shelf to finish the IO
13890	 * as well.  We don't send a finish message to the other shelf if
13891	 * this is a task management command.  Task management commands
13892	 * aren't serialized in the OOA queue, but rather just executed on
13893	 * both shelf controllers for commands that originated on that
13894	 * controller.
13895	 */
13896	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13897	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13898		union ctl_ha_msg msg_io;
13899
13900		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13901		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13902		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13903		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13904		}
13905		/* continue on to finish IO */
13906	}
13907#ifdef CTL_IO_DELAY
13908	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13909		struct ctl_lun *lun;
13910
13911		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13912
13913		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13914	} else {
13915		struct ctl_lun *lun;
13916
13917		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13918
13919		if ((lun != NULL)
13920		 && (lun->delay_info.done_delay > 0)) {
13921			struct callout *callout;
13922
13923			callout = (struct callout *)&io->io_hdr.timer_bytes;
13924			callout_init(callout, /*mpsafe*/ 1);
13925			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13926			callout_reset(callout,
13927				      lun->delay_info.done_delay * hz,
13928				      ctl_done_timer_wakeup, io);
13929			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13930				lun->delay_info.done_delay = 0;
13931			return;
13932		}
13933	}
13934#endif /* CTL_IO_DELAY */
13935
13936	ctl_enqueue_done(io);
13937}
13938
13939int
13940ctl_isc(struct ctl_scsiio *ctsio)
13941{
13942	struct ctl_lun *lun;
13943	int retval;
13944
13945	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13946
13947	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13948
13949	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13950
13951	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13952
13953	return (retval);
13954}
13955
13956
13957static void
13958ctl_work_thread(void *arg)
13959{
13960	struct ctl_thread *thr = (struct ctl_thread *)arg;
13961	struct ctl_softc *softc = thr->ctl_softc;
13962	union ctl_io *io;
13963	int retval;
13964
13965	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13966
13967	for (;;) {
13968		retval = 0;
13969
13970		/*
13971		 * We handle the queues in this order:
13972		 * - ISC
13973		 * - done queue (to free up resources, unblock other commands)
13974		 * - RtR queue
13975		 * - incoming queue
13976		 *
13977		 * If those queues are empty, we break out of the loop and
13978		 * go to sleep.
13979		 */
13980		mtx_lock(&thr->queue_lock);
13981		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13982		if (io != NULL) {
13983			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13984			mtx_unlock(&thr->queue_lock);
13985			ctl_handle_isc(io);
13986			continue;
13987		}
13988		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13989		if (io != NULL) {
13990			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13991			/* clear any blocked commands, call fe_done */
13992			mtx_unlock(&thr->queue_lock);
13993			retval = ctl_process_done(io);
13994			continue;
13995		}
13996		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13997		if (io != NULL) {
13998			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13999			mtx_unlock(&thr->queue_lock);
14000			if (io->io_hdr.io_type == CTL_IO_TASK)
14001				ctl_run_task(io);
14002			else
14003				ctl_scsiio_precheck(softc, &io->scsiio);
14004			continue;
14005		}
14006		if (!ctl_pause_rtr) {
14007			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14008			if (io != NULL) {
14009				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14010				mtx_unlock(&thr->queue_lock);
14011				retval = ctl_scsiio(&io->scsiio);
14012				if (retval != CTL_RETVAL_COMPLETE)
14013					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14014				continue;
14015			}
14016		}
14017
14018		/* Sleep until we have something to do. */
14019		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14020	}
14021}
14022
14023static void
14024ctl_lun_thread(void *arg)
14025{
14026	struct ctl_softc *softc = (struct ctl_softc *)arg;
14027	struct ctl_be_lun *be_lun;
14028	int retval;
14029
14030	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14031
14032	for (;;) {
14033		retval = 0;
14034		mtx_lock(&softc->ctl_lock);
14035		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14036		if (be_lun != NULL) {
14037			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14038			mtx_unlock(&softc->ctl_lock);
14039			ctl_create_lun(be_lun);
14040			continue;
14041		}
14042
14043		/* Sleep until we have something to do. */
14044		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14045		    PDROP | PRIBIO, "-", 0);
14046	}
14047}
14048
14049static void
14050ctl_enqueue_incoming(union ctl_io *io)
14051{
14052	struct ctl_softc *softc = control_softc;
14053	struct ctl_thread *thr;
14054	u_int idx;
14055
14056	idx = (io->io_hdr.nexus.targ_port * 127 +
14057	       io->io_hdr.nexus.initid.id) % worker_threads;
14058	thr = &softc->threads[idx];
14059	mtx_lock(&thr->queue_lock);
14060	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14061	mtx_unlock(&thr->queue_lock);
14062	wakeup(thr);
14063}
14064
14065static void
14066ctl_enqueue_rtr(union ctl_io *io)
14067{
14068	struct ctl_softc *softc = control_softc;
14069	struct ctl_thread *thr;
14070
14071	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14072	mtx_lock(&thr->queue_lock);
14073	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14074	mtx_unlock(&thr->queue_lock);
14075	wakeup(thr);
14076}
14077
14078static void
14079ctl_enqueue_done(union ctl_io *io)
14080{
14081	struct ctl_softc *softc = control_softc;
14082	struct ctl_thread *thr;
14083
14084	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14085	mtx_lock(&thr->queue_lock);
14086	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14087	mtx_unlock(&thr->queue_lock);
14088	wakeup(thr);
14089}
14090
14091static void
14092ctl_enqueue_isc(union ctl_io *io)
14093{
14094	struct ctl_softc *softc = control_softc;
14095	struct ctl_thread *thr;
14096
14097	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14098	mtx_lock(&thr->queue_lock);
14099	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14100	mtx_unlock(&thr->queue_lock);
14101	wakeup(thr);
14102}
14103
14104/* Initialization and failover */
14105
14106void
14107ctl_init_isc_msg(void)
14108{
14109	printf("CTL: Still calling this thing\n");
14110}
14111
14112/*
14113 * Init component
14114 * 	Initializes component into configuration defined by bootMode
14115 *	(see hasc-sv.c)
14116 *  	returns hasc_Status:
14117 * 		OK
14118 *		ERROR - fatal error
14119 */
14120static ctl_ha_comp_status
14121ctl_isc_init(struct ctl_ha_component *c)
14122{
14123	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14124
14125	c->status = ret;
14126	return ret;
14127}
14128
14129/* Start component
14130 * 	Starts component in state requested. If component starts successfully,
14131 *	it must set its own state to the requestrd state
14132 *	When requested state is HASC_STATE_HA, the component may refine it
14133 * 	by adding _SLAVE or _MASTER flags.
14134 *	Currently allowed state transitions are:
14135 *	UNKNOWN->HA		- initial startup
14136 *	UNKNOWN->SINGLE - initial startup when no parter detected
14137 *	HA->SINGLE		- failover
14138 * returns ctl_ha_comp_status:
14139 * 		OK	- component successfully started in requested state
14140 *		FAILED  - could not start the requested state, failover may
14141 * 			  be possible
14142 *		ERROR	- fatal error detected, no future startup possible
14143 */
14144static ctl_ha_comp_status
14145ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14146{
14147	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14148
14149	printf("%s: go\n", __func__);
14150
14151	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14152	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14153		ctl_is_single = 0;
14154		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14155		    != CTL_HA_STATUS_SUCCESS) {
14156			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14157			ret = CTL_HA_COMP_STATUS_ERROR;
14158		}
14159	} else if (CTL_HA_STATE_IS_HA(c->state)
14160		&& CTL_HA_STATE_IS_SINGLE(state)){
14161		// HA->SINGLE transition
14162	        ctl_failover();
14163		ctl_is_single = 1;
14164	} else {
14165		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14166		       c->state, state);
14167		ret = CTL_HA_COMP_STATUS_ERROR;
14168	}
14169	if (CTL_HA_STATE_IS_SINGLE(state))
14170		ctl_is_single = 1;
14171
14172	c->state = state;
14173	c->status = ret;
14174	return ret;
14175}
14176
14177/*
14178 * Quiesce component
14179 * The component must clear any error conditions (set status to OK) and
14180 * prepare itself to another Start call
14181 * returns ctl_ha_comp_status:
14182 * 	OK
14183 *	ERROR
14184 */
14185static ctl_ha_comp_status
14186ctl_isc_quiesce(struct ctl_ha_component *c)
14187{
14188	int ret = CTL_HA_COMP_STATUS_OK;
14189
14190	ctl_pause_rtr = 1;
14191	c->status = ret;
14192	return ret;
14193}
14194
14195struct ctl_ha_component ctl_ha_component_ctlisc =
14196{
14197	.name = "CTL ISC",
14198	.state = CTL_HA_STATE_UNKNOWN,
14199	.init = ctl_isc_init,
14200	.start = ctl_isc_start,
14201	.quiesce = ctl_isc_quiesce
14202};
14203
14204/*
14205 *  vim: ts=8
14206 */
14207