ctl.c revision 268421
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 268421 2014-07-08 18:51:03Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/types.h>
51#include <sys/kthread.h>
52#include <sys/bio.h>
53#include <sys/fcntl.h>
54#include <sys/lock.h>
55#include <sys/module.h>
56#include <sys/mutex.h>
57#include <sys/condvar.h>
58#include <sys/malloc.h>
59#include <sys/conf.h>
60#include <sys/ioccom.h>
61#include <sys/queue.h>
62#include <sys/sbuf.h>
63#include <sys/smp.h>
64#include <sys/endian.h>
65#include <sys/sysctl.h>
66
67#include <cam/cam.h>
68#include <cam/scsi/scsi_all.h>
69#include <cam/scsi/scsi_da.h>
70#include <cam/ctl/ctl_io.h>
71#include <cam/ctl/ctl.h>
72#include <cam/ctl/ctl_frontend.h>
73#include <cam/ctl/ctl_frontend_internal.h>
74#include <cam/ctl/ctl_util.h>
75#include <cam/ctl/ctl_backend.h>
76#include <cam/ctl/ctl_ioctl.h>
77#include <cam/ctl/ctl_ha.h>
78#include <cam/ctl/ctl_private.h>
79#include <cam/ctl/ctl_debug.h>
80#include <cam/ctl/ctl_scsi_all.h>
81#include <cam/ctl/ctl_error.h>
82
83struct ctl_softc *control_softc = NULL;
84
85/*
86 * Size and alignment macros needed for Copan-specific HA hardware.  These
87 * can go away when the HA code is re-written, and uses busdma for any
88 * hardware.
89 */
90#define	CTL_ALIGN_8B(target, source, type)				\
91	if (((uint32_t)source & 0x7) != 0)				\
92		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93	else								\
94		target = (type)source;
95
96#define	CTL_SIZE_8B(target, size)					\
97	if ((size & 0x7) != 0)						\
98		target = size + (0x8 - (size & 0x7));			\
99	else								\
100		target = size;
101
102#define CTL_ALIGN_8B_MARGIN	16
103
104/*
105 * Template mode pages.
106 */
107
108/*
109 * Note that these are default values only.  The actual values will be
110 * filled in when the user does a mode sense.
111 */
112static struct copan_power_subpage power_page_default = {
113	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114	/*subpage*/ PWR_SUBPAGE_CODE,
115	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117	/*page_version*/ PWR_VERSION,
118	/* total_luns */ 26,
119	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122		      0, 0, 0, 0, 0, 0}
123};
124
125static struct copan_power_subpage power_page_changeable = {
126	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127	/*subpage*/ PWR_SUBPAGE_CODE,
128	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130	/*page_version*/ 0,
131	/* total_luns */ 0,
132	/* max_active_luns*/ 0,
133	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135		      0, 0, 0, 0, 0, 0}
136};
137
138static struct copan_aps_subpage aps_page_default = {
139	APS_PAGE_CODE | SMPH_SPF, //page_code
140	APS_SUBPAGE_CODE, //subpage
141	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143	APS_VERSION, //page_version
144	0, //lock_active
145	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147	0, 0, 0, 0, 0} //reserved
148};
149
150static struct copan_aps_subpage aps_page_changeable = {
151	APS_PAGE_CODE | SMPH_SPF, //page_code
152	APS_SUBPAGE_CODE, //subpage
153	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155	0, //page_version
156	0, //lock_active
157	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159	0, 0, 0, 0, 0} //reserved
160};
161
162static struct copan_debugconf_subpage debugconf_page_default = {
163	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
164	DBGCNF_SUBPAGE_CODE,		/* subpage */
165	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167	DBGCNF_VERSION,			/* page_version */
168	{CTL_TIME_IO_DEFAULT_SECS>>8,
169	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
170};
171
172static struct copan_debugconf_subpage debugconf_page_changeable = {
173	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
174	DBGCNF_SUBPAGE_CODE,		/* subpage */
175	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177	0,				/* page_version */
178	{0xff,0xff},			/* ctl_time_io_secs */
179};
180
181static struct scsi_format_page format_page_default = {
182	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
183	/*page_length*/sizeof(struct scsi_format_page) - 2,
184	/*tracks_per_zone*/ {0, 0},
185	/*alt_sectors_per_zone*/ {0, 0},
186	/*alt_tracks_per_zone*/ {0, 0},
187	/*alt_tracks_per_lun*/ {0, 0},
188	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190	/*bytes_per_sector*/ {0, 0},
191	/*interleave*/ {0, 0},
192	/*track_skew*/ {0, 0},
193	/*cylinder_skew*/ {0, 0},
194	/*flags*/ SFP_HSEC,
195	/*reserved*/ {0, 0, 0}
196};
197
198static struct scsi_format_page format_page_changeable = {
199	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
200	/*page_length*/sizeof(struct scsi_format_page) - 2,
201	/*tracks_per_zone*/ {0, 0},
202	/*alt_sectors_per_zone*/ {0, 0},
203	/*alt_tracks_per_zone*/ {0, 0},
204	/*alt_tracks_per_lun*/ {0, 0},
205	/*sectors_per_track*/ {0, 0},
206	/*bytes_per_sector*/ {0, 0},
207	/*interleave*/ {0, 0},
208	/*track_skew*/ {0, 0},
209	/*cylinder_skew*/ {0, 0},
210	/*flags*/ 0,
211	/*reserved*/ {0, 0, 0}
212};
213
214static struct scsi_rigid_disk_page rigid_disk_page_default = {
215	/*page_code*/SMS_RIGID_DISK_PAGE,
216	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217	/*cylinders*/ {0, 0, 0},
218	/*heads*/ CTL_DEFAULT_HEADS,
219	/*start_write_precomp*/ {0, 0, 0},
220	/*start_reduced_current*/ {0, 0, 0},
221	/*step_rate*/ {0, 0},
222	/*landing_zone_cylinder*/ {0, 0, 0},
223	/*rpl*/ SRDP_RPL_DISABLED,
224	/*rotational_offset*/ 0,
225	/*reserved1*/ 0,
226	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227			   CTL_DEFAULT_ROTATION_RATE & 0xff},
228	/*reserved2*/ {0, 0}
229};
230
231static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232	/*page_code*/SMS_RIGID_DISK_PAGE,
233	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234	/*cylinders*/ {0, 0, 0},
235	/*heads*/ 0,
236	/*start_write_precomp*/ {0, 0, 0},
237	/*start_reduced_current*/ {0, 0, 0},
238	/*step_rate*/ {0, 0},
239	/*landing_zone_cylinder*/ {0, 0, 0},
240	/*rpl*/ 0,
241	/*rotational_offset*/ 0,
242	/*reserved1*/ 0,
243	/*rotation_rate*/ {0, 0},
244	/*reserved2*/ {0, 0}
245};
246
247static struct scsi_caching_page caching_page_default = {
248	/*page_code*/SMS_CACHING_PAGE,
249	/*page_length*/sizeof(struct scsi_caching_page) - 2,
250	/*flags1*/ SCP_DISC | SCP_WCE,
251	/*ret_priority*/ 0,
252	/*disable_pf_transfer_len*/ {0xff, 0xff},
253	/*min_prefetch*/ {0, 0},
254	/*max_prefetch*/ {0xff, 0xff},
255	/*max_pf_ceiling*/ {0xff, 0xff},
256	/*flags2*/ 0,
257	/*cache_segments*/ 0,
258	/*cache_seg_size*/ {0, 0},
259	/*reserved*/ 0,
260	/*non_cache_seg_size*/ {0, 0, 0}
261};
262
263static struct scsi_caching_page caching_page_changeable = {
264	/*page_code*/SMS_CACHING_PAGE,
265	/*page_length*/sizeof(struct scsi_caching_page) - 2,
266	/*flags1*/ 0,
267	/*ret_priority*/ 0,
268	/*disable_pf_transfer_len*/ {0, 0},
269	/*min_prefetch*/ {0, 0},
270	/*max_prefetch*/ {0, 0},
271	/*max_pf_ceiling*/ {0, 0},
272	/*flags2*/ 0,
273	/*cache_segments*/ 0,
274	/*cache_seg_size*/ {0, 0},
275	/*reserved*/ 0,
276	/*non_cache_seg_size*/ {0, 0, 0}
277};
278
279static struct scsi_control_page control_page_default = {
280	/*page_code*/SMS_CONTROL_MODE_PAGE,
281	/*page_length*/sizeof(struct scsi_control_page) - 2,
282	/*rlec*/0,
283	/*queue_flags*/0,
284	/*eca_and_aen*/0,
285	/*flags4*/SCP_TAS,
286	/*aen_holdoff_period*/{0, 0},
287	/*busy_timeout_period*/{0, 0},
288	/*extended_selftest_completion_time*/{0, 0}
289};
290
291static struct scsi_control_page control_page_changeable = {
292	/*page_code*/SMS_CONTROL_MODE_PAGE,
293	/*page_length*/sizeof(struct scsi_control_page) - 2,
294	/*rlec*/SCP_DSENSE,
295	/*queue_flags*/0,
296	/*eca_and_aen*/0,
297	/*flags4*/0,
298	/*aen_holdoff_period*/{0, 0},
299	/*busy_timeout_period*/{0, 0},
300	/*extended_selftest_completion_time*/{0, 0}
301};
302
303
304/*
305 * XXX KDM move these into the softc.
306 */
307static int rcv_sync_msg;
308static int persis_offset;
309static uint8_t ctl_pause_rtr;
310static int     ctl_is_single = 1;
311static int     index_to_aps_page;
312
313SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314static int worker_threads = -1;
315SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316    &worker_threads, 1, "Number of worker threads");
317static int verbose = 0;
318SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319    &verbose, 0, "Show SCSI errors returned to initiator");
320
321/*
322 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323 * SCSI Ports (0x88), Block limits (0xB0) and
324 * Logical Block Provisioning (0xB2)
325 */
326#define SCSI_EVPD_NUM_SUPPORTED_PAGES	6
327
328static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
329				  int param);
330static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
331static int ctl_init(void);
332void ctl_shutdown(void);
333static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
334static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
335static void ctl_ioctl_online(void *arg);
336static void ctl_ioctl_offline(void *arg);
337static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
338static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
339static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
340static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
341static int ctl_ioctl_submit_wait(union ctl_io *io);
342static void ctl_ioctl_datamove(union ctl_io *io);
343static void ctl_ioctl_done(union ctl_io *io);
344static void ctl_ioctl_hard_startstop_callback(void *arg,
345					      struct cfi_metatask *metatask);
346static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
347static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
348			      struct ctl_ooa *ooa_hdr,
349			      struct ctl_ooa_entry *kern_entries);
350static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
351		     struct thread *td);
352uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
353uint32_t ctl_port_idx(int port_num);
354static uint32_t ctl_map_lun(int port_num, uint32_t lun);
355static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
356#ifdef unused
357static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
358				   uint32_t targ_target, uint32_t targ_lun,
359				   int can_wait);
360static void ctl_kfree_io(union ctl_io *io);
361#endif /* unused */
362static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
363			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
364static int ctl_free_lun(struct ctl_lun *lun);
365static void ctl_create_lun(struct ctl_be_lun *be_lun);
366/**
367static void ctl_failover_change_pages(struct ctl_softc *softc,
368				      struct ctl_scsiio *ctsio, int master);
369**/
370
371static int ctl_do_mode_select(union ctl_io *io);
372static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
373			   uint64_t res_key, uint64_t sa_res_key,
374			   uint8_t type, uint32_t residx,
375			   struct ctl_scsiio *ctsio,
376			   struct scsi_per_res_out *cdb,
377			   struct scsi_per_res_out_parms* param);
378static void ctl_pro_preempt_other(struct ctl_lun *lun,
379				  union ctl_ha_msg *msg);
380static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
381static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
382static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
383static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
385					 int alloc_len);
386static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
387					 int alloc_len);
388static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
389static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
390static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
391static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
392static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
393static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
394					 union ctl_io *ooa_io);
395static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
396				union ctl_io *starting_io);
397static int ctl_check_blocked(struct ctl_lun *lun);
398static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
399				struct ctl_lun *lun,
400				const struct ctl_cmd_entry *entry,
401				struct ctl_scsiio *ctsio);
402//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
403static void ctl_failover(void);
404static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
405			       struct ctl_scsiio *ctsio);
406static int ctl_scsiio(struct ctl_scsiio *ctsio);
407
408static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
409static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
410			    ctl_ua_type ua_type);
411static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
412			 ctl_ua_type ua_type);
413static int ctl_abort_task(union ctl_io *io);
414static int ctl_abort_task_set(union ctl_io *io);
415static int ctl_i_t_nexus_reset(union ctl_io *io);
416static void ctl_run_task(union ctl_io *io);
417#ifdef CTL_IO_DELAY
418static void ctl_datamove_timer_wakeup(void *arg);
419static void ctl_done_timer_wakeup(void *arg);
420#endif /* CTL_IO_DELAY */
421
422static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
423static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
424static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
425static void ctl_datamove_remote_write(union ctl_io *io);
426static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
427static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
428static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
429static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
430				    ctl_ha_dt_cb callback);
431static void ctl_datamove_remote_read(union ctl_io *io);
432static void ctl_datamove_remote(union ctl_io *io);
433static int ctl_process_done(union ctl_io *io);
434static void ctl_lun_thread(void *arg);
435static void ctl_work_thread(void *arg);
436static void ctl_enqueue_incoming(union ctl_io *io);
437static void ctl_enqueue_rtr(union ctl_io *io);
438static void ctl_enqueue_done(union ctl_io *io);
439static void ctl_enqueue_isc(union ctl_io *io);
440static const struct ctl_cmd_entry *
441    ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
442static const struct ctl_cmd_entry *
443    ctl_validate_command(struct ctl_scsiio *ctsio);
444static int ctl_cmd_applicable(uint8_t lun_type,
445    const struct ctl_cmd_entry *entry);
446
447/*
448 * Load the serialization table.  This isn't very pretty, but is probably
449 * the easiest way to do it.
450 */
451#include "ctl_ser_table.c"
452
453/*
454 * We only need to define open, close and ioctl routines for this driver.
455 */
456static struct cdevsw ctl_cdevsw = {
457	.d_version =	D_VERSION,
458	.d_flags =	0,
459	.d_open =	ctl_open,
460	.d_close =	ctl_close,
461	.d_ioctl =	ctl_ioctl,
462	.d_name =	"ctl",
463};
464
465
466MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
467MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
468
469static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
470
471static moduledata_t ctl_moduledata = {
472	"ctl",
473	ctl_module_event_handler,
474	NULL
475};
476
477DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
478MODULE_VERSION(ctl, 1);
479
480static struct ctl_frontend ioctl_frontend =
481{
482	.name = "ioctl",
483};
484
485static void
486ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
487			    union ctl_ha_msg *msg_info)
488{
489	struct ctl_scsiio *ctsio;
490
491	if (msg_info->hdr.original_sc == NULL) {
492		printf("%s: original_sc == NULL!\n", __func__);
493		/* XXX KDM now what? */
494		return;
495	}
496
497	ctsio = &msg_info->hdr.original_sc->scsiio;
498	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
499	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
500	ctsio->io_hdr.status = msg_info->hdr.status;
501	ctsio->scsi_status = msg_info->scsi.scsi_status;
502	ctsio->sense_len = msg_info->scsi.sense_len;
503	ctsio->sense_residual = msg_info->scsi.sense_residual;
504	ctsio->residual = msg_info->scsi.residual;
505	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
506	       sizeof(ctsio->sense_data));
507	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
508	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
509	ctl_enqueue_isc((union ctl_io *)ctsio);
510}
511
512static void
513ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
514				union ctl_ha_msg *msg_info)
515{
516	struct ctl_scsiio *ctsio;
517
518	if (msg_info->hdr.serializing_sc == NULL) {
519		printf("%s: serializing_sc == NULL!\n", __func__);
520		/* XXX KDM now what? */
521		return;
522	}
523
524	ctsio = &msg_info->hdr.serializing_sc->scsiio;
525#if 0
526	/*
527	 * Attempt to catch the situation where an I/O has
528	 * been freed, and we're using it again.
529	 */
530	if (ctsio->io_hdr.io_type == 0xff) {
531		union ctl_io *tmp_io;
532		tmp_io = (union ctl_io *)ctsio;
533		printf("%s: %p use after free!\n", __func__,
534		       ctsio);
535		printf("%s: type %d msg %d cdb %x iptl: "
536		       "%d:%d:%d:%d tag 0x%04x "
537		       "flag %#x status %x\n",
538			__func__,
539			tmp_io->io_hdr.io_type,
540			tmp_io->io_hdr.msg_type,
541			tmp_io->scsiio.cdb[0],
542			tmp_io->io_hdr.nexus.initid.id,
543			tmp_io->io_hdr.nexus.targ_port,
544			tmp_io->io_hdr.nexus.targ_target.id,
545			tmp_io->io_hdr.nexus.targ_lun,
546			(tmp_io->io_hdr.io_type ==
547			CTL_IO_TASK) ?
548			tmp_io->taskio.tag_num :
549			tmp_io->scsiio.tag_num,
550		        tmp_io->io_hdr.flags,
551			tmp_io->io_hdr.status);
552	}
553#endif
554	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
555	ctl_enqueue_isc((union ctl_io *)ctsio);
556}
557
558/*
559 * ISC (Inter Shelf Communication) event handler.  Events from the HA
560 * subsystem come in here.
561 */
562static void
563ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
564{
565	struct ctl_softc *ctl_softc;
566	union ctl_io *io;
567	struct ctl_prio *presio;
568	ctl_ha_status isc_status;
569
570	ctl_softc = control_softc;
571	io = NULL;
572
573
574#if 0
575	printf("CTL: Isc Msg event %d\n", event);
576#endif
577	if (event == CTL_HA_EVT_MSG_RECV) {
578		union ctl_ha_msg msg_info;
579
580		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
581					     sizeof(msg_info), /*wait*/ 0);
582#if 0
583		printf("CTL: msg_type %d\n", msg_info.msg_type);
584#endif
585		if (isc_status != 0) {
586			printf("Error receiving message, status = %d\n",
587			       isc_status);
588			return;
589		}
590
591		switch (msg_info.hdr.msg_type) {
592		case CTL_MSG_SERIALIZE:
593#if 0
594			printf("Serialize\n");
595#endif
596			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
597			if (io == NULL) {
598				printf("ctl_isc_event_handler: can't allocate "
599				       "ctl_io!\n");
600				/* Bad Juju */
601				/* Need to set busy and send msg back */
602				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
603				msg_info.hdr.status = CTL_SCSI_ERROR;
604				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
605				msg_info.scsi.sense_len = 0;
606			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
607				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
608				}
609				goto bailout;
610			}
611			ctl_zero_io(io);
612			// populate ctsio from msg_info
613			io->io_hdr.io_type = CTL_IO_SCSI;
614			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
615			io->io_hdr.original_sc = msg_info.hdr.original_sc;
616#if 0
617			printf("pOrig %x\n", (int)msg_info.original_sc);
618#endif
619			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
620					    CTL_FLAG_IO_ACTIVE;
621			/*
622			 * If we're in serialization-only mode, we don't
623			 * want to go through full done processing.  Thus
624			 * the COPY flag.
625			 *
626			 * XXX KDM add another flag that is more specific.
627			 */
628			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
629				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
630			io->io_hdr.nexus = msg_info.hdr.nexus;
631#if 0
632			printf("targ %d, port %d, iid %d, lun %d\n",
633			       io->io_hdr.nexus.targ_target.id,
634			       io->io_hdr.nexus.targ_port,
635			       io->io_hdr.nexus.initid.id,
636			       io->io_hdr.nexus.targ_lun);
637#endif
638			io->scsiio.tag_num = msg_info.scsi.tag_num;
639			io->scsiio.tag_type = msg_info.scsi.tag_type;
640			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
641			       CTL_MAX_CDBLEN);
642			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
643				const struct ctl_cmd_entry *entry;
644
645				entry = ctl_get_cmd_entry(&io->scsiio);
646				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
647				io->io_hdr.flags |=
648					entry->flags & CTL_FLAG_DATA_MASK;
649			}
650			ctl_enqueue_isc(io);
651			break;
652
653		/* Performed on the Originating SC, XFER mode only */
654		case CTL_MSG_DATAMOVE: {
655			struct ctl_sg_entry *sgl;
656			int i, j;
657
658			io = msg_info.hdr.original_sc;
659			if (io == NULL) {
660				printf("%s: original_sc == NULL!\n", __func__);
661				/* XXX KDM do something here */
662				break;
663			}
664			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
665			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
666			/*
667			 * Keep track of this, we need to send it back over
668			 * when the datamove is complete.
669			 */
670			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
671
672			if (msg_info.dt.sg_sequence == 0) {
673				/*
674				 * XXX KDM we use the preallocated S/G list
675				 * here, but we'll need to change this to
676				 * dynamic allocation if we need larger S/G
677				 * lists.
678				 */
679				if (msg_info.dt.kern_sg_entries >
680				    sizeof(io->io_hdr.remote_sglist) /
681				    sizeof(io->io_hdr.remote_sglist[0])) {
682					printf("%s: number of S/G entries "
683					    "needed %u > allocated num %zd\n",
684					    __func__,
685					    msg_info.dt.kern_sg_entries,
686					    sizeof(io->io_hdr.remote_sglist)/
687					    sizeof(io->io_hdr.remote_sglist[0]));
688
689					/*
690					 * XXX KDM send a message back to
691					 * the other side to shut down the
692					 * DMA.  The error will come back
693					 * through via the normal channel.
694					 */
695					break;
696				}
697				sgl = io->io_hdr.remote_sglist;
698				memset(sgl, 0,
699				       sizeof(io->io_hdr.remote_sglist));
700
701				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
702
703				io->scsiio.kern_sg_entries =
704					msg_info.dt.kern_sg_entries;
705				io->scsiio.rem_sg_entries =
706					msg_info.dt.kern_sg_entries;
707				io->scsiio.kern_data_len =
708					msg_info.dt.kern_data_len;
709				io->scsiio.kern_total_len =
710					msg_info.dt.kern_total_len;
711				io->scsiio.kern_data_resid =
712					msg_info.dt.kern_data_resid;
713				io->scsiio.kern_rel_offset =
714					msg_info.dt.kern_rel_offset;
715				/*
716				 * Clear out per-DMA flags.
717				 */
718				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
719				/*
720				 * Add per-DMA flags that are set for this
721				 * particular DMA request.
722				 */
723				io->io_hdr.flags |= msg_info.dt.flags &
724						    CTL_FLAG_RDMA_MASK;
725			} else
726				sgl = (struct ctl_sg_entry *)
727					io->scsiio.kern_data_ptr;
728
729			for (i = msg_info.dt.sent_sg_entries, j = 0;
730			     i < (msg_info.dt.sent_sg_entries +
731			     msg_info.dt.cur_sg_entries); i++, j++) {
732				sgl[i].addr = msg_info.dt.sg_list[j].addr;
733				sgl[i].len = msg_info.dt.sg_list[j].len;
734
735#if 0
736				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
737				       __func__,
738				       msg_info.dt.sg_list[j].addr,
739				       msg_info.dt.sg_list[j].len,
740				       sgl[i].addr, sgl[i].len, j, i);
741#endif
742			}
743#if 0
744			memcpy(&sgl[msg_info.dt.sent_sg_entries],
745			       msg_info.dt.sg_list,
746			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
747#endif
748
749			/*
750			 * If this is the last piece of the I/O, we've got
751			 * the full S/G list.  Queue processing in the thread.
752			 * Otherwise wait for the next piece.
753			 */
754			if (msg_info.dt.sg_last != 0)
755				ctl_enqueue_isc(io);
756			break;
757		}
758		/* Performed on the Serializing (primary) SC, XFER mode only */
759		case CTL_MSG_DATAMOVE_DONE: {
760			if (msg_info.hdr.serializing_sc == NULL) {
761				printf("%s: serializing_sc == NULL!\n",
762				       __func__);
763				/* XXX KDM now what? */
764				break;
765			}
766			/*
767			 * We grab the sense information here in case
768			 * there was a failure, so we can return status
769			 * back to the initiator.
770			 */
771			io = msg_info.hdr.serializing_sc;
772			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
773			io->io_hdr.status = msg_info.hdr.status;
774			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
775			io->scsiio.sense_len = msg_info.scsi.sense_len;
776			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
777			io->io_hdr.port_status = msg_info.scsi.fetd_status;
778			io->scsiio.residual = msg_info.scsi.residual;
779			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
780			       sizeof(io->scsiio.sense_data));
781			ctl_enqueue_isc(io);
782			break;
783		}
784
785		/* Preformed on Originating SC, SER_ONLY mode */
786		case CTL_MSG_R2R:
787			io = msg_info.hdr.original_sc;
788			if (io == NULL) {
789				printf("%s: Major Bummer\n", __func__);
790				return;
791			} else {
792#if 0
793				printf("pOrig %x\n",(int) ctsio);
794#endif
795			}
796			io->io_hdr.msg_type = CTL_MSG_R2R;
797			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
798			ctl_enqueue_isc(io);
799			break;
800
801		/*
802		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
803		 * mode.
804		 * Performed on the Originating (i.e. secondary) SC in XFER
805		 * mode
806		 */
807		case CTL_MSG_FINISH_IO:
808			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
809				ctl_isc_handler_finish_xfer(ctl_softc,
810							    &msg_info);
811			else
812				ctl_isc_handler_finish_ser_only(ctl_softc,
813								&msg_info);
814			break;
815
816		/* Preformed on Originating SC */
817		case CTL_MSG_BAD_JUJU:
818			io = msg_info.hdr.original_sc;
819			if (io == NULL) {
820				printf("%s: Bad JUJU!, original_sc is NULL!\n",
821				       __func__);
822				break;
823			}
824			ctl_copy_sense_data(&msg_info, io);
825			/*
826			 * IO should have already been cleaned up on other
827			 * SC so clear this flag so we won't send a message
828			 * back to finish the IO there.
829			 */
830			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
831			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
832
833			/* io = msg_info.hdr.serializing_sc; */
834			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
835			ctl_enqueue_isc(io);
836			break;
837
838		/* Handle resets sent from the other side */
839		case CTL_MSG_MANAGE_TASKS: {
840			struct ctl_taskio *taskio;
841			taskio = (struct ctl_taskio *)ctl_alloc_io(
842				(void *)ctl_softc->othersc_pool);
843			if (taskio == NULL) {
844				printf("ctl_isc_event_handler: can't allocate "
845				       "ctl_io!\n");
846				/* Bad Juju */
847				/* should I just call the proper reset func
848				   here??? */
849				goto bailout;
850			}
851			ctl_zero_io((union ctl_io *)taskio);
852			taskio->io_hdr.io_type = CTL_IO_TASK;
853			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
854			taskio->io_hdr.nexus = msg_info.hdr.nexus;
855			taskio->task_action = msg_info.task.task_action;
856			taskio->tag_num = msg_info.task.tag_num;
857			taskio->tag_type = msg_info.task.tag_type;
858#ifdef CTL_TIME_IO
859			taskio->io_hdr.start_time = time_uptime;
860			getbintime(&taskio->io_hdr.start_bt);
861#if 0
862			cs_prof_gettime(&taskio->io_hdr.start_ticks);
863#endif
864#endif /* CTL_TIME_IO */
865			ctl_run_task((union ctl_io *)taskio);
866			break;
867		}
868		/* Persistent Reserve action which needs attention */
869		case CTL_MSG_PERS_ACTION:
870			presio = (struct ctl_prio *)ctl_alloc_io(
871				(void *)ctl_softc->othersc_pool);
872			if (presio == NULL) {
873				printf("ctl_isc_event_handler: can't allocate "
874				       "ctl_io!\n");
875				/* Bad Juju */
876				/* Need to set busy and send msg back */
877				goto bailout;
878			}
879			ctl_zero_io((union ctl_io *)presio);
880			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
881			presio->pr_msg = msg_info.pr;
882			ctl_enqueue_isc((union ctl_io *)presio);
883			break;
884		case CTL_MSG_SYNC_FE:
885			rcv_sync_msg = 1;
886			break;
887		case CTL_MSG_APS_LOCK: {
888			// It's quicker to execute this then to
889			// queue it.
890			struct ctl_lun *lun;
891			struct ctl_page_index *page_index;
892			struct copan_aps_subpage *current_sp;
893			uint32_t targ_lun;
894
895			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
896			lun = ctl_softc->ctl_luns[targ_lun];
897			mtx_lock(&lun->lun_lock);
898			page_index = &lun->mode_pages.index[index_to_aps_page];
899			current_sp = (struct copan_aps_subpage *)
900				     (page_index->page_data +
901				     (page_index->page_len * CTL_PAGE_CURRENT));
902
903			current_sp->lock_active = msg_info.aps.lock_flag;
904			mtx_unlock(&lun->lun_lock);
905		        break;
906		}
907		default:
908		        printf("How did I get here?\n");
909		}
910	} else if (event == CTL_HA_EVT_MSG_SENT) {
911		if (param != CTL_HA_STATUS_SUCCESS) {
912			printf("Bad status from ctl_ha_msg_send status %d\n",
913			       param);
914		}
915		return;
916	} else if (event == CTL_HA_EVT_DISCONNECT) {
917		printf("CTL: Got a disconnect from Isc\n");
918		return;
919	} else {
920		printf("ctl_isc_event_handler: Unknown event %d\n", event);
921		return;
922	}
923
924bailout:
925	return;
926}
927
928static void
929ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
930{
931	struct scsi_sense_data *sense;
932
933	sense = &dest->scsiio.sense_data;
934	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
935	dest->scsiio.scsi_status = src->scsi.scsi_status;
936	dest->scsiio.sense_len = src->scsi.sense_len;
937	dest->io_hdr.status = src->hdr.status;
938}
939
940static int
941ctl_init(void)
942{
943	struct ctl_softc *softc;
944	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
945	struct ctl_port *port;
946        uint8_t sc_id =0;
947	int i, error, retval;
948	//int isc_retval;
949
950	retval = 0;
951	ctl_pause_rtr = 0;
952        rcv_sync_msg = 0;
953
954	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
955			       M_WAITOK | M_ZERO);
956	softc = control_softc;
957
958	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
959			      "cam/ctl");
960
961	softc->dev->si_drv1 = softc;
962
963	/*
964	 * By default, return a "bad LUN" peripheral qualifier for unknown
965	 * LUNs.  The user can override this default using the tunable or
966	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
967	 */
968	softc->inquiry_pq_no_lun = 1;
969	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
970			  &softc->inquiry_pq_no_lun);
971	sysctl_ctx_init(&softc->sysctl_ctx);
972	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
973		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
974		CTLFLAG_RD, 0, "CAM Target Layer");
975
976	if (softc->sysctl_tree == NULL) {
977		printf("%s: unable to allocate sysctl tree\n", __func__);
978		destroy_dev(softc->dev);
979		free(control_softc, M_DEVBUF);
980		control_softc = NULL;
981		return (ENOMEM);
982	}
983
984	SYSCTL_ADD_INT(&softc->sysctl_ctx,
985		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
986		       "inquiry_pq_no_lun", CTLFLAG_RW,
987		       &softc->inquiry_pq_no_lun, 0,
988		       "Report no lun possible for invalid LUNs");
989
990	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
991	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
992	softc->open_count = 0;
993
994	/*
995	 * Default to actually sending a SYNCHRONIZE CACHE command down to
996	 * the drive.
997	 */
998	softc->flags = CTL_FLAG_REAL_SYNC;
999
1000	/*
1001	 * In Copan's HA scheme, the "master" and "slave" roles are
1002	 * figured out through the slot the controller is in.  Although it
1003	 * is an active/active system, someone has to be in charge.
1004 	 */
1005#ifdef NEEDTOPORT
1006        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1007#endif
1008
1009        if (sc_id == 0) {
1010		softc->flags |= CTL_FLAG_MASTER_SHELF;
1011		persis_offset = 0;
1012	} else
1013		persis_offset = CTL_MAX_INITIATORS;
1014
1015	/*
1016	 * XXX KDM need to figure out where we want to get our target ID
1017	 * and WWID.  Is it different on each port?
1018	 */
1019	softc->target.id = 0;
1020	softc->target.wwid[0] = 0x12345678;
1021	softc->target.wwid[1] = 0x87654321;
1022	STAILQ_INIT(&softc->lun_list);
1023	STAILQ_INIT(&softc->pending_lun_queue);
1024	STAILQ_INIT(&softc->fe_list);
1025	STAILQ_INIT(&softc->port_list);
1026	STAILQ_INIT(&softc->be_list);
1027	STAILQ_INIT(&softc->io_pools);
1028
1029	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1030			    &internal_pool)!= 0){
1031		printf("ctl: can't allocate %d entry internal pool, "
1032		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1033		return (ENOMEM);
1034	}
1035
1036	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1037			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1038		printf("ctl: can't allocate %d entry emergency pool, "
1039		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1040		ctl_pool_free(internal_pool);
1041		return (ENOMEM);
1042	}
1043
1044	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1045	                    &other_pool) != 0)
1046	{
1047		printf("ctl: can't allocate %d entry other SC pool, "
1048		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1049		ctl_pool_free(internal_pool);
1050		ctl_pool_free(emergency_pool);
1051		return (ENOMEM);
1052	}
1053
1054	softc->internal_pool = internal_pool;
1055	softc->emergency_pool = emergency_pool;
1056	softc->othersc_pool = other_pool;
1057
1058	if (worker_threads <= 0)
1059		worker_threads = max(1, mp_ncpus / 4);
1060	if (worker_threads > CTL_MAX_THREADS)
1061		worker_threads = CTL_MAX_THREADS;
1062
1063	for (i = 0; i < worker_threads; i++) {
1064		struct ctl_thread *thr = &softc->threads[i];
1065
1066		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1067		thr->ctl_softc = softc;
1068		STAILQ_INIT(&thr->incoming_queue);
1069		STAILQ_INIT(&thr->rtr_queue);
1070		STAILQ_INIT(&thr->done_queue);
1071		STAILQ_INIT(&thr->isc_queue);
1072
1073		error = kproc_kthread_add(ctl_work_thread, thr,
1074		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1075		if (error != 0) {
1076			printf("error creating CTL work thread!\n");
1077			ctl_pool_free(internal_pool);
1078			ctl_pool_free(emergency_pool);
1079			ctl_pool_free(other_pool);
1080			return (error);
1081		}
1082	}
1083	error = kproc_kthread_add(ctl_lun_thread, softc,
1084	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1085	if (error != 0) {
1086		printf("error creating CTL lun thread!\n");
1087		ctl_pool_free(internal_pool);
1088		ctl_pool_free(emergency_pool);
1089		ctl_pool_free(other_pool);
1090		return (error);
1091	}
1092	if (bootverbose)
1093		printf("ctl: CAM Target Layer loaded\n");
1094
1095	/*
1096	 * Initialize the ioctl front end.
1097	 */
1098	ctl_frontend_register(&ioctl_frontend);
1099	port = &softc->ioctl_info.port;
1100	port->frontend = &ioctl_frontend;
1101	sprintf(softc->ioctl_info.port_name, "ioctl");
1102	port->port_type = CTL_PORT_IOCTL;
1103	port->num_requested_ctl_io = 100;
1104	port->port_name = softc->ioctl_info.port_name;
1105	port->port_online = ctl_ioctl_online;
1106	port->port_offline = ctl_ioctl_offline;
1107	port->onoff_arg = &softc->ioctl_info;
1108	port->lun_enable = ctl_ioctl_lun_enable;
1109	port->lun_disable = ctl_ioctl_lun_disable;
1110	port->targ_lun_arg = &softc->ioctl_info;
1111	port->fe_datamove = ctl_ioctl_datamove;
1112	port->fe_done = ctl_ioctl_done;
1113	port->max_targets = 15;
1114	port->max_target_id = 15;
1115
1116	if (ctl_port_register(&softc->ioctl_info.port,
1117	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1118		printf("ctl: ioctl front end registration failed, will "
1119		       "continue anyway\n");
1120	}
1121
1122#ifdef CTL_IO_DELAY
1123	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1124		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1125		       sizeof(struct callout), CTL_TIMER_BYTES);
1126		return (EINVAL);
1127	}
1128#endif /* CTL_IO_DELAY */
1129
1130	return (0);
1131}
1132
1133void
1134ctl_shutdown(void)
1135{
1136	struct ctl_softc *softc;
1137	struct ctl_lun *lun, *next_lun;
1138	struct ctl_io_pool *pool;
1139
1140	softc = (struct ctl_softc *)control_softc;
1141
1142	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1143		printf("ctl: ioctl front end deregistration failed\n");
1144
1145	mtx_lock(&softc->ctl_lock);
1146
1147	/*
1148	 * Free up each LUN.
1149	 */
1150	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1151		next_lun = STAILQ_NEXT(lun, links);
1152		ctl_free_lun(lun);
1153	}
1154
1155	mtx_unlock(&softc->ctl_lock);
1156
1157	ctl_frontend_deregister(&ioctl_frontend);
1158
1159	/*
1160	 * This will rip the rug out from under any FETDs or anyone else
1161	 * that has a pool allocated.  Since we increment our module
1162	 * refcount any time someone outside the main CTL module allocates
1163	 * a pool, we shouldn't have any problems here.  The user won't be
1164	 * able to unload the CTL module until client modules have
1165	 * successfully unloaded.
1166	 */
1167	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1168		ctl_pool_free(pool);
1169
1170#if 0
1171	ctl_shutdown_thread(softc->work_thread);
1172	mtx_destroy(&softc->queue_lock);
1173#endif
1174
1175	mtx_destroy(&softc->pool_lock);
1176	mtx_destroy(&softc->ctl_lock);
1177
1178	destroy_dev(softc->dev);
1179
1180	sysctl_ctx_free(&softc->sysctl_ctx);
1181
1182	free(control_softc, M_DEVBUF);
1183	control_softc = NULL;
1184
1185	if (bootverbose)
1186		printf("ctl: CAM Target Layer unloaded\n");
1187}
1188
1189static int
1190ctl_module_event_handler(module_t mod, int what, void *arg)
1191{
1192
1193	switch (what) {
1194	case MOD_LOAD:
1195		return (ctl_init());
1196	case MOD_UNLOAD:
1197		return (EBUSY);
1198	default:
1199		return (EOPNOTSUPP);
1200	}
1201}
1202
1203/*
1204 * XXX KDM should we do some access checks here?  Bump a reference count to
1205 * prevent a CTL module from being unloaded while someone has it open?
1206 */
1207static int
1208ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1209{
1210	return (0);
1211}
1212
1213static int
1214ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1215{
1216	return (0);
1217}
1218
1219int
1220ctl_port_enable(ctl_port_type port_type)
1221{
1222	struct ctl_softc *softc;
1223	struct ctl_port *port;
1224
1225	if (ctl_is_single == 0) {
1226		union ctl_ha_msg msg_info;
1227		int isc_retval;
1228
1229#if 0
1230		printf("%s: HA mode, synchronizing frontend enable\n",
1231		        __func__);
1232#endif
1233		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1234	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1235		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1236			printf("Sync msg send error retval %d\n", isc_retval);
1237		}
1238		if (!rcv_sync_msg) {
1239			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1240			        sizeof(msg_info), 1);
1241		}
1242#if 0
1243        	printf("CTL:Frontend Enable\n");
1244	} else {
1245		printf("%s: single mode, skipping frontend synchronization\n",
1246		        __func__);
1247#endif
1248	}
1249
1250	softc = control_softc;
1251
1252	STAILQ_FOREACH(port, &softc->port_list, links) {
1253		if (port_type & port->port_type)
1254		{
1255#if 0
1256			printf("port %d\n", port->targ_port);
1257#endif
1258			ctl_port_online(port);
1259		}
1260	}
1261
1262	return (0);
1263}
1264
1265int
1266ctl_port_disable(ctl_port_type port_type)
1267{
1268	struct ctl_softc *softc;
1269	struct ctl_port *port;
1270
1271	softc = control_softc;
1272
1273	STAILQ_FOREACH(port, &softc->port_list, links) {
1274		if (port_type & port->port_type)
1275			ctl_port_offline(port);
1276	}
1277
1278	return (0);
1279}
1280
1281/*
1282 * Returns 0 for success, 1 for failure.
1283 * Currently the only failure mode is if there aren't enough entries
1284 * allocated.  So, in case of a failure, look at num_entries_dropped,
1285 * reallocate and try again.
1286 */
1287int
1288ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1289	      int *num_entries_filled, int *num_entries_dropped,
1290	      ctl_port_type port_type, int no_virtual)
1291{
1292	struct ctl_softc *softc;
1293	struct ctl_port *port;
1294	int entries_dropped, entries_filled;
1295	int retval;
1296	int i;
1297
1298	softc = control_softc;
1299
1300	retval = 0;
1301	entries_filled = 0;
1302	entries_dropped = 0;
1303
1304	i = 0;
1305	mtx_lock(&softc->ctl_lock);
1306	STAILQ_FOREACH(port, &softc->port_list, links) {
1307		struct ctl_port_entry *entry;
1308
1309		if ((port->port_type & port_type) == 0)
1310			continue;
1311
1312		if ((no_virtual != 0)
1313		 && (port->virtual_port != 0))
1314			continue;
1315
1316		if (entries_filled >= num_entries_alloced) {
1317			entries_dropped++;
1318			continue;
1319		}
1320		entry = &entries[i];
1321
1322		entry->port_type = port->port_type;
1323		strlcpy(entry->port_name, port->port_name,
1324			sizeof(entry->port_name));
1325		entry->physical_port = port->physical_port;
1326		entry->virtual_port = port->virtual_port;
1327		entry->wwnn = port->wwnn;
1328		entry->wwpn = port->wwpn;
1329
1330		i++;
1331		entries_filled++;
1332	}
1333
1334	mtx_unlock(&softc->ctl_lock);
1335
1336	if (entries_dropped > 0)
1337		retval = 1;
1338
1339	*num_entries_dropped = entries_dropped;
1340	*num_entries_filled = entries_filled;
1341
1342	return (retval);
1343}
1344
1345static void
1346ctl_ioctl_online(void *arg)
1347{
1348	struct ctl_ioctl_info *ioctl_info;
1349
1350	ioctl_info = (struct ctl_ioctl_info *)arg;
1351
1352	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1353}
1354
1355static void
1356ctl_ioctl_offline(void *arg)
1357{
1358	struct ctl_ioctl_info *ioctl_info;
1359
1360	ioctl_info = (struct ctl_ioctl_info *)arg;
1361
1362	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1363}
1364
1365/*
1366 * Remove an initiator by port number and initiator ID.
1367 * Returns 0 for success, -1 for failure.
1368 */
1369int
1370ctl_remove_initiator(struct ctl_port *port, int iid)
1371{
1372	struct ctl_softc *softc = control_softc;
1373
1374	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1375
1376	if (iid > CTL_MAX_INIT_PER_PORT) {
1377		printf("%s: initiator ID %u > maximun %u!\n",
1378		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1379		return (-1);
1380	}
1381
1382	mtx_lock(&softc->ctl_lock);
1383	port->wwpn_iid[iid].in_use--;
1384	port->wwpn_iid[iid].last_use = time_uptime;
1385	mtx_unlock(&softc->ctl_lock);
1386
1387	return (0);
1388}
1389
1390/*
1391 * Add an initiator to the initiator map.
1392 * Returns iid for success, < 0 for failure.
1393 */
1394int
1395ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1396{
1397	struct ctl_softc *softc = control_softc;
1398	time_t best_time;
1399	int i, best;
1400
1401	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1402
1403	if (iid >= CTL_MAX_INIT_PER_PORT) {
1404		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1405		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1406		free(name, M_CTL);
1407		return (-1);
1408	}
1409
1410	mtx_lock(&softc->ctl_lock);
1411
1412	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1413		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1414			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1415				iid = i;
1416				break;
1417			}
1418			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1419			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1420				iid = i;
1421				break;
1422			}
1423		}
1424	}
1425
1426	if (iid < 0) {
1427		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1428			if (port->wwpn_iid[i].in_use == 0 &&
1429			    port->wwpn_iid[i].wwpn == 0 &&
1430			    port->wwpn_iid[i].name == NULL) {
1431				iid = i;
1432				break;
1433			}
1434		}
1435	}
1436
1437	if (iid < 0) {
1438		best = -1;
1439		best_time = INT32_MAX;
1440		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1441			if (port->wwpn_iid[i].in_use == 0) {
1442				if (port->wwpn_iid[i].last_use < best_time) {
1443					best = i;
1444					best_time = port->wwpn_iid[i].last_use;
1445				}
1446			}
1447		}
1448		iid = best;
1449	}
1450
1451	if (iid < 0) {
1452		mtx_unlock(&softc->ctl_lock);
1453		free(name, M_CTL);
1454		return (-2);
1455	}
1456
1457	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1458		/*
1459		 * This is not an error yet.
1460		 */
1461		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1462#if 0
1463			printf("%s: port %d iid %u WWPN %#jx arrived"
1464			    " again\n", __func__, port->targ_port,
1465			    iid, (uintmax_t)wwpn);
1466#endif
1467			goto take;
1468		}
1469		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1470		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1471#if 0
1472			printf("%s: port %d iid %u name '%s' arrived"
1473			    " again\n", __func__, port->targ_port,
1474			    iid, name);
1475#endif
1476			goto take;
1477		}
1478
1479		/*
1480		 * This is an error, but what do we do about it?  The
1481		 * driver is telling us we have a new WWPN for this
1482		 * initiator ID, so we pretty much need to use it.
1483		 */
1484		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1485		    " but WWPN %#jx '%s' is still at that address\n",
1486		    __func__, port->targ_port, iid, wwpn, name,
1487		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1488		    port->wwpn_iid[iid].name);
1489
1490		/*
1491		 * XXX KDM clear have_ca and ua_pending on each LUN for
1492		 * this initiator.
1493		 */
1494	}
1495take:
1496	free(port->wwpn_iid[iid].name, M_CTL);
1497	port->wwpn_iid[iid].name = name;
1498	port->wwpn_iid[iid].wwpn = wwpn;
1499	port->wwpn_iid[iid].in_use++;
1500	mtx_unlock(&softc->ctl_lock);
1501
1502	return (iid);
1503}
1504
1505static int
1506ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1507{
1508	int len;
1509
1510	switch (port->port_type) {
1511	case CTL_PORT_FC:
1512	{
1513		struct scsi_transportid_fcp *id =
1514		    (struct scsi_transportid_fcp *)buf;
1515		if (port->wwpn_iid[iid].wwpn == 0)
1516			return (0);
1517		memset(id, 0, sizeof(*id));
1518		id->format_protocol = SCSI_PROTO_FC;
1519		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1520		return (sizeof(*id));
1521	}
1522	case CTL_PORT_ISCSI:
1523	{
1524		struct scsi_transportid_iscsi_port *id =
1525		    (struct scsi_transportid_iscsi_port *)buf;
1526		if (port->wwpn_iid[iid].name == NULL)
1527			return (0);
1528		memset(id, 0, 256);
1529		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1530		    SCSI_PROTO_ISCSI;
1531		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1532		len = roundup2(min(len, 252), 4);
1533		scsi_ulto2b(len, id->additional_length);
1534		return (sizeof(*id) + len);
1535	}
1536	case CTL_PORT_SAS:
1537	{
1538		struct scsi_transportid_sas *id =
1539		    (struct scsi_transportid_sas *)buf;
1540		if (port->wwpn_iid[iid].wwpn == 0)
1541			return (0);
1542		memset(id, 0, sizeof(*id));
1543		id->format_protocol = SCSI_PROTO_SAS;
1544		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1545		return (sizeof(*id));
1546	}
1547	default:
1548	{
1549		struct scsi_transportid_spi *id =
1550		    (struct scsi_transportid_spi *)buf;
1551		memset(id, 0, sizeof(*id));
1552		id->format_protocol = SCSI_PROTO_SPI;
1553		scsi_ulto2b(iid, id->scsi_addr);
1554		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1555		return (sizeof(*id));
1556	}
1557	}
1558}
1559
1560static int
1561ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1562{
1563	return (0);
1564}
1565
1566static int
1567ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1568{
1569	return (0);
1570}
1571
1572/*
1573 * Data movement routine for the CTL ioctl frontend port.
1574 */
1575static int
1576ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1577{
1578	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1579	struct ctl_sg_entry ext_entry, kern_entry;
1580	int ext_sglen, ext_sg_entries, kern_sg_entries;
1581	int ext_sg_start, ext_offset;
1582	int len_to_copy, len_copied;
1583	int kern_watermark, ext_watermark;
1584	int ext_sglist_malloced;
1585	int i, j;
1586
1587	ext_sglist_malloced = 0;
1588	ext_sg_start = 0;
1589	ext_offset = 0;
1590
1591	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1592
1593	/*
1594	 * If this flag is set, fake the data transfer.
1595	 */
1596	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1597		ctsio->ext_data_filled = ctsio->ext_data_len;
1598		goto bailout;
1599	}
1600
1601	/*
1602	 * To simplify things here, if we have a single buffer, stick it in
1603	 * a S/G entry and just make it a single entry S/G list.
1604	 */
1605	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1606		int len_seen;
1607
1608		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1609
1610		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1611							   M_WAITOK);
1612		ext_sglist_malloced = 1;
1613		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1614				   ext_sglen) != 0) {
1615			ctl_set_internal_failure(ctsio,
1616						 /*sks_valid*/ 0,
1617						 /*retry_count*/ 0);
1618			goto bailout;
1619		}
1620		ext_sg_entries = ctsio->ext_sg_entries;
1621		len_seen = 0;
1622		for (i = 0; i < ext_sg_entries; i++) {
1623			if ((len_seen + ext_sglist[i].len) >=
1624			     ctsio->ext_data_filled) {
1625				ext_sg_start = i;
1626				ext_offset = ctsio->ext_data_filled - len_seen;
1627				break;
1628			}
1629			len_seen += ext_sglist[i].len;
1630		}
1631	} else {
1632		ext_sglist = &ext_entry;
1633		ext_sglist->addr = ctsio->ext_data_ptr;
1634		ext_sglist->len = ctsio->ext_data_len;
1635		ext_sg_entries = 1;
1636		ext_sg_start = 0;
1637		ext_offset = ctsio->ext_data_filled;
1638	}
1639
1640	if (ctsio->kern_sg_entries > 0) {
1641		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1642		kern_sg_entries = ctsio->kern_sg_entries;
1643	} else {
1644		kern_sglist = &kern_entry;
1645		kern_sglist->addr = ctsio->kern_data_ptr;
1646		kern_sglist->len = ctsio->kern_data_len;
1647		kern_sg_entries = 1;
1648	}
1649
1650
1651	kern_watermark = 0;
1652	ext_watermark = ext_offset;
1653	len_copied = 0;
1654	for (i = ext_sg_start, j = 0;
1655	     i < ext_sg_entries && j < kern_sg_entries;) {
1656		uint8_t *ext_ptr, *kern_ptr;
1657
1658		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1659				      kern_sglist[j].len - kern_watermark);
1660
1661		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1662		ext_ptr = ext_ptr + ext_watermark;
1663		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1664			/*
1665			 * XXX KDM fix this!
1666			 */
1667			panic("need to implement bus address support");
1668#if 0
1669			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1670#endif
1671		} else
1672			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1673		kern_ptr = kern_ptr + kern_watermark;
1674
1675		kern_watermark += len_to_copy;
1676		ext_watermark += len_to_copy;
1677
1678		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1679		     CTL_FLAG_DATA_IN) {
1680			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1681					 "bytes to user\n", len_to_copy));
1682			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1683					 "to %p\n", kern_ptr, ext_ptr));
1684			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1685				ctl_set_internal_failure(ctsio,
1686							 /*sks_valid*/ 0,
1687							 /*retry_count*/ 0);
1688				goto bailout;
1689			}
1690		} else {
1691			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1692					 "bytes from user\n", len_to_copy));
1693			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1694					 "to %p\n", ext_ptr, kern_ptr));
1695			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1696				ctl_set_internal_failure(ctsio,
1697							 /*sks_valid*/ 0,
1698							 /*retry_count*/0);
1699				goto bailout;
1700			}
1701		}
1702
1703		len_copied += len_to_copy;
1704
1705		if (ext_sglist[i].len == ext_watermark) {
1706			i++;
1707			ext_watermark = 0;
1708		}
1709
1710		if (kern_sglist[j].len == kern_watermark) {
1711			j++;
1712			kern_watermark = 0;
1713		}
1714	}
1715
1716	ctsio->ext_data_filled += len_copied;
1717
1718	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1719			 "kern_sg_entries: %d\n", ext_sg_entries,
1720			 kern_sg_entries));
1721	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1722			 "kern_data_len = %d\n", ctsio->ext_data_len,
1723			 ctsio->kern_data_len));
1724
1725
1726	/* XXX KDM set residual?? */
1727bailout:
1728
1729	if (ext_sglist_malloced != 0)
1730		free(ext_sglist, M_CTL);
1731
1732	return (CTL_RETVAL_COMPLETE);
1733}
1734
1735/*
1736 * Serialize a command that went down the "wrong" side, and so was sent to
1737 * this controller for execution.  The logic is a little different than the
1738 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1739 * sent back to the other side, but in the success case, we execute the
1740 * command on this side (XFER mode) or tell the other side to execute it
1741 * (SER_ONLY mode).
1742 */
1743static int
1744ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1745{
1746	struct ctl_softc *ctl_softc;
1747	union ctl_ha_msg msg_info;
1748	struct ctl_lun *lun;
1749	int retval = 0;
1750	uint32_t targ_lun;
1751
1752	ctl_softc = control_softc;
1753
1754	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1755	lun = ctl_softc->ctl_luns[targ_lun];
1756	if (lun==NULL)
1757	{
1758		/*
1759		 * Why isn't LUN defined? The other side wouldn't
1760		 * send a cmd if the LUN is undefined.
1761		 */
1762		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1763
1764		/* "Logical unit not supported" */
1765		ctl_set_sense_data(&msg_info.scsi.sense_data,
1766				   lun,
1767				   /*sense_format*/SSD_TYPE_NONE,
1768				   /*current_error*/ 1,
1769				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1770				   /*asc*/ 0x25,
1771				   /*ascq*/ 0x00,
1772				   SSD_ELEM_NONE);
1773
1774		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1775		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1776		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1777		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1778		msg_info.hdr.serializing_sc = NULL;
1779		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1780	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1781				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1782		}
1783		return(1);
1784
1785	}
1786
1787	mtx_lock(&lun->lun_lock);
1788    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1789
1790	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1791		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1792		 ooa_links))) {
1793	case CTL_ACTION_BLOCK:
1794		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1795		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1796				  blocked_links);
1797		break;
1798	case CTL_ACTION_PASS:
1799	case CTL_ACTION_SKIP:
1800		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1801			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1802			ctl_enqueue_rtr((union ctl_io *)ctsio);
1803		} else {
1804
1805			/* send msg back to other side */
1806			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1807			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1808			msg_info.hdr.msg_type = CTL_MSG_R2R;
1809#if 0
1810			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1811#endif
1812		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1813			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1814			}
1815		}
1816		break;
1817	case CTL_ACTION_OVERLAP:
1818		/* OVERLAPPED COMMANDS ATTEMPTED */
1819		ctl_set_sense_data(&msg_info.scsi.sense_data,
1820				   lun,
1821				   /*sense_format*/SSD_TYPE_NONE,
1822				   /*current_error*/ 1,
1823				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1824				   /*asc*/ 0x4E,
1825				   /*ascq*/ 0x00,
1826				   SSD_ELEM_NONE);
1827
1828		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1829		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1830		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1831		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1832		msg_info.hdr.serializing_sc = NULL;
1833		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1834#if 0
1835		printf("BAD JUJU:Major Bummer Overlap\n");
1836#endif
1837		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1838		retval = 1;
1839		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1840		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1841		}
1842		break;
1843	case CTL_ACTION_OVERLAP_TAG:
1844		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1845		ctl_set_sense_data(&msg_info.scsi.sense_data,
1846				   lun,
1847				   /*sense_format*/SSD_TYPE_NONE,
1848				   /*current_error*/ 1,
1849				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1850				   /*asc*/ 0x4D,
1851				   /*ascq*/ ctsio->tag_num & 0xff,
1852				   SSD_ELEM_NONE);
1853
1854		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1855		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1856		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1857		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1858		msg_info.hdr.serializing_sc = NULL;
1859		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1860#if 0
1861		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1862#endif
1863		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1864		retval = 1;
1865		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1866		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1867		}
1868		break;
1869	case CTL_ACTION_ERROR:
1870	default:
1871		/* "Internal target failure" */
1872		ctl_set_sense_data(&msg_info.scsi.sense_data,
1873				   lun,
1874				   /*sense_format*/SSD_TYPE_NONE,
1875				   /*current_error*/ 1,
1876				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1877				   /*asc*/ 0x44,
1878				   /*ascq*/ 0x00,
1879				   SSD_ELEM_NONE);
1880
1881		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1882		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1883		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1884		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1885		msg_info.hdr.serializing_sc = NULL;
1886		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1887#if 0
1888		printf("BAD JUJU:Major Bummer HW Error\n");
1889#endif
1890		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1891		retval = 1;
1892		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1893		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1894		}
1895		break;
1896	}
1897	mtx_unlock(&lun->lun_lock);
1898	return (retval);
1899}
1900
1901static int
1902ctl_ioctl_submit_wait(union ctl_io *io)
1903{
1904	struct ctl_fe_ioctl_params params;
1905	ctl_fe_ioctl_state last_state;
1906	int done, retval;
1907
1908	retval = 0;
1909
1910	bzero(&params, sizeof(params));
1911
1912	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1913	cv_init(&params.sem, "ctlioccv");
1914	params.state = CTL_IOCTL_INPROG;
1915	last_state = params.state;
1916
1917	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1918
1919	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1920
1921	/* This shouldn't happen */
1922	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1923		return (retval);
1924
1925	done = 0;
1926
1927	do {
1928		mtx_lock(&params.ioctl_mtx);
1929		/*
1930		 * Check the state here, and don't sleep if the state has
1931		 * already changed (i.e. wakeup has already occured, but we
1932		 * weren't waiting yet).
1933		 */
1934		if (params.state == last_state) {
1935			/* XXX KDM cv_wait_sig instead? */
1936			cv_wait(&params.sem, &params.ioctl_mtx);
1937		}
1938		last_state = params.state;
1939
1940		switch (params.state) {
1941		case CTL_IOCTL_INPROG:
1942			/* Why did we wake up? */
1943			/* XXX KDM error here? */
1944			mtx_unlock(&params.ioctl_mtx);
1945			break;
1946		case CTL_IOCTL_DATAMOVE:
1947			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1948
1949			/*
1950			 * change last_state back to INPROG to avoid
1951			 * deadlock on subsequent data moves.
1952			 */
1953			params.state = last_state = CTL_IOCTL_INPROG;
1954
1955			mtx_unlock(&params.ioctl_mtx);
1956			ctl_ioctl_do_datamove(&io->scsiio);
1957			/*
1958			 * Note that in some cases, most notably writes,
1959			 * this will queue the I/O and call us back later.
1960			 * In other cases, generally reads, this routine
1961			 * will immediately call back and wake us up,
1962			 * probably using our own context.
1963			 */
1964			io->scsiio.be_move_done(io);
1965			break;
1966		case CTL_IOCTL_DONE:
1967			mtx_unlock(&params.ioctl_mtx);
1968			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1969			done = 1;
1970			break;
1971		default:
1972			mtx_unlock(&params.ioctl_mtx);
1973			/* XXX KDM error here? */
1974			break;
1975		}
1976	} while (done == 0);
1977
1978	mtx_destroy(&params.ioctl_mtx);
1979	cv_destroy(&params.sem);
1980
1981	return (CTL_RETVAL_COMPLETE);
1982}
1983
1984static void
1985ctl_ioctl_datamove(union ctl_io *io)
1986{
1987	struct ctl_fe_ioctl_params *params;
1988
1989	params = (struct ctl_fe_ioctl_params *)
1990		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1991
1992	mtx_lock(&params->ioctl_mtx);
1993	params->state = CTL_IOCTL_DATAMOVE;
1994	cv_broadcast(&params->sem);
1995	mtx_unlock(&params->ioctl_mtx);
1996}
1997
1998static void
1999ctl_ioctl_done(union ctl_io *io)
2000{
2001	struct ctl_fe_ioctl_params *params;
2002
2003	params = (struct ctl_fe_ioctl_params *)
2004		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2005
2006	mtx_lock(&params->ioctl_mtx);
2007	params->state = CTL_IOCTL_DONE;
2008	cv_broadcast(&params->sem);
2009	mtx_unlock(&params->ioctl_mtx);
2010}
2011
2012static void
2013ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2014{
2015	struct ctl_fe_ioctl_startstop_info *sd_info;
2016
2017	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2018
2019	sd_info->hs_info.status = metatask->status;
2020	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2021	sd_info->hs_info.luns_complete =
2022		metatask->taskinfo.startstop.luns_complete;
2023	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2024
2025	cv_broadcast(&sd_info->sem);
2026}
2027
2028static void
2029ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2030{
2031	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2032
2033	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2034
2035	mtx_lock(fe_bbr_info->lock);
2036	fe_bbr_info->bbr_info->status = metatask->status;
2037	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2038	fe_bbr_info->wakeup_done = 1;
2039	mtx_unlock(fe_bbr_info->lock);
2040
2041	cv_broadcast(&fe_bbr_info->sem);
2042}
2043
2044/*
2045 * Returns 0 for success, errno for failure.
2046 */
2047static int
2048ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2049		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2050{
2051	union ctl_io *io;
2052	int retval;
2053
2054	retval = 0;
2055
2056	mtx_lock(&lun->lun_lock);
2057	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2058	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2059	     ooa_links)) {
2060		struct ctl_ooa_entry *entry;
2061
2062		/*
2063		 * If we've got more than we can fit, just count the
2064		 * remaining entries.
2065		 */
2066		if (*cur_fill_num >= ooa_hdr->alloc_num)
2067			continue;
2068
2069		entry = &kern_entries[*cur_fill_num];
2070
2071		entry->tag_num = io->scsiio.tag_num;
2072		entry->lun_num = lun->lun;
2073#ifdef CTL_TIME_IO
2074		entry->start_bt = io->io_hdr.start_bt;
2075#endif
2076		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2077		entry->cdb_len = io->scsiio.cdb_len;
2078		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2079			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2080
2081		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2082			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2083
2084		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2085			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2086
2087		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2088			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2089
2090		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2091			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2092	}
2093	mtx_unlock(&lun->lun_lock);
2094
2095	return (retval);
2096}
2097
2098static void *
2099ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2100		 size_t error_str_len)
2101{
2102	void *kptr;
2103
2104	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2105
2106	if (copyin(user_addr, kptr, len) != 0) {
2107		snprintf(error_str, error_str_len, "Error copying %d bytes "
2108			 "from user address %p to kernel address %p", len,
2109			 user_addr, kptr);
2110		free(kptr, M_CTL);
2111		return (NULL);
2112	}
2113
2114	return (kptr);
2115}
2116
2117static void
2118ctl_free_args(int num_args, struct ctl_be_arg *args)
2119{
2120	int i;
2121
2122	if (args == NULL)
2123		return;
2124
2125	for (i = 0; i < num_args; i++) {
2126		free(args[i].kname, M_CTL);
2127		free(args[i].kvalue, M_CTL);
2128	}
2129
2130	free(args, M_CTL);
2131}
2132
2133static struct ctl_be_arg *
2134ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2135		char *error_str, size_t error_str_len)
2136{
2137	struct ctl_be_arg *args;
2138	int i;
2139
2140	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2141				error_str, error_str_len);
2142
2143	if (args == NULL)
2144		goto bailout;
2145
2146	for (i = 0; i < num_args; i++) {
2147		args[i].kname = NULL;
2148		args[i].kvalue = NULL;
2149	}
2150
2151	for (i = 0; i < num_args; i++) {
2152		uint8_t *tmpptr;
2153
2154		args[i].kname = ctl_copyin_alloc(args[i].name,
2155			args[i].namelen, error_str, error_str_len);
2156		if (args[i].kname == NULL)
2157			goto bailout;
2158
2159		if (args[i].kname[args[i].namelen - 1] != '\0') {
2160			snprintf(error_str, error_str_len, "Argument %d "
2161				 "name is not NUL-terminated", i);
2162			goto bailout;
2163		}
2164
2165		if (args[i].flags & CTL_BEARG_RD) {
2166			tmpptr = ctl_copyin_alloc(args[i].value,
2167				args[i].vallen, error_str, error_str_len);
2168			if (tmpptr == NULL)
2169				goto bailout;
2170			if ((args[i].flags & CTL_BEARG_ASCII)
2171			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2172				snprintf(error_str, error_str_len, "Argument "
2173				    "%d value is not NUL-terminated", i);
2174				goto bailout;
2175			}
2176			args[i].kvalue = tmpptr;
2177		} else {
2178			args[i].kvalue = malloc(args[i].vallen,
2179			    M_CTL, M_WAITOK | M_ZERO);
2180		}
2181	}
2182
2183	return (args);
2184bailout:
2185
2186	ctl_free_args(num_args, args);
2187
2188	return (NULL);
2189}
2190
2191static void
2192ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2193{
2194	int i;
2195
2196	for (i = 0; i < num_args; i++) {
2197		if (args[i].flags & CTL_BEARG_WR)
2198			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2199	}
2200}
2201
2202/*
2203 * Escape characters that are illegal or not recommended in XML.
2204 */
2205int
2206ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2207{
2208	int retval;
2209
2210	retval = 0;
2211
2212	for (; *str; str++) {
2213		switch (*str) {
2214		case '&':
2215			retval = sbuf_printf(sb, "&amp;");
2216			break;
2217		case '>':
2218			retval = sbuf_printf(sb, "&gt;");
2219			break;
2220		case '<':
2221			retval = sbuf_printf(sb, "&lt;");
2222			break;
2223		default:
2224			retval = sbuf_putc(sb, *str);
2225			break;
2226		}
2227
2228		if (retval != 0)
2229			break;
2230
2231	}
2232
2233	return (retval);
2234}
2235
2236static int
2237ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2238	  struct thread *td)
2239{
2240	struct ctl_softc *softc;
2241	int retval;
2242
2243	softc = control_softc;
2244
2245	retval = 0;
2246
2247	switch (cmd) {
2248	case CTL_IO: {
2249		union ctl_io *io;
2250		void *pool_tmp;
2251
2252		/*
2253		 * If we haven't been "enabled", don't allow any SCSI I/O
2254		 * to this FETD.
2255		 */
2256		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2257			retval = EPERM;
2258			break;
2259		}
2260
2261		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2262		if (io == NULL) {
2263			printf("ctl_ioctl: can't allocate ctl_io!\n");
2264			retval = ENOSPC;
2265			break;
2266		}
2267
2268		/*
2269		 * Need to save the pool reference so it doesn't get
2270		 * spammed by the user's ctl_io.
2271		 */
2272		pool_tmp = io->io_hdr.pool;
2273
2274		memcpy(io, (void *)addr, sizeof(*io));
2275
2276		io->io_hdr.pool = pool_tmp;
2277		/*
2278		 * No status yet, so make sure the status is set properly.
2279		 */
2280		io->io_hdr.status = CTL_STATUS_NONE;
2281
2282		/*
2283		 * The user sets the initiator ID, target and LUN IDs.
2284		 */
2285		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2286		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2287		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2288		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2289			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2290
2291		retval = ctl_ioctl_submit_wait(io);
2292
2293		if (retval != 0) {
2294			ctl_free_io(io);
2295			break;
2296		}
2297
2298		memcpy((void *)addr, io, sizeof(*io));
2299
2300		/* return this to our pool */
2301		ctl_free_io(io);
2302
2303		break;
2304	}
2305	case CTL_ENABLE_PORT:
2306	case CTL_DISABLE_PORT:
2307	case CTL_SET_PORT_WWNS: {
2308		struct ctl_port *port;
2309		struct ctl_port_entry *entry;
2310
2311		entry = (struct ctl_port_entry *)addr;
2312
2313		mtx_lock(&softc->ctl_lock);
2314		STAILQ_FOREACH(port, &softc->port_list, links) {
2315			int action, done;
2316
2317			action = 0;
2318			done = 0;
2319
2320			if ((entry->port_type == CTL_PORT_NONE)
2321			 && (entry->targ_port == port->targ_port)) {
2322				/*
2323				 * If the user only wants to enable or
2324				 * disable or set WWNs on a specific port,
2325				 * do the operation and we're done.
2326				 */
2327				action = 1;
2328				done = 1;
2329			} else if (entry->port_type & port->port_type) {
2330				/*
2331				 * Compare the user's type mask with the
2332				 * particular frontend type to see if we
2333				 * have a match.
2334				 */
2335				action = 1;
2336				done = 0;
2337
2338				/*
2339				 * Make sure the user isn't trying to set
2340				 * WWNs on multiple ports at the same time.
2341				 */
2342				if (cmd == CTL_SET_PORT_WWNS) {
2343					printf("%s: Can't set WWNs on "
2344					       "multiple ports\n", __func__);
2345					retval = EINVAL;
2346					break;
2347				}
2348			}
2349			if (action != 0) {
2350				/*
2351				 * XXX KDM we have to drop the lock here,
2352				 * because the online/offline operations
2353				 * can potentially block.  We need to
2354				 * reference count the frontends so they
2355				 * can't go away,
2356				 */
2357				mtx_unlock(&softc->ctl_lock);
2358
2359				if (cmd == CTL_ENABLE_PORT) {
2360					struct ctl_lun *lun;
2361
2362					STAILQ_FOREACH(lun, &softc->lun_list,
2363						       links) {
2364						port->lun_enable(port->targ_lun_arg,
2365						    lun->target,
2366						    lun->lun);
2367					}
2368
2369					ctl_port_online(port);
2370				} else if (cmd == CTL_DISABLE_PORT) {
2371					struct ctl_lun *lun;
2372
2373					ctl_port_offline(port);
2374
2375					STAILQ_FOREACH(lun, &softc->lun_list,
2376						       links) {
2377						port->lun_disable(
2378						    port->targ_lun_arg,
2379						    lun->target,
2380						    lun->lun);
2381					}
2382				}
2383
2384				mtx_lock(&softc->ctl_lock);
2385
2386				if (cmd == CTL_SET_PORT_WWNS)
2387					ctl_port_set_wwns(port,
2388					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2389					    1 : 0, entry->wwnn,
2390					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2391					    1 : 0, entry->wwpn);
2392			}
2393			if (done != 0)
2394				break;
2395		}
2396		mtx_unlock(&softc->ctl_lock);
2397		break;
2398	}
2399	case CTL_GET_PORT_LIST: {
2400		struct ctl_port *port;
2401		struct ctl_port_list *list;
2402		int i;
2403
2404		list = (struct ctl_port_list *)addr;
2405
2406		if (list->alloc_len != (list->alloc_num *
2407		    sizeof(struct ctl_port_entry))) {
2408			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2409			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2410			       "%zu\n", __func__, list->alloc_len,
2411			       list->alloc_num, sizeof(struct ctl_port_entry));
2412			retval = EINVAL;
2413			break;
2414		}
2415		list->fill_len = 0;
2416		list->fill_num = 0;
2417		list->dropped_num = 0;
2418		i = 0;
2419		mtx_lock(&softc->ctl_lock);
2420		STAILQ_FOREACH(port, &softc->port_list, links) {
2421			struct ctl_port_entry entry, *list_entry;
2422
2423			if (list->fill_num >= list->alloc_num) {
2424				list->dropped_num++;
2425				continue;
2426			}
2427
2428			entry.port_type = port->port_type;
2429			strlcpy(entry.port_name, port->port_name,
2430				sizeof(entry.port_name));
2431			entry.targ_port = port->targ_port;
2432			entry.physical_port = port->physical_port;
2433			entry.virtual_port = port->virtual_port;
2434			entry.wwnn = port->wwnn;
2435			entry.wwpn = port->wwpn;
2436			if (port->status & CTL_PORT_STATUS_ONLINE)
2437				entry.online = 1;
2438			else
2439				entry.online = 0;
2440
2441			list_entry = &list->entries[i];
2442
2443			retval = copyout(&entry, list_entry, sizeof(entry));
2444			if (retval != 0) {
2445				printf("%s: CTL_GET_PORT_LIST: copyout "
2446				       "returned %d\n", __func__, retval);
2447				break;
2448			}
2449			i++;
2450			list->fill_num++;
2451			list->fill_len += sizeof(entry);
2452		}
2453		mtx_unlock(&softc->ctl_lock);
2454
2455		/*
2456		 * If this is non-zero, we had a copyout fault, so there's
2457		 * probably no point in attempting to set the status inside
2458		 * the structure.
2459		 */
2460		if (retval != 0)
2461			break;
2462
2463		if (list->dropped_num > 0)
2464			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2465		else
2466			list->status = CTL_PORT_LIST_OK;
2467		break;
2468	}
2469	case CTL_DUMP_OOA: {
2470		struct ctl_lun *lun;
2471		union ctl_io *io;
2472		char printbuf[128];
2473		struct sbuf sb;
2474
2475		mtx_lock(&softc->ctl_lock);
2476		printf("Dumping OOA queues:\n");
2477		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2478			mtx_lock(&lun->lun_lock);
2479			for (io = (union ctl_io *)TAILQ_FIRST(
2480			     &lun->ooa_queue); io != NULL;
2481			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2482			     ooa_links)) {
2483				sbuf_new(&sb, printbuf, sizeof(printbuf),
2484					 SBUF_FIXEDLEN);
2485				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2486					    (intmax_t)lun->lun,
2487					    io->scsiio.tag_num,
2488					    (io->io_hdr.flags &
2489					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2490					    (io->io_hdr.flags &
2491					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2492					    (io->io_hdr.flags &
2493					    CTL_FLAG_ABORT) ? " ABORT" : "",
2494			                    (io->io_hdr.flags &
2495		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2496				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2497				sbuf_finish(&sb);
2498				printf("%s\n", sbuf_data(&sb));
2499			}
2500			mtx_unlock(&lun->lun_lock);
2501		}
2502		printf("OOA queues dump done\n");
2503		mtx_unlock(&softc->ctl_lock);
2504		break;
2505	}
2506	case CTL_GET_OOA: {
2507		struct ctl_lun *lun;
2508		struct ctl_ooa *ooa_hdr;
2509		struct ctl_ooa_entry *entries;
2510		uint32_t cur_fill_num;
2511
2512		ooa_hdr = (struct ctl_ooa *)addr;
2513
2514		if ((ooa_hdr->alloc_len == 0)
2515		 || (ooa_hdr->alloc_num == 0)) {
2516			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2517			       "must be non-zero\n", __func__,
2518			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2519			retval = EINVAL;
2520			break;
2521		}
2522
2523		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2524		    sizeof(struct ctl_ooa_entry))) {
2525			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2526			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2527			       __func__, ooa_hdr->alloc_len,
2528			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2529			retval = EINVAL;
2530			break;
2531		}
2532
2533		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2534		if (entries == NULL) {
2535			printf("%s: could not allocate %d bytes for OOA "
2536			       "dump\n", __func__, ooa_hdr->alloc_len);
2537			retval = ENOMEM;
2538			break;
2539		}
2540
2541		mtx_lock(&softc->ctl_lock);
2542		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2543		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2544		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2545			mtx_unlock(&softc->ctl_lock);
2546			free(entries, M_CTL);
2547			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2548			       __func__, (uintmax_t)ooa_hdr->lun_num);
2549			retval = EINVAL;
2550			break;
2551		}
2552
2553		cur_fill_num = 0;
2554
2555		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2556			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2557				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2558					ooa_hdr, entries);
2559				if (retval != 0)
2560					break;
2561			}
2562			if (retval != 0) {
2563				mtx_unlock(&softc->ctl_lock);
2564				free(entries, M_CTL);
2565				break;
2566			}
2567		} else {
2568			lun = softc->ctl_luns[ooa_hdr->lun_num];
2569
2570			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2571						    entries);
2572		}
2573		mtx_unlock(&softc->ctl_lock);
2574
2575		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2576		ooa_hdr->fill_len = ooa_hdr->fill_num *
2577			sizeof(struct ctl_ooa_entry);
2578		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2579		if (retval != 0) {
2580			printf("%s: error copying out %d bytes for OOA dump\n",
2581			       __func__, ooa_hdr->fill_len);
2582		}
2583
2584		getbintime(&ooa_hdr->cur_bt);
2585
2586		if (cur_fill_num > ooa_hdr->alloc_num) {
2587			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2588			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2589		} else {
2590			ooa_hdr->dropped_num = 0;
2591			ooa_hdr->status = CTL_OOA_OK;
2592		}
2593
2594		free(entries, M_CTL);
2595		break;
2596	}
2597	case CTL_CHECK_OOA: {
2598		union ctl_io *io;
2599		struct ctl_lun *lun;
2600		struct ctl_ooa_info *ooa_info;
2601
2602
2603		ooa_info = (struct ctl_ooa_info *)addr;
2604
2605		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2606			ooa_info->status = CTL_OOA_INVALID_LUN;
2607			break;
2608		}
2609		mtx_lock(&softc->ctl_lock);
2610		lun = softc->ctl_luns[ooa_info->lun_id];
2611		if (lun == NULL) {
2612			mtx_unlock(&softc->ctl_lock);
2613			ooa_info->status = CTL_OOA_INVALID_LUN;
2614			break;
2615		}
2616		mtx_lock(&lun->lun_lock);
2617		mtx_unlock(&softc->ctl_lock);
2618		ooa_info->num_entries = 0;
2619		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2620		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2621		     &io->io_hdr, ooa_links)) {
2622			ooa_info->num_entries++;
2623		}
2624		mtx_unlock(&lun->lun_lock);
2625
2626		ooa_info->status = CTL_OOA_SUCCESS;
2627
2628		break;
2629	}
2630	case CTL_HARD_START:
2631	case CTL_HARD_STOP: {
2632		struct ctl_fe_ioctl_startstop_info ss_info;
2633		struct cfi_metatask *metatask;
2634		struct mtx hs_mtx;
2635
2636		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2637
2638		cv_init(&ss_info.sem, "hard start/stop cv" );
2639
2640		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2641		if (metatask == NULL) {
2642			retval = ENOMEM;
2643			mtx_destroy(&hs_mtx);
2644			break;
2645		}
2646
2647		if (cmd == CTL_HARD_START)
2648			metatask->tasktype = CFI_TASK_STARTUP;
2649		else
2650			metatask->tasktype = CFI_TASK_SHUTDOWN;
2651
2652		metatask->callback = ctl_ioctl_hard_startstop_callback;
2653		metatask->callback_arg = &ss_info;
2654
2655		cfi_action(metatask);
2656
2657		/* Wait for the callback */
2658		mtx_lock(&hs_mtx);
2659		cv_wait_sig(&ss_info.sem, &hs_mtx);
2660		mtx_unlock(&hs_mtx);
2661
2662		/*
2663		 * All information has been copied from the metatask by the
2664		 * time cv_broadcast() is called, so we free the metatask here.
2665		 */
2666		cfi_free_metatask(metatask);
2667
2668		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2669
2670		mtx_destroy(&hs_mtx);
2671		break;
2672	}
2673	case CTL_BBRREAD: {
2674		struct ctl_bbrread_info *bbr_info;
2675		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2676		struct mtx bbr_mtx;
2677		struct cfi_metatask *metatask;
2678
2679		bbr_info = (struct ctl_bbrread_info *)addr;
2680
2681		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2682
2683		bzero(&bbr_mtx, sizeof(bbr_mtx));
2684		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2685
2686		fe_bbr_info.bbr_info = bbr_info;
2687		fe_bbr_info.lock = &bbr_mtx;
2688
2689		cv_init(&fe_bbr_info.sem, "BBR read cv");
2690		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2691
2692		if (metatask == NULL) {
2693			mtx_destroy(&bbr_mtx);
2694			cv_destroy(&fe_bbr_info.sem);
2695			retval = ENOMEM;
2696			break;
2697		}
2698		metatask->tasktype = CFI_TASK_BBRREAD;
2699		metatask->callback = ctl_ioctl_bbrread_callback;
2700		metatask->callback_arg = &fe_bbr_info;
2701		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2702		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2703		metatask->taskinfo.bbrread.len = bbr_info->len;
2704
2705		cfi_action(metatask);
2706
2707		mtx_lock(&bbr_mtx);
2708		while (fe_bbr_info.wakeup_done == 0)
2709			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2710		mtx_unlock(&bbr_mtx);
2711
2712		bbr_info->status = metatask->status;
2713		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2714		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2715		memcpy(&bbr_info->sense_data,
2716		       &metatask->taskinfo.bbrread.sense_data,
2717		       ctl_min(sizeof(bbr_info->sense_data),
2718			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2719
2720		cfi_free_metatask(metatask);
2721
2722		mtx_destroy(&bbr_mtx);
2723		cv_destroy(&fe_bbr_info.sem);
2724
2725		break;
2726	}
2727	case CTL_DELAY_IO: {
2728		struct ctl_io_delay_info *delay_info;
2729#ifdef CTL_IO_DELAY
2730		struct ctl_lun *lun;
2731#endif /* CTL_IO_DELAY */
2732
2733		delay_info = (struct ctl_io_delay_info *)addr;
2734
2735#ifdef CTL_IO_DELAY
2736		mtx_lock(&softc->ctl_lock);
2737
2738		if ((delay_info->lun_id > CTL_MAX_LUNS)
2739		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2740			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2741		} else {
2742			lun = softc->ctl_luns[delay_info->lun_id];
2743			mtx_lock(&lun->lun_lock);
2744
2745			delay_info->status = CTL_DELAY_STATUS_OK;
2746
2747			switch (delay_info->delay_type) {
2748			case CTL_DELAY_TYPE_CONT:
2749				break;
2750			case CTL_DELAY_TYPE_ONESHOT:
2751				break;
2752			default:
2753				delay_info->status =
2754					CTL_DELAY_STATUS_INVALID_TYPE;
2755				break;
2756			}
2757
2758			switch (delay_info->delay_loc) {
2759			case CTL_DELAY_LOC_DATAMOVE:
2760				lun->delay_info.datamove_type =
2761					delay_info->delay_type;
2762				lun->delay_info.datamove_delay =
2763					delay_info->delay_secs;
2764				break;
2765			case CTL_DELAY_LOC_DONE:
2766				lun->delay_info.done_type =
2767					delay_info->delay_type;
2768				lun->delay_info.done_delay =
2769					delay_info->delay_secs;
2770				break;
2771			default:
2772				delay_info->status =
2773					CTL_DELAY_STATUS_INVALID_LOC;
2774				break;
2775			}
2776			mtx_unlock(&lun->lun_lock);
2777		}
2778
2779		mtx_unlock(&softc->ctl_lock);
2780#else
2781		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2782#endif /* CTL_IO_DELAY */
2783		break;
2784	}
2785	case CTL_REALSYNC_SET: {
2786		int *syncstate;
2787
2788		syncstate = (int *)addr;
2789
2790		mtx_lock(&softc->ctl_lock);
2791		switch (*syncstate) {
2792		case 0:
2793			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2794			break;
2795		case 1:
2796			softc->flags |= CTL_FLAG_REAL_SYNC;
2797			break;
2798		default:
2799			retval = EINVAL;
2800			break;
2801		}
2802		mtx_unlock(&softc->ctl_lock);
2803		break;
2804	}
2805	case CTL_REALSYNC_GET: {
2806		int *syncstate;
2807
2808		syncstate = (int*)addr;
2809
2810		mtx_lock(&softc->ctl_lock);
2811		if (softc->flags & CTL_FLAG_REAL_SYNC)
2812			*syncstate = 1;
2813		else
2814			*syncstate = 0;
2815		mtx_unlock(&softc->ctl_lock);
2816
2817		break;
2818	}
2819	case CTL_SETSYNC:
2820	case CTL_GETSYNC: {
2821		struct ctl_sync_info *sync_info;
2822		struct ctl_lun *lun;
2823
2824		sync_info = (struct ctl_sync_info *)addr;
2825
2826		mtx_lock(&softc->ctl_lock);
2827		lun = softc->ctl_luns[sync_info->lun_id];
2828		if (lun == NULL) {
2829			mtx_unlock(&softc->ctl_lock);
2830			sync_info->status = CTL_GS_SYNC_NO_LUN;
2831		}
2832		/*
2833		 * Get or set the sync interval.  We're not bounds checking
2834		 * in the set case, hopefully the user won't do something
2835		 * silly.
2836		 */
2837		mtx_lock(&lun->lun_lock);
2838		mtx_unlock(&softc->ctl_lock);
2839		if (cmd == CTL_GETSYNC)
2840			sync_info->sync_interval = lun->sync_interval;
2841		else
2842			lun->sync_interval = sync_info->sync_interval;
2843		mtx_unlock(&lun->lun_lock);
2844
2845		sync_info->status = CTL_GS_SYNC_OK;
2846
2847		break;
2848	}
2849	case CTL_GETSTATS: {
2850		struct ctl_stats *stats;
2851		struct ctl_lun *lun;
2852		int i;
2853
2854		stats = (struct ctl_stats *)addr;
2855
2856		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2857		     stats->alloc_len) {
2858			stats->status = CTL_SS_NEED_MORE_SPACE;
2859			stats->num_luns = softc->num_luns;
2860			break;
2861		}
2862		/*
2863		 * XXX KDM no locking here.  If the LUN list changes,
2864		 * things can blow up.
2865		 */
2866		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2867		     i++, lun = STAILQ_NEXT(lun, links)) {
2868			retval = copyout(&lun->stats, &stats->lun_stats[i],
2869					 sizeof(lun->stats));
2870			if (retval != 0)
2871				break;
2872		}
2873		stats->num_luns = softc->num_luns;
2874		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2875				 softc->num_luns;
2876		stats->status = CTL_SS_OK;
2877#ifdef CTL_TIME_IO
2878		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2879#else
2880		stats->flags = CTL_STATS_FLAG_NONE;
2881#endif
2882		getnanouptime(&stats->timestamp);
2883		break;
2884	}
2885	case CTL_ERROR_INJECT: {
2886		struct ctl_error_desc *err_desc, *new_err_desc;
2887		struct ctl_lun *lun;
2888
2889		err_desc = (struct ctl_error_desc *)addr;
2890
2891		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2892				      M_WAITOK | M_ZERO);
2893		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2894
2895		mtx_lock(&softc->ctl_lock);
2896		lun = softc->ctl_luns[err_desc->lun_id];
2897		if (lun == NULL) {
2898			mtx_unlock(&softc->ctl_lock);
2899			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2900			       __func__, (uintmax_t)err_desc->lun_id);
2901			retval = EINVAL;
2902			break;
2903		}
2904		mtx_lock(&lun->lun_lock);
2905		mtx_unlock(&softc->ctl_lock);
2906
2907		/*
2908		 * We could do some checking here to verify the validity
2909		 * of the request, but given the complexity of error
2910		 * injection requests, the checking logic would be fairly
2911		 * complex.
2912		 *
2913		 * For now, if the request is invalid, it just won't get
2914		 * executed and might get deleted.
2915		 */
2916		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2917
2918		/*
2919		 * XXX KDM check to make sure the serial number is unique,
2920		 * in case we somehow manage to wrap.  That shouldn't
2921		 * happen for a very long time, but it's the right thing to
2922		 * do.
2923		 */
2924		new_err_desc->serial = lun->error_serial;
2925		err_desc->serial = lun->error_serial;
2926		lun->error_serial++;
2927
2928		mtx_unlock(&lun->lun_lock);
2929		break;
2930	}
2931	case CTL_ERROR_INJECT_DELETE: {
2932		struct ctl_error_desc *delete_desc, *desc, *desc2;
2933		struct ctl_lun *lun;
2934		int delete_done;
2935
2936		delete_desc = (struct ctl_error_desc *)addr;
2937		delete_done = 0;
2938
2939		mtx_lock(&softc->ctl_lock);
2940		lun = softc->ctl_luns[delete_desc->lun_id];
2941		if (lun == NULL) {
2942			mtx_unlock(&softc->ctl_lock);
2943			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2944			       __func__, (uintmax_t)delete_desc->lun_id);
2945			retval = EINVAL;
2946			break;
2947		}
2948		mtx_lock(&lun->lun_lock);
2949		mtx_unlock(&softc->ctl_lock);
2950		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2951			if (desc->serial != delete_desc->serial)
2952				continue;
2953
2954			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2955				      links);
2956			free(desc, M_CTL);
2957			delete_done = 1;
2958		}
2959		mtx_unlock(&lun->lun_lock);
2960		if (delete_done == 0) {
2961			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2962			       "error serial %ju on LUN %u\n", __func__,
2963			       delete_desc->serial, delete_desc->lun_id);
2964			retval = EINVAL;
2965			break;
2966		}
2967		break;
2968	}
2969	case CTL_DUMP_STRUCTS: {
2970		int i, j, k, idx;
2971		struct ctl_port *port;
2972		struct ctl_frontend *fe;
2973
2974		mtx_lock(&softc->ctl_lock);
2975		printf("CTL Persistent Reservation information start:\n");
2976		for (i = 0; i < CTL_MAX_LUNS; i++) {
2977			struct ctl_lun *lun;
2978
2979			lun = softc->ctl_luns[i];
2980
2981			if ((lun == NULL)
2982			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2983				continue;
2984
2985			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2986				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2987					idx = j * CTL_MAX_INIT_PER_PORT + k;
2988					if (lun->per_res[idx].registered == 0)
2989						continue;
2990					printf("  LUN %d port %d iid %d key "
2991					       "%#jx\n", i, j, k,
2992					       (uintmax_t)scsi_8btou64(
2993					       lun->per_res[idx].res_key.key));
2994				}
2995			}
2996		}
2997		printf("CTL Persistent Reservation information end\n");
2998		printf("CTL Ports:\n");
2999		STAILQ_FOREACH(port, &softc->port_list, links) {
3000			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3001			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3002			       port->frontend->name, port->port_type,
3003			       port->physical_port, port->virtual_port,
3004			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3005			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3006				if (port->wwpn_iid[j].in_use == 0 &&
3007				    port->wwpn_iid[j].wwpn == 0 &&
3008				    port->wwpn_iid[j].name == NULL)
3009					continue;
3010
3011				printf("    iid %u use %d WWPN %#jx '%s'\n",
3012				    j, port->wwpn_iid[j].in_use,
3013				    (uintmax_t)port->wwpn_iid[j].wwpn,
3014				    port->wwpn_iid[j].name);
3015			}
3016		}
3017		printf("CTL Port information end\n");
3018		mtx_unlock(&softc->ctl_lock);
3019		/*
3020		 * XXX KDM calling this without a lock.  We'd likely want
3021		 * to drop the lock before calling the frontend's dump
3022		 * routine anyway.
3023		 */
3024		printf("CTL Frontends:\n");
3025		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3026			printf("  Frontend '%s'\n", fe->name);
3027			if (fe->fe_dump != NULL)
3028				fe->fe_dump();
3029		}
3030		printf("CTL Frontend information end\n");
3031		break;
3032	}
3033	case CTL_LUN_REQ: {
3034		struct ctl_lun_req *lun_req;
3035		struct ctl_backend_driver *backend;
3036
3037		lun_req = (struct ctl_lun_req *)addr;
3038
3039		backend = ctl_backend_find(lun_req->backend);
3040		if (backend == NULL) {
3041			lun_req->status = CTL_LUN_ERROR;
3042			snprintf(lun_req->error_str,
3043				 sizeof(lun_req->error_str),
3044				 "Backend \"%s\" not found.",
3045				 lun_req->backend);
3046			break;
3047		}
3048		if (lun_req->num_be_args > 0) {
3049			lun_req->kern_be_args = ctl_copyin_args(
3050				lun_req->num_be_args,
3051				lun_req->be_args,
3052				lun_req->error_str,
3053				sizeof(lun_req->error_str));
3054			if (lun_req->kern_be_args == NULL) {
3055				lun_req->status = CTL_LUN_ERROR;
3056				break;
3057			}
3058		}
3059
3060		retval = backend->ioctl(dev, cmd, addr, flag, td);
3061
3062		if (lun_req->num_be_args > 0) {
3063			ctl_copyout_args(lun_req->num_be_args,
3064				      lun_req->kern_be_args);
3065			ctl_free_args(lun_req->num_be_args,
3066				      lun_req->kern_be_args);
3067		}
3068		break;
3069	}
3070	case CTL_LUN_LIST: {
3071		struct sbuf *sb;
3072		struct ctl_lun *lun;
3073		struct ctl_lun_list *list;
3074		struct ctl_option *opt;
3075
3076		list = (struct ctl_lun_list *)addr;
3077
3078		/*
3079		 * Allocate a fixed length sbuf here, based on the length
3080		 * of the user's buffer.  We could allocate an auto-extending
3081		 * buffer, and then tell the user how much larger our
3082		 * amount of data is than his buffer, but that presents
3083		 * some problems:
3084		 *
3085		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3086		 *     we can't hold a lock while calling them with an
3087		 *     auto-extending buffer.
3088 		 *
3089		 * 2.  There is not currently a LUN reference counting
3090		 *     mechanism, outside of outstanding transactions on
3091		 *     the LUN's OOA queue.  So a LUN could go away on us
3092		 *     while we're getting the LUN number, backend-specific
3093		 *     information, etc.  Thus, given the way things
3094		 *     currently work, we need to hold the CTL lock while
3095		 *     grabbing LUN information.
3096		 *
3097		 * So, from the user's standpoint, the best thing to do is
3098		 * allocate what he thinks is a reasonable buffer length,
3099		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3100		 * double the buffer length and try again.  (And repeat
3101		 * that until he succeeds.)
3102		 */
3103		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3104		if (sb == NULL) {
3105			list->status = CTL_LUN_LIST_ERROR;
3106			snprintf(list->error_str, sizeof(list->error_str),
3107				 "Unable to allocate %d bytes for LUN list",
3108				 list->alloc_len);
3109			break;
3110		}
3111
3112		sbuf_printf(sb, "<ctllunlist>\n");
3113
3114		mtx_lock(&softc->ctl_lock);
3115		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3116			mtx_lock(&lun->lun_lock);
3117			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3118					     (uintmax_t)lun->lun);
3119
3120			/*
3121			 * Bail out as soon as we see that we've overfilled
3122			 * the buffer.
3123			 */
3124			if (retval != 0)
3125				break;
3126
3127			retval = sbuf_printf(sb, "\t<backend_type>%s"
3128					     "</backend_type>\n",
3129					     (lun->backend == NULL) ?  "none" :
3130					     lun->backend->name);
3131
3132			if (retval != 0)
3133				break;
3134
3135			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3136					     lun->be_lun->lun_type);
3137
3138			if (retval != 0)
3139				break;
3140
3141			if (lun->backend == NULL) {
3142				retval = sbuf_printf(sb, "</lun>\n");
3143				if (retval != 0)
3144					break;
3145				continue;
3146			}
3147
3148			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3149					     (lun->be_lun->maxlba > 0) ?
3150					     lun->be_lun->maxlba + 1 : 0);
3151
3152			if (retval != 0)
3153				break;
3154
3155			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3156					     lun->be_lun->blocksize);
3157
3158			if (retval != 0)
3159				break;
3160
3161			retval = sbuf_printf(sb, "\t<serial_number>");
3162
3163			if (retval != 0)
3164				break;
3165
3166			retval = ctl_sbuf_printf_esc(sb,
3167						     lun->be_lun->serial_num);
3168
3169			if (retval != 0)
3170				break;
3171
3172			retval = sbuf_printf(sb, "</serial_number>\n");
3173
3174			if (retval != 0)
3175				break;
3176
3177			retval = sbuf_printf(sb, "\t<device_id>");
3178
3179			if (retval != 0)
3180				break;
3181
3182			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3183
3184			if (retval != 0)
3185				break;
3186
3187			retval = sbuf_printf(sb, "</device_id>\n");
3188
3189			if (retval != 0)
3190				break;
3191
3192			if (lun->backend->lun_info != NULL) {
3193				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3194				if (retval != 0)
3195					break;
3196			}
3197			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3198				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3199				    opt->name, opt->value, opt->name);
3200				if (retval != 0)
3201					break;
3202			}
3203
3204			retval = sbuf_printf(sb, "</lun>\n");
3205
3206			if (retval != 0)
3207				break;
3208			mtx_unlock(&lun->lun_lock);
3209		}
3210		if (lun != NULL)
3211			mtx_unlock(&lun->lun_lock);
3212		mtx_unlock(&softc->ctl_lock);
3213
3214		if ((retval != 0)
3215		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3216			retval = 0;
3217			sbuf_delete(sb);
3218			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3219			snprintf(list->error_str, sizeof(list->error_str),
3220				 "Out of space, %d bytes is too small",
3221				 list->alloc_len);
3222			break;
3223		}
3224
3225		sbuf_finish(sb);
3226
3227		retval = copyout(sbuf_data(sb), list->lun_xml,
3228				 sbuf_len(sb) + 1);
3229
3230		list->fill_len = sbuf_len(sb) + 1;
3231		list->status = CTL_LUN_LIST_OK;
3232		sbuf_delete(sb);
3233		break;
3234	}
3235	case CTL_ISCSI: {
3236		struct ctl_iscsi *ci;
3237		struct ctl_frontend *fe;
3238
3239		ci = (struct ctl_iscsi *)addr;
3240
3241		fe = ctl_frontend_find("iscsi");
3242		if (fe == NULL) {
3243			ci->status = CTL_ISCSI_ERROR;
3244			snprintf(ci->error_str, sizeof(ci->error_str),
3245			    "Frontend \"iscsi\" not found.");
3246			break;
3247		}
3248
3249		retval = fe->ioctl(dev, cmd, addr, flag, td);
3250		break;
3251	}
3252	case CTL_PORT_REQ: {
3253		struct ctl_req *req;
3254		struct ctl_frontend *fe;
3255
3256		req = (struct ctl_req *)addr;
3257
3258		fe = ctl_frontend_find(req->driver);
3259		if (fe == NULL) {
3260			req->status = CTL_LUN_ERROR;
3261			snprintf(req->error_str, sizeof(req->error_str),
3262			    "Frontend \"%s\" not found.", req->driver);
3263			break;
3264		}
3265		if (req->num_args > 0) {
3266			req->kern_args = ctl_copyin_args(req->num_args,
3267			    req->args, req->error_str, sizeof(req->error_str));
3268			if (req->kern_args == NULL) {
3269				req->status = CTL_LUN_ERROR;
3270				break;
3271			}
3272		}
3273
3274		retval = fe->ioctl(dev, cmd, addr, flag, td);
3275
3276		if (req->num_args > 0) {
3277			ctl_copyout_args(req->num_args, req->kern_args);
3278			ctl_free_args(req->num_args, req->kern_args);
3279		}
3280		break;
3281	}
3282	case CTL_PORT_LIST: {
3283		struct sbuf *sb;
3284		struct ctl_port *port;
3285		struct ctl_lun_list *list;
3286		struct ctl_option *opt;
3287
3288		list = (struct ctl_lun_list *)addr;
3289
3290		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3291		if (sb == NULL) {
3292			list->status = CTL_LUN_LIST_ERROR;
3293			snprintf(list->error_str, sizeof(list->error_str),
3294				 "Unable to allocate %d bytes for LUN list",
3295				 list->alloc_len);
3296			break;
3297		}
3298
3299		sbuf_printf(sb, "<ctlportlist>\n");
3300
3301		mtx_lock(&softc->ctl_lock);
3302		STAILQ_FOREACH(port, &softc->port_list, links) {
3303			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3304					     (uintmax_t)port->targ_port);
3305
3306			/*
3307			 * Bail out as soon as we see that we've overfilled
3308			 * the buffer.
3309			 */
3310			if (retval != 0)
3311				break;
3312
3313			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3314			    "</frontend_type>\n", port->frontend->name);
3315			if (retval != 0)
3316				break;
3317
3318			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3319					     port->port_type);
3320			if (retval != 0)
3321				break;
3322
3323			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3324			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3325			if (retval != 0)
3326				break;
3327
3328			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3329			    port->port_name);
3330			if (retval != 0)
3331				break;
3332
3333			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3334			    port->physical_port);
3335			if (retval != 0)
3336				break;
3337
3338			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3339			    port->virtual_port);
3340			if (retval != 0)
3341				break;
3342
3343			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3344			    (uintmax_t)port->wwnn);
3345			if (retval != 0)
3346				break;
3347
3348			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3349			    (uintmax_t)port->wwpn);
3350			if (retval != 0)
3351				break;
3352
3353			if (port->port_info != NULL) {
3354				retval = port->port_info(port->onoff_arg, sb);
3355				if (retval != 0)
3356					break;
3357			}
3358			STAILQ_FOREACH(opt, &port->options, links) {
3359				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3360				    opt->name, opt->value, opt->name);
3361				if (retval != 0)
3362					break;
3363			}
3364
3365			retval = sbuf_printf(sb, "</targ_port>\n");
3366			if (retval != 0)
3367				break;
3368		}
3369		mtx_unlock(&softc->ctl_lock);
3370
3371		if ((retval != 0)
3372		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3373			retval = 0;
3374			sbuf_delete(sb);
3375			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3376			snprintf(list->error_str, sizeof(list->error_str),
3377				 "Out of space, %d bytes is too small",
3378				 list->alloc_len);
3379			break;
3380		}
3381
3382		sbuf_finish(sb);
3383
3384		retval = copyout(sbuf_data(sb), list->lun_xml,
3385				 sbuf_len(sb) + 1);
3386
3387		list->fill_len = sbuf_len(sb) + 1;
3388		list->status = CTL_LUN_LIST_OK;
3389		sbuf_delete(sb);
3390		break;
3391	}
3392	default: {
3393		/* XXX KDM should we fix this? */
3394#if 0
3395		struct ctl_backend_driver *backend;
3396		unsigned int type;
3397		int found;
3398
3399		found = 0;
3400
3401		/*
3402		 * We encode the backend type as the ioctl type for backend
3403		 * ioctls.  So parse it out here, and then search for a
3404		 * backend of this type.
3405		 */
3406		type = _IOC_TYPE(cmd);
3407
3408		STAILQ_FOREACH(backend, &softc->be_list, links) {
3409			if (backend->type == type) {
3410				found = 1;
3411				break;
3412			}
3413		}
3414		if (found == 0) {
3415			printf("ctl: unknown ioctl command %#lx or backend "
3416			       "%d\n", cmd, type);
3417			retval = EINVAL;
3418			break;
3419		}
3420		retval = backend->ioctl(dev, cmd, addr, flag, td);
3421#endif
3422		retval = ENOTTY;
3423		break;
3424	}
3425	}
3426	return (retval);
3427}
3428
3429uint32_t
3430ctl_get_initindex(struct ctl_nexus *nexus)
3431{
3432	if (nexus->targ_port < CTL_MAX_PORTS)
3433		return (nexus->initid.id +
3434			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3435	else
3436		return (nexus->initid.id +
3437		       ((nexus->targ_port - CTL_MAX_PORTS) *
3438			CTL_MAX_INIT_PER_PORT));
3439}
3440
3441uint32_t
3442ctl_get_resindex(struct ctl_nexus *nexus)
3443{
3444	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3445}
3446
3447uint32_t
3448ctl_port_idx(int port_num)
3449{
3450	if (port_num < CTL_MAX_PORTS)
3451		return(port_num);
3452	else
3453		return(port_num - CTL_MAX_PORTS);
3454}
3455
3456static uint32_t
3457ctl_map_lun(int port_num, uint32_t lun_id)
3458{
3459	struct ctl_port *port;
3460
3461	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3462	if (port == NULL)
3463		return (UINT32_MAX);
3464	if (port->lun_map == NULL)
3465		return (lun_id);
3466	return (port->lun_map(port->targ_lun_arg, lun_id));
3467}
3468
3469static uint32_t
3470ctl_map_lun_back(int port_num, uint32_t lun_id)
3471{
3472	struct ctl_port *port;
3473	uint32_t i;
3474
3475	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3476	if (port->lun_map == NULL)
3477		return (lun_id);
3478	for (i = 0; i < CTL_MAX_LUNS; i++) {
3479		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3480			return (i);
3481	}
3482	return (UINT32_MAX);
3483}
3484
3485/*
3486 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3487 * that are a power of 2.
3488 */
3489int
3490ctl_ffz(uint32_t *mask, uint32_t size)
3491{
3492	uint32_t num_chunks, num_pieces;
3493	int i, j;
3494
3495	num_chunks = (size >> 5);
3496	if (num_chunks == 0)
3497		num_chunks++;
3498	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3499
3500	for (i = 0; i < num_chunks; i++) {
3501		for (j = 0; j < num_pieces; j++) {
3502			if ((mask[i] & (1 << j)) == 0)
3503				return ((i << 5) + j);
3504		}
3505	}
3506
3507	return (-1);
3508}
3509
3510int
3511ctl_set_mask(uint32_t *mask, uint32_t bit)
3512{
3513	uint32_t chunk, piece;
3514
3515	chunk = bit >> 5;
3516	piece = bit % (sizeof(uint32_t) * 8);
3517
3518	if ((mask[chunk] & (1 << piece)) != 0)
3519		return (-1);
3520	else
3521		mask[chunk] |= (1 << piece);
3522
3523	return (0);
3524}
3525
3526int
3527ctl_clear_mask(uint32_t *mask, uint32_t bit)
3528{
3529	uint32_t chunk, piece;
3530
3531	chunk = bit >> 5;
3532	piece = bit % (sizeof(uint32_t) * 8);
3533
3534	if ((mask[chunk] & (1 << piece)) == 0)
3535		return (-1);
3536	else
3537		mask[chunk] &= ~(1 << piece);
3538
3539	return (0);
3540}
3541
3542int
3543ctl_is_set(uint32_t *mask, uint32_t bit)
3544{
3545	uint32_t chunk, piece;
3546
3547	chunk = bit >> 5;
3548	piece = bit % (sizeof(uint32_t) * 8);
3549
3550	if ((mask[chunk] & (1 << piece)) == 0)
3551		return (0);
3552	else
3553		return (1);
3554}
3555
3556#ifdef unused
3557/*
3558 * The bus, target and lun are optional, they can be filled in later.
3559 * can_wait is used to determine whether we can wait on the malloc or not.
3560 */
3561union ctl_io*
3562ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3563	      uint32_t targ_lun, int can_wait)
3564{
3565	union ctl_io *io;
3566
3567	if (can_wait)
3568		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3569	else
3570		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3571
3572	if (io != NULL) {
3573		io->io_hdr.io_type = io_type;
3574		io->io_hdr.targ_port = targ_port;
3575		/*
3576		 * XXX KDM this needs to change/go away.  We need to move
3577		 * to a preallocated pool of ctl_scsiio structures.
3578		 */
3579		io->io_hdr.nexus.targ_target.id = targ_target;
3580		io->io_hdr.nexus.targ_lun = targ_lun;
3581	}
3582
3583	return (io);
3584}
3585
3586void
3587ctl_kfree_io(union ctl_io *io)
3588{
3589	free(io, M_CTL);
3590}
3591#endif /* unused */
3592
3593/*
3594 * ctl_softc, pool_type, total_ctl_io are passed in.
3595 * npool is passed out.
3596 */
3597int
3598ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3599		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3600{
3601	uint32_t i;
3602	union ctl_io *cur_io, *next_io;
3603	struct ctl_io_pool *pool;
3604	int retval;
3605
3606	retval = 0;
3607
3608	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3609					    M_NOWAIT | M_ZERO);
3610	if (pool == NULL) {
3611		retval = ENOMEM;
3612		goto bailout;
3613	}
3614
3615	pool->type = pool_type;
3616	pool->ctl_softc = ctl_softc;
3617
3618	mtx_lock(&ctl_softc->pool_lock);
3619	pool->id = ctl_softc->cur_pool_id++;
3620	mtx_unlock(&ctl_softc->pool_lock);
3621
3622	pool->flags = CTL_POOL_FLAG_NONE;
3623	pool->refcount = 1;		/* Reference for validity. */
3624	STAILQ_INIT(&pool->free_queue);
3625
3626	/*
3627	 * XXX KDM other options here:
3628	 * - allocate a page at a time
3629	 * - allocate one big chunk of memory.
3630	 * Page allocation might work well, but would take a little more
3631	 * tracking.
3632	 */
3633	for (i = 0; i < total_ctl_io; i++) {
3634		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3635						M_NOWAIT);
3636		if (cur_io == NULL) {
3637			retval = ENOMEM;
3638			break;
3639		}
3640		cur_io->io_hdr.pool = pool;
3641		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3642		pool->total_ctl_io++;
3643		pool->free_ctl_io++;
3644	}
3645
3646	if (retval != 0) {
3647		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3648		     cur_io != NULL; cur_io = next_io) {
3649			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3650							      links);
3651			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3652				      ctl_io_hdr, links);
3653			free(cur_io, M_CTLIO);
3654		}
3655
3656		free(pool, M_CTL);
3657		goto bailout;
3658	}
3659	mtx_lock(&ctl_softc->pool_lock);
3660	ctl_softc->num_pools++;
3661	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3662	/*
3663	 * Increment our usage count if this is an external consumer, so we
3664	 * can't get unloaded until the external consumer (most likely a
3665	 * FETD) unloads and frees his pool.
3666	 *
3667	 * XXX KDM will this increment the caller's module use count, or
3668	 * mine?
3669	 */
3670#if 0
3671	if ((pool_type != CTL_POOL_EMERGENCY)
3672	 && (pool_type != CTL_POOL_INTERNAL)
3673	 && (pool_type != CTL_POOL_4OTHERSC))
3674		MOD_INC_USE_COUNT;
3675#endif
3676
3677	mtx_unlock(&ctl_softc->pool_lock);
3678
3679	*npool = pool;
3680
3681bailout:
3682
3683	return (retval);
3684}
3685
3686static int
3687ctl_pool_acquire(struct ctl_io_pool *pool)
3688{
3689
3690	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3691
3692	if (pool->flags & CTL_POOL_FLAG_INVALID)
3693		return (EINVAL);
3694
3695	pool->refcount++;
3696
3697	return (0);
3698}
3699
3700static void
3701ctl_pool_release(struct ctl_io_pool *pool)
3702{
3703	struct ctl_softc *ctl_softc = pool->ctl_softc;
3704	union ctl_io *io;
3705
3706	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3707
3708	if (--pool->refcount != 0)
3709		return;
3710
3711	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3712		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3713			      links);
3714		free(io, M_CTLIO);
3715	}
3716
3717	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3718	ctl_softc->num_pools--;
3719
3720	/*
3721	 * XXX KDM will this decrement the caller's usage count or mine?
3722	 */
3723#if 0
3724	if ((pool->type != CTL_POOL_EMERGENCY)
3725	 && (pool->type != CTL_POOL_INTERNAL)
3726	 && (pool->type != CTL_POOL_4OTHERSC))
3727		MOD_DEC_USE_COUNT;
3728#endif
3729
3730	free(pool, M_CTL);
3731}
3732
3733void
3734ctl_pool_free(struct ctl_io_pool *pool)
3735{
3736	struct ctl_softc *ctl_softc;
3737
3738	if (pool == NULL)
3739		return;
3740
3741	ctl_softc = pool->ctl_softc;
3742	mtx_lock(&ctl_softc->pool_lock);
3743	pool->flags |= CTL_POOL_FLAG_INVALID;
3744	ctl_pool_release(pool);
3745	mtx_unlock(&ctl_softc->pool_lock);
3746}
3747
3748/*
3749 * This routine does not block (except for spinlocks of course).
3750 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3751 * possible.
3752 */
3753union ctl_io *
3754ctl_alloc_io(void *pool_ref)
3755{
3756	union ctl_io *io;
3757	struct ctl_softc *ctl_softc;
3758	struct ctl_io_pool *pool, *npool;
3759	struct ctl_io_pool *emergency_pool;
3760
3761	pool = (struct ctl_io_pool *)pool_ref;
3762
3763	if (pool == NULL) {
3764		printf("%s: pool is NULL\n", __func__);
3765		return (NULL);
3766	}
3767
3768	emergency_pool = NULL;
3769
3770	ctl_softc = pool->ctl_softc;
3771
3772	mtx_lock(&ctl_softc->pool_lock);
3773	/*
3774	 * First, try to get the io structure from the user's pool.
3775	 */
3776	if (ctl_pool_acquire(pool) == 0) {
3777		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3778		if (io != NULL) {
3779			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3780			pool->total_allocated++;
3781			pool->free_ctl_io--;
3782			mtx_unlock(&ctl_softc->pool_lock);
3783			return (io);
3784		} else
3785			ctl_pool_release(pool);
3786	}
3787	/*
3788	 * If he doesn't have any io structures left, search for an
3789	 * emergency pool and grab one from there.
3790	 */
3791	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3792		if (npool->type != CTL_POOL_EMERGENCY)
3793			continue;
3794
3795		if (ctl_pool_acquire(npool) != 0)
3796			continue;
3797
3798		emergency_pool = npool;
3799
3800		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3801		if (io != NULL) {
3802			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3803			npool->total_allocated++;
3804			npool->free_ctl_io--;
3805			mtx_unlock(&ctl_softc->pool_lock);
3806			return (io);
3807		} else
3808			ctl_pool_release(npool);
3809	}
3810
3811	/* Drop the spinlock before we malloc */
3812	mtx_unlock(&ctl_softc->pool_lock);
3813
3814	/*
3815	 * The emergency pool (if it exists) didn't have one, so try an
3816	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3817	 */
3818	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3819	if (io != NULL) {
3820		/*
3821		 * If the emergency pool exists but is empty, add this
3822		 * ctl_io to its list when it gets freed.
3823		 */
3824		if (emergency_pool != NULL) {
3825			mtx_lock(&ctl_softc->pool_lock);
3826			if (ctl_pool_acquire(emergency_pool) == 0) {
3827				io->io_hdr.pool = emergency_pool;
3828				emergency_pool->total_ctl_io++;
3829				/*
3830				 * Need to bump this, otherwise
3831				 * total_allocated and total_freed won't
3832				 * match when we no longer have anything
3833				 * outstanding.
3834				 */
3835				emergency_pool->total_allocated++;
3836			}
3837			mtx_unlock(&ctl_softc->pool_lock);
3838		} else
3839			io->io_hdr.pool = NULL;
3840	}
3841
3842	return (io);
3843}
3844
3845void
3846ctl_free_io(union ctl_io *io)
3847{
3848	if (io == NULL)
3849		return;
3850
3851	/*
3852	 * If this ctl_io has a pool, return it to that pool.
3853	 */
3854	if (io->io_hdr.pool != NULL) {
3855		struct ctl_io_pool *pool;
3856
3857		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3858		mtx_lock(&pool->ctl_softc->pool_lock);
3859		io->io_hdr.io_type = 0xff;
3860		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3861		pool->total_freed++;
3862		pool->free_ctl_io++;
3863		ctl_pool_release(pool);
3864		mtx_unlock(&pool->ctl_softc->pool_lock);
3865	} else {
3866		/*
3867		 * Otherwise, just free it.  We probably malloced it and
3868		 * the emergency pool wasn't available.
3869		 */
3870		free(io, M_CTLIO);
3871	}
3872
3873}
3874
3875void
3876ctl_zero_io(union ctl_io *io)
3877{
3878	void *pool_ref;
3879
3880	if (io == NULL)
3881		return;
3882
3883	/*
3884	 * May need to preserve linked list pointers at some point too.
3885	 */
3886	pool_ref = io->io_hdr.pool;
3887
3888	memset(io, 0, sizeof(*io));
3889
3890	io->io_hdr.pool = pool_ref;
3891}
3892
3893/*
3894 * This routine is currently used for internal copies of ctl_ios that need
3895 * to persist for some reason after we've already returned status to the
3896 * FETD.  (Thus the flag set.)
3897 *
3898 * XXX XXX
3899 * Note that this makes a blind copy of all fields in the ctl_io, except
3900 * for the pool reference.  This includes any memory that has been
3901 * allocated!  That memory will no longer be valid after done has been
3902 * called, so this would be VERY DANGEROUS for command that actually does
3903 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3904 * start and stop commands, which don't transfer any data, so this is not a
3905 * problem.  If it is used for anything else, the caller would also need to
3906 * allocate data buffer space and this routine would need to be modified to
3907 * copy the data buffer(s) as well.
3908 */
3909void
3910ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3911{
3912	void *pool_ref;
3913
3914	if ((src == NULL)
3915	 || (dest == NULL))
3916		return;
3917
3918	/*
3919	 * May need to preserve linked list pointers at some point too.
3920	 */
3921	pool_ref = dest->io_hdr.pool;
3922
3923	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3924
3925	dest->io_hdr.pool = pool_ref;
3926	/*
3927	 * We need to know that this is an internal copy, and doesn't need
3928	 * to get passed back to the FETD that allocated it.
3929	 */
3930	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3931}
3932
3933#ifdef NEEDTOPORT
3934static void
3935ctl_update_power_subpage(struct copan_power_subpage *page)
3936{
3937	int num_luns, num_partitions, config_type;
3938	struct ctl_softc *softc;
3939	cs_BOOL_t aor_present, shelf_50pct_power;
3940	cs_raidset_personality_t rs_type;
3941	int max_active_luns;
3942
3943	softc = control_softc;
3944
3945	/* subtract out the processor LUN */
3946	num_luns = softc->num_luns - 1;
3947	/*
3948	 * Default to 7 LUNs active, which was the only number we allowed
3949	 * in the past.
3950	 */
3951	max_active_luns = 7;
3952
3953	num_partitions = config_GetRsPartitionInfo();
3954	config_type = config_GetConfigType();
3955	shelf_50pct_power = config_GetShelfPowerMode();
3956	aor_present = config_IsAorRsPresent();
3957
3958	rs_type = ddb_GetRsRaidType(1);
3959	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3960	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3961		EPRINT(0, "Unsupported RS type %d!", rs_type);
3962	}
3963
3964
3965	page->total_luns = num_luns;
3966
3967	switch (config_type) {
3968	case 40:
3969		/*
3970		 * In a 40 drive configuration, it doesn't matter what DC
3971		 * cards we have, whether we have AOR enabled or not,
3972		 * partitioning or not, or what type of RAIDset we have.
3973		 * In that scenario, we can power up every LUN we present
3974		 * to the user.
3975		 */
3976		max_active_luns = num_luns;
3977
3978		break;
3979	case 64:
3980		if (shelf_50pct_power == CS_FALSE) {
3981			/* 25% power */
3982			if (aor_present == CS_TRUE) {
3983				if (rs_type ==
3984				     CS_RAIDSET_PERSONALITY_RAID5) {
3985					max_active_luns = 7;
3986				} else if (rs_type ==
3987					 CS_RAIDSET_PERSONALITY_RAID1){
3988					max_active_luns = 14;
3989				} else {
3990					/* XXX KDM now what?? */
3991				}
3992			} else {
3993				if (rs_type ==
3994				     CS_RAIDSET_PERSONALITY_RAID5) {
3995					max_active_luns = 8;
3996				} else if (rs_type ==
3997					 CS_RAIDSET_PERSONALITY_RAID1){
3998					max_active_luns = 16;
3999				} else {
4000					/* XXX KDM now what?? */
4001				}
4002			}
4003		} else {
4004			/* 50% power */
4005			/*
4006			 * With 50% power in a 64 drive configuration, we
4007			 * can power all LUNs we present.
4008			 */
4009			max_active_luns = num_luns;
4010		}
4011		break;
4012	case 112:
4013		if (shelf_50pct_power == CS_FALSE) {
4014			/* 25% power */
4015			if (aor_present == CS_TRUE) {
4016				if (rs_type ==
4017				     CS_RAIDSET_PERSONALITY_RAID5) {
4018					max_active_luns = 7;
4019				} else if (rs_type ==
4020					 CS_RAIDSET_PERSONALITY_RAID1){
4021					max_active_luns = 14;
4022				} else {
4023					/* XXX KDM now what?? */
4024				}
4025			} else {
4026				if (rs_type ==
4027				     CS_RAIDSET_PERSONALITY_RAID5) {
4028					max_active_luns = 8;
4029				} else if (rs_type ==
4030					 CS_RAIDSET_PERSONALITY_RAID1){
4031					max_active_luns = 16;
4032				} else {
4033					/* XXX KDM now what?? */
4034				}
4035			}
4036		} else {
4037			/* 50% power */
4038			if (aor_present == CS_TRUE) {
4039				if (rs_type ==
4040				     CS_RAIDSET_PERSONALITY_RAID5) {
4041					max_active_luns = 14;
4042				} else if (rs_type ==
4043					 CS_RAIDSET_PERSONALITY_RAID1){
4044					/*
4045					 * We're assuming here that disk
4046					 * caching is enabled, and so we're
4047					 * able to power up half of each
4048					 * LUN, and cache all writes.
4049					 */
4050					max_active_luns = num_luns;
4051				} else {
4052					/* XXX KDM now what?? */
4053				}
4054			} else {
4055				if (rs_type ==
4056				     CS_RAIDSET_PERSONALITY_RAID5) {
4057					max_active_luns = 15;
4058				} else if (rs_type ==
4059					 CS_RAIDSET_PERSONALITY_RAID1){
4060					max_active_luns = 30;
4061				} else {
4062					/* XXX KDM now what?? */
4063				}
4064			}
4065		}
4066		break;
4067	default:
4068		/*
4069		 * In this case, we have an unknown configuration, so we
4070		 * just use the default from above.
4071		 */
4072		break;
4073	}
4074
4075	page->max_active_luns = max_active_luns;
4076#if 0
4077	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4078	       page->total_luns, page->max_active_luns);
4079#endif
4080}
4081#endif /* NEEDTOPORT */
4082
4083/*
4084 * This routine could be used in the future to load default and/or saved
4085 * mode page parameters for a particuar lun.
4086 */
4087static int
4088ctl_init_page_index(struct ctl_lun *lun)
4089{
4090	int i;
4091	struct ctl_page_index *page_index;
4092	struct ctl_softc *softc;
4093
4094	memcpy(&lun->mode_pages.index, page_index_template,
4095	       sizeof(page_index_template));
4096
4097	softc = lun->ctl_softc;
4098
4099	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4100
4101		page_index = &lun->mode_pages.index[i];
4102		/*
4103		 * If this is a disk-only mode page, there's no point in
4104		 * setting it up.  For some pages, we have to have some
4105		 * basic information about the disk in order to calculate the
4106		 * mode page data.
4107		 */
4108		if ((lun->be_lun->lun_type != T_DIRECT)
4109		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4110			continue;
4111
4112		switch (page_index->page_code & SMPH_PC_MASK) {
4113		case SMS_FORMAT_DEVICE_PAGE: {
4114			struct scsi_format_page *format_page;
4115
4116			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4117				panic("subpage is incorrect!");
4118
4119			/*
4120			 * Sectors per track are set above.  Bytes per
4121			 * sector need to be set here on a per-LUN basis.
4122			 */
4123			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4124			       &format_page_default,
4125			       sizeof(format_page_default));
4126			memcpy(&lun->mode_pages.format_page[
4127			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4128			       sizeof(format_page_changeable));
4129			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4130			       &format_page_default,
4131			       sizeof(format_page_default));
4132			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4133			       &format_page_default,
4134			       sizeof(format_page_default));
4135
4136			format_page = &lun->mode_pages.format_page[
4137				CTL_PAGE_CURRENT];
4138			scsi_ulto2b(lun->be_lun->blocksize,
4139				    format_page->bytes_per_sector);
4140
4141			format_page = &lun->mode_pages.format_page[
4142				CTL_PAGE_DEFAULT];
4143			scsi_ulto2b(lun->be_lun->blocksize,
4144				    format_page->bytes_per_sector);
4145
4146			format_page = &lun->mode_pages.format_page[
4147				CTL_PAGE_SAVED];
4148			scsi_ulto2b(lun->be_lun->blocksize,
4149				    format_page->bytes_per_sector);
4150
4151			page_index->page_data =
4152				(uint8_t *)lun->mode_pages.format_page;
4153			break;
4154		}
4155		case SMS_RIGID_DISK_PAGE: {
4156			struct scsi_rigid_disk_page *rigid_disk_page;
4157			uint32_t sectors_per_cylinder;
4158			uint64_t cylinders;
4159#ifndef	__XSCALE__
4160			int shift;
4161#endif /* !__XSCALE__ */
4162
4163			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4164				panic("invalid subpage value %d",
4165				      page_index->subpage);
4166
4167			/*
4168			 * Rotation rate and sectors per track are set
4169			 * above.  We calculate the cylinders here based on
4170			 * capacity.  Due to the number of heads and
4171			 * sectors per track we're using, smaller arrays
4172			 * may turn out to have 0 cylinders.  Linux and
4173			 * FreeBSD don't pay attention to these mode pages
4174			 * to figure out capacity, but Solaris does.  It
4175			 * seems to deal with 0 cylinders just fine, and
4176			 * works out a fake geometry based on the capacity.
4177			 */
4178			memcpy(&lun->mode_pages.rigid_disk_page[
4179			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4180			       sizeof(rigid_disk_page_default));
4181			memcpy(&lun->mode_pages.rigid_disk_page[
4182			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4183			       sizeof(rigid_disk_page_changeable));
4184			memcpy(&lun->mode_pages.rigid_disk_page[
4185			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4186			       sizeof(rigid_disk_page_default));
4187			memcpy(&lun->mode_pages.rigid_disk_page[
4188			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4189			       sizeof(rigid_disk_page_default));
4190
4191			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4192				CTL_DEFAULT_HEADS;
4193
4194			/*
4195			 * The divide method here will be more accurate,
4196			 * probably, but results in floating point being
4197			 * used in the kernel on i386 (__udivdi3()).  On the
4198			 * XScale, though, __udivdi3() is implemented in
4199			 * software.
4200			 *
4201			 * The shift method for cylinder calculation is
4202			 * accurate if sectors_per_cylinder is a power of
4203			 * 2.  Otherwise it might be slightly off -- you
4204			 * might have a bit of a truncation problem.
4205			 */
4206#ifdef	__XSCALE__
4207			cylinders = (lun->be_lun->maxlba + 1) /
4208				sectors_per_cylinder;
4209#else
4210			for (shift = 31; shift > 0; shift--) {
4211				if (sectors_per_cylinder & (1 << shift))
4212					break;
4213			}
4214			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4215#endif
4216
4217			/*
4218			 * We've basically got 3 bytes, or 24 bits for the
4219			 * cylinder size in the mode page.  If we're over,
4220			 * just round down to 2^24.
4221			 */
4222			if (cylinders > 0xffffff)
4223				cylinders = 0xffffff;
4224
4225			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4226				CTL_PAGE_CURRENT];
4227			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4228
4229			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4230				CTL_PAGE_DEFAULT];
4231			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4232
4233			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4234				CTL_PAGE_SAVED];
4235			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4236
4237			page_index->page_data =
4238				(uint8_t *)lun->mode_pages.rigid_disk_page;
4239			break;
4240		}
4241		case SMS_CACHING_PAGE: {
4242
4243			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4244				panic("invalid subpage value %d",
4245				      page_index->subpage);
4246			/*
4247			 * Defaults should be okay here, no calculations
4248			 * needed.
4249			 */
4250			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4251			       &caching_page_default,
4252			       sizeof(caching_page_default));
4253			memcpy(&lun->mode_pages.caching_page[
4254			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4255			       sizeof(caching_page_changeable));
4256			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4257			       &caching_page_default,
4258			       sizeof(caching_page_default));
4259			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4260			       &caching_page_default,
4261			       sizeof(caching_page_default));
4262			page_index->page_data =
4263				(uint8_t *)lun->mode_pages.caching_page;
4264			break;
4265		}
4266		case SMS_CONTROL_MODE_PAGE: {
4267
4268			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4269				panic("invalid subpage value %d",
4270				      page_index->subpage);
4271
4272			/*
4273			 * Defaults should be okay here, no calculations
4274			 * needed.
4275			 */
4276			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4277			       &control_page_default,
4278			       sizeof(control_page_default));
4279			memcpy(&lun->mode_pages.control_page[
4280			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4281			       sizeof(control_page_changeable));
4282			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4283			       &control_page_default,
4284			       sizeof(control_page_default));
4285			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4286			       &control_page_default,
4287			       sizeof(control_page_default));
4288			page_index->page_data =
4289				(uint8_t *)lun->mode_pages.control_page;
4290			break;
4291
4292		}
4293		case SMS_VENDOR_SPECIFIC_PAGE:{
4294			switch (page_index->subpage) {
4295			case PWR_SUBPAGE_CODE: {
4296				struct copan_power_subpage *current_page,
4297							   *saved_page;
4298
4299				memcpy(&lun->mode_pages.power_subpage[
4300				       CTL_PAGE_CURRENT],
4301				       &power_page_default,
4302				       sizeof(power_page_default));
4303				memcpy(&lun->mode_pages.power_subpage[
4304				       CTL_PAGE_CHANGEABLE],
4305				       &power_page_changeable,
4306				       sizeof(power_page_changeable));
4307				memcpy(&lun->mode_pages.power_subpage[
4308				       CTL_PAGE_DEFAULT],
4309				       &power_page_default,
4310				       sizeof(power_page_default));
4311				memcpy(&lun->mode_pages.power_subpage[
4312				       CTL_PAGE_SAVED],
4313				       &power_page_default,
4314				       sizeof(power_page_default));
4315				page_index->page_data =
4316				    (uint8_t *)lun->mode_pages.power_subpage;
4317
4318				current_page = (struct copan_power_subpage *)
4319					(page_index->page_data +
4320					 (page_index->page_len *
4321					  CTL_PAGE_CURRENT));
4322			        saved_page = (struct copan_power_subpage *)
4323				        (page_index->page_data +
4324					 (page_index->page_len *
4325					  CTL_PAGE_SAVED));
4326				break;
4327			}
4328			case APS_SUBPAGE_CODE: {
4329				struct copan_aps_subpage *current_page,
4330							 *saved_page;
4331
4332				// This gets set multiple times but
4333				// it should always be the same. It's
4334				// only done during init so who cares.
4335				index_to_aps_page = i;
4336
4337				memcpy(&lun->mode_pages.aps_subpage[
4338				       CTL_PAGE_CURRENT],
4339				       &aps_page_default,
4340				       sizeof(aps_page_default));
4341				memcpy(&lun->mode_pages.aps_subpage[
4342				       CTL_PAGE_CHANGEABLE],
4343				       &aps_page_changeable,
4344				       sizeof(aps_page_changeable));
4345				memcpy(&lun->mode_pages.aps_subpage[
4346				       CTL_PAGE_DEFAULT],
4347				       &aps_page_default,
4348				       sizeof(aps_page_default));
4349				memcpy(&lun->mode_pages.aps_subpage[
4350				       CTL_PAGE_SAVED],
4351				       &aps_page_default,
4352				       sizeof(aps_page_default));
4353				page_index->page_data =
4354					(uint8_t *)lun->mode_pages.aps_subpage;
4355
4356				current_page = (struct copan_aps_subpage *)
4357					(page_index->page_data +
4358					 (page_index->page_len *
4359					  CTL_PAGE_CURRENT));
4360				saved_page = (struct copan_aps_subpage *)
4361					(page_index->page_data +
4362					 (page_index->page_len *
4363					  CTL_PAGE_SAVED));
4364				break;
4365			}
4366			case DBGCNF_SUBPAGE_CODE: {
4367				struct copan_debugconf_subpage *current_page,
4368							       *saved_page;
4369
4370				memcpy(&lun->mode_pages.debugconf_subpage[
4371				       CTL_PAGE_CURRENT],
4372				       &debugconf_page_default,
4373				       sizeof(debugconf_page_default));
4374				memcpy(&lun->mode_pages.debugconf_subpage[
4375				       CTL_PAGE_CHANGEABLE],
4376				       &debugconf_page_changeable,
4377				       sizeof(debugconf_page_changeable));
4378				memcpy(&lun->mode_pages.debugconf_subpage[
4379				       CTL_PAGE_DEFAULT],
4380				       &debugconf_page_default,
4381				       sizeof(debugconf_page_default));
4382				memcpy(&lun->mode_pages.debugconf_subpage[
4383				       CTL_PAGE_SAVED],
4384				       &debugconf_page_default,
4385				       sizeof(debugconf_page_default));
4386				page_index->page_data =
4387					(uint8_t *)lun->mode_pages.debugconf_subpage;
4388
4389				current_page = (struct copan_debugconf_subpage *)
4390					(page_index->page_data +
4391					 (page_index->page_len *
4392					  CTL_PAGE_CURRENT));
4393				saved_page = (struct copan_debugconf_subpage *)
4394					(page_index->page_data +
4395					 (page_index->page_len *
4396					  CTL_PAGE_SAVED));
4397				break;
4398			}
4399			default:
4400				panic("invalid subpage value %d",
4401				      page_index->subpage);
4402				break;
4403			}
4404   			break;
4405		}
4406		default:
4407			panic("invalid page value %d",
4408			      page_index->page_code & SMPH_PC_MASK);
4409			break;
4410    	}
4411	}
4412
4413	return (CTL_RETVAL_COMPLETE);
4414}
4415
4416/*
4417 * LUN allocation.
4418 *
4419 * Requirements:
4420 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4421 *   wants us to allocate the LUN and he can block.
4422 * - ctl_softc is always set
4423 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4424 *
4425 * Returns 0 for success, non-zero (errno) for failure.
4426 */
4427static int
4428ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4429	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4430{
4431	struct ctl_lun *nlun, *lun;
4432	struct ctl_port *port;
4433	struct scsi_vpd_id_descriptor *desc;
4434	struct scsi_vpd_id_t10 *t10id;
4435	const char *scsiname, *vendor;
4436	int lun_number, i, lun_malloced;
4437	int devidlen, idlen1, idlen2 = 0, len;
4438
4439	if (be_lun == NULL)
4440		return (EINVAL);
4441
4442	/*
4443	 * We currently only support Direct Access or Processor LUN types.
4444	 */
4445	switch (be_lun->lun_type) {
4446	case T_DIRECT:
4447		break;
4448	case T_PROCESSOR:
4449		break;
4450	case T_SEQUENTIAL:
4451	case T_CHANGER:
4452	default:
4453		be_lun->lun_config_status(be_lun->be_lun,
4454					  CTL_LUN_CONFIG_FAILURE);
4455		break;
4456	}
4457	if (ctl_lun == NULL) {
4458		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4459		lun_malloced = 1;
4460	} else {
4461		lun_malloced = 0;
4462		lun = ctl_lun;
4463	}
4464
4465	memset(lun, 0, sizeof(*lun));
4466	if (lun_malloced)
4467		lun->flags = CTL_LUN_MALLOCED;
4468
4469	/* Generate LUN ID. */
4470	devidlen = max(CTL_DEVID_MIN_LEN,
4471	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4472	idlen1 = sizeof(*t10id) + devidlen;
4473	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4474	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4475	if (scsiname != NULL) {
4476		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4477		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4478	}
4479	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4480	    M_CTL, M_WAITOK | M_ZERO);
4481	lun->lun_devid->len = len;
4482	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4483	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4484	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4485	desc->length = idlen1;
4486	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4487	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4488	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4489		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4490	} else {
4491		strncpy(t10id->vendor, vendor,
4492		    min(sizeof(t10id->vendor), strlen(vendor)));
4493	}
4494	strncpy((char *)t10id->vendor_spec_id,
4495	    (char *)be_lun->device_id, devidlen);
4496	if (scsiname != NULL) {
4497		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4498		    desc->length);
4499		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4500		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4501		    SVPD_ID_TYPE_SCSI_NAME;
4502		desc->length = idlen2;
4503		strlcpy(desc->identifier, scsiname, idlen2);
4504	}
4505
4506	mtx_lock(&ctl_softc->ctl_lock);
4507	/*
4508	 * See if the caller requested a particular LUN number.  If so, see
4509	 * if it is available.  Otherwise, allocate the first available LUN.
4510	 */
4511	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4512		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4513		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4514			mtx_unlock(&ctl_softc->ctl_lock);
4515			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4516				printf("ctl: requested LUN ID %d is higher "
4517				       "than CTL_MAX_LUNS - 1 (%d)\n",
4518				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4519			} else {
4520				/*
4521				 * XXX KDM return an error, or just assign
4522				 * another LUN ID in this case??
4523				 */
4524				printf("ctl: requested LUN ID %d is already "
4525				       "in use\n", be_lun->req_lun_id);
4526			}
4527			if (lun->flags & CTL_LUN_MALLOCED)
4528				free(lun, M_CTL);
4529			be_lun->lun_config_status(be_lun->be_lun,
4530						  CTL_LUN_CONFIG_FAILURE);
4531			return (ENOSPC);
4532		}
4533		lun_number = be_lun->req_lun_id;
4534	} else {
4535		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4536		if (lun_number == -1) {
4537			mtx_unlock(&ctl_softc->ctl_lock);
4538			printf("ctl: can't allocate LUN on target %ju, out of "
4539			       "LUNs\n", (uintmax_t)target_id.id);
4540			if (lun->flags & CTL_LUN_MALLOCED)
4541				free(lun, M_CTL);
4542			be_lun->lun_config_status(be_lun->be_lun,
4543						  CTL_LUN_CONFIG_FAILURE);
4544			return (ENOSPC);
4545		}
4546	}
4547	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4548
4549	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4550	lun->target = target_id;
4551	lun->lun = lun_number;
4552	lun->be_lun = be_lun;
4553	/*
4554	 * The processor LUN is always enabled.  Disk LUNs come on line
4555	 * disabled, and must be enabled by the backend.
4556	 */
4557	lun->flags |= CTL_LUN_DISABLED;
4558	lun->backend = be_lun->be;
4559	be_lun->ctl_lun = lun;
4560	be_lun->lun_id = lun_number;
4561	atomic_add_int(&be_lun->be->num_luns, 1);
4562	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4563		lun->flags |= CTL_LUN_STOPPED;
4564
4565	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4566		lun->flags |= CTL_LUN_INOPERABLE;
4567
4568	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4569		lun->flags |= CTL_LUN_PRIMARY_SC;
4570
4571	lun->ctl_softc = ctl_softc;
4572	TAILQ_INIT(&lun->ooa_queue);
4573	TAILQ_INIT(&lun->blocked_queue);
4574	STAILQ_INIT(&lun->error_list);
4575
4576	/*
4577	 * Initialize the mode page index.
4578	 */
4579	ctl_init_page_index(lun);
4580
4581	/*
4582	 * Set the poweron UA for all initiators on this LUN only.
4583	 */
4584	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4585		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4586
4587	/*
4588	 * Now, before we insert this lun on the lun list, set the lun
4589	 * inventory changed UA for all other luns.
4590	 */
4591	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4592		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4593			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4594		}
4595	}
4596
4597	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4598
4599	ctl_softc->ctl_luns[lun_number] = lun;
4600
4601	ctl_softc->num_luns++;
4602
4603	/* Setup statistics gathering */
4604	lun->stats.device_type = be_lun->lun_type;
4605	lun->stats.lun_number = lun_number;
4606	if (lun->stats.device_type == T_DIRECT)
4607		lun->stats.blocksize = be_lun->blocksize;
4608	else
4609		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4610	for (i = 0;i < CTL_MAX_PORTS;i++)
4611		lun->stats.ports[i].targ_port = i;
4612
4613	mtx_unlock(&ctl_softc->ctl_lock);
4614
4615	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4616
4617	/*
4618	 * Run through each registered FETD and bring it online if it isn't
4619	 * already.  Enable the target ID if it hasn't been enabled, and
4620	 * enable this particular LUN.
4621	 */
4622	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4623		int retval;
4624
4625		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4626		if (retval != 0) {
4627			printf("ctl_alloc_lun: FETD %s port %d returned error "
4628			       "%d for lun_enable on target %ju lun %d\n",
4629			       port->port_name, port->targ_port, retval,
4630			       (uintmax_t)target_id.id, lun_number);
4631		} else
4632			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4633	}
4634	return (0);
4635}
4636
4637/*
4638 * Delete a LUN.
4639 * Assumptions:
4640 * - LUN has already been marked invalid and any pending I/O has been taken
4641 *   care of.
4642 */
4643static int
4644ctl_free_lun(struct ctl_lun *lun)
4645{
4646	struct ctl_softc *softc;
4647#if 0
4648	struct ctl_port *port;
4649#endif
4650	struct ctl_lun *nlun;
4651	int i;
4652
4653	softc = lun->ctl_softc;
4654
4655	mtx_assert(&softc->ctl_lock, MA_OWNED);
4656
4657	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4658
4659	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4660
4661	softc->ctl_luns[lun->lun] = NULL;
4662
4663	if (!TAILQ_EMPTY(&lun->ooa_queue))
4664		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4665
4666	softc->num_luns--;
4667
4668	/*
4669	 * XXX KDM this scheme only works for a single target/multiple LUN
4670	 * setup.  It needs to be revamped for a multiple target scheme.
4671	 *
4672	 * XXX KDM this results in port->lun_disable() getting called twice,
4673	 * once when ctl_disable_lun() is called, and a second time here.
4674	 * We really need to re-think the LUN disable semantics.  There
4675	 * should probably be several steps/levels to LUN removal:
4676	 *  - disable
4677	 *  - invalidate
4678	 *  - free
4679 	 *
4680	 * Right now we only have a disable method when communicating to
4681	 * the front end ports, at least for individual LUNs.
4682	 */
4683#if 0
4684	STAILQ_FOREACH(port, &softc->port_list, links) {
4685		int retval;
4686
4687		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4688					 lun->lun);
4689		if (retval != 0) {
4690			printf("ctl_free_lun: FETD %s port %d returned error "
4691			       "%d for lun_disable on target %ju lun %jd\n",
4692			       port->port_name, port->targ_port, retval,
4693			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4694		}
4695
4696		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4697			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4698
4699			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4700			if (retval != 0) {
4701				printf("ctl_free_lun: FETD %s port %d "
4702				       "returned error %d for targ_disable on "
4703				       "target %ju\n", port->port_name,
4704				       port->targ_port, retval,
4705				       (uintmax_t)lun->target.id);
4706			} else
4707				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4708
4709			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4710				continue;
4711
4712#if 0
4713			port->port_offline(port->onoff_arg);
4714			port->status &= ~CTL_PORT_STATUS_ONLINE;
4715#endif
4716		}
4717	}
4718#endif
4719
4720	/*
4721	 * Tell the backend to free resources, if this LUN has a backend.
4722	 */
4723	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4724	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4725
4726	mtx_destroy(&lun->lun_lock);
4727	free(lun->lun_devid, M_CTL);
4728	if (lun->flags & CTL_LUN_MALLOCED)
4729		free(lun, M_CTL);
4730
4731	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4732		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4733			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4734		}
4735	}
4736
4737	return (0);
4738}
4739
4740static void
4741ctl_create_lun(struct ctl_be_lun *be_lun)
4742{
4743	struct ctl_softc *ctl_softc;
4744
4745	ctl_softc = control_softc;
4746
4747	/*
4748	 * ctl_alloc_lun() should handle all potential failure cases.
4749	 */
4750	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4751}
4752
4753int
4754ctl_add_lun(struct ctl_be_lun *be_lun)
4755{
4756	struct ctl_softc *ctl_softc = control_softc;
4757
4758	mtx_lock(&ctl_softc->ctl_lock);
4759	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4760	mtx_unlock(&ctl_softc->ctl_lock);
4761	wakeup(&ctl_softc->pending_lun_queue);
4762
4763	return (0);
4764}
4765
4766int
4767ctl_enable_lun(struct ctl_be_lun *be_lun)
4768{
4769	struct ctl_softc *ctl_softc;
4770	struct ctl_port *port, *nport;
4771	struct ctl_lun *lun;
4772	int retval;
4773
4774	ctl_softc = control_softc;
4775
4776	lun = (struct ctl_lun *)be_lun->ctl_lun;
4777
4778	mtx_lock(&ctl_softc->ctl_lock);
4779	mtx_lock(&lun->lun_lock);
4780	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4781		/*
4782		 * eh?  Why did we get called if the LUN is already
4783		 * enabled?
4784		 */
4785		mtx_unlock(&lun->lun_lock);
4786		mtx_unlock(&ctl_softc->ctl_lock);
4787		return (0);
4788	}
4789	lun->flags &= ~CTL_LUN_DISABLED;
4790	mtx_unlock(&lun->lun_lock);
4791
4792	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4793		nport = STAILQ_NEXT(port, links);
4794
4795		/*
4796		 * Drop the lock while we call the FETD's enable routine.
4797		 * This can lead to a callback into CTL (at least in the
4798		 * case of the internal initiator frontend.
4799		 */
4800		mtx_unlock(&ctl_softc->ctl_lock);
4801		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4802		mtx_lock(&ctl_softc->ctl_lock);
4803		if (retval != 0) {
4804			printf("%s: FETD %s port %d returned error "
4805			       "%d for lun_enable on target %ju lun %jd\n",
4806			       __func__, port->port_name, port->targ_port, retval,
4807			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4808		}
4809#if 0
4810		 else {
4811            /* NOTE:  TODO:  why does lun enable affect port status? */
4812			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4813		}
4814#endif
4815	}
4816
4817	mtx_unlock(&ctl_softc->ctl_lock);
4818
4819	return (0);
4820}
4821
4822int
4823ctl_disable_lun(struct ctl_be_lun *be_lun)
4824{
4825	struct ctl_softc *ctl_softc;
4826	struct ctl_port *port;
4827	struct ctl_lun *lun;
4828	int retval;
4829
4830	ctl_softc = control_softc;
4831
4832	lun = (struct ctl_lun *)be_lun->ctl_lun;
4833
4834	mtx_lock(&ctl_softc->ctl_lock);
4835	mtx_lock(&lun->lun_lock);
4836	if (lun->flags & CTL_LUN_DISABLED) {
4837		mtx_unlock(&lun->lun_lock);
4838		mtx_unlock(&ctl_softc->ctl_lock);
4839		return (0);
4840	}
4841	lun->flags |= CTL_LUN_DISABLED;
4842	mtx_unlock(&lun->lun_lock);
4843
4844	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4845		mtx_unlock(&ctl_softc->ctl_lock);
4846		/*
4847		 * Drop the lock before we call the frontend's disable
4848		 * routine, to avoid lock order reversals.
4849		 *
4850		 * XXX KDM what happens if the frontend list changes while
4851		 * we're traversing it?  It's unlikely, but should be handled.
4852		 */
4853		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4854					 lun->lun);
4855		mtx_lock(&ctl_softc->ctl_lock);
4856		if (retval != 0) {
4857			printf("ctl_alloc_lun: FETD %s port %d returned error "
4858			       "%d for lun_disable on target %ju lun %jd\n",
4859			       port->port_name, port->targ_port, retval,
4860			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4861		}
4862	}
4863
4864	mtx_unlock(&ctl_softc->ctl_lock);
4865
4866	return (0);
4867}
4868
4869int
4870ctl_start_lun(struct ctl_be_lun *be_lun)
4871{
4872	struct ctl_softc *ctl_softc;
4873	struct ctl_lun *lun;
4874
4875	ctl_softc = control_softc;
4876
4877	lun = (struct ctl_lun *)be_lun->ctl_lun;
4878
4879	mtx_lock(&lun->lun_lock);
4880	lun->flags &= ~CTL_LUN_STOPPED;
4881	mtx_unlock(&lun->lun_lock);
4882
4883	return (0);
4884}
4885
4886int
4887ctl_stop_lun(struct ctl_be_lun *be_lun)
4888{
4889	struct ctl_softc *ctl_softc;
4890	struct ctl_lun *lun;
4891
4892	ctl_softc = control_softc;
4893
4894	lun = (struct ctl_lun *)be_lun->ctl_lun;
4895
4896	mtx_lock(&lun->lun_lock);
4897	lun->flags |= CTL_LUN_STOPPED;
4898	mtx_unlock(&lun->lun_lock);
4899
4900	return (0);
4901}
4902
4903int
4904ctl_lun_offline(struct ctl_be_lun *be_lun)
4905{
4906	struct ctl_softc *ctl_softc;
4907	struct ctl_lun *lun;
4908
4909	ctl_softc = control_softc;
4910
4911	lun = (struct ctl_lun *)be_lun->ctl_lun;
4912
4913	mtx_lock(&lun->lun_lock);
4914	lun->flags |= CTL_LUN_OFFLINE;
4915	mtx_unlock(&lun->lun_lock);
4916
4917	return (0);
4918}
4919
4920int
4921ctl_lun_online(struct ctl_be_lun *be_lun)
4922{
4923	struct ctl_softc *ctl_softc;
4924	struct ctl_lun *lun;
4925
4926	ctl_softc = control_softc;
4927
4928	lun = (struct ctl_lun *)be_lun->ctl_lun;
4929
4930	mtx_lock(&lun->lun_lock);
4931	lun->flags &= ~CTL_LUN_OFFLINE;
4932	mtx_unlock(&lun->lun_lock);
4933
4934	return (0);
4935}
4936
4937int
4938ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4939{
4940	struct ctl_softc *ctl_softc;
4941	struct ctl_lun *lun;
4942
4943	ctl_softc = control_softc;
4944
4945	lun = (struct ctl_lun *)be_lun->ctl_lun;
4946
4947	mtx_lock(&lun->lun_lock);
4948
4949	/*
4950	 * The LUN needs to be disabled before it can be marked invalid.
4951	 */
4952	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4953		mtx_unlock(&lun->lun_lock);
4954		return (-1);
4955	}
4956	/*
4957	 * Mark the LUN invalid.
4958	 */
4959	lun->flags |= CTL_LUN_INVALID;
4960
4961	/*
4962	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4963	 * If we have something in the OOA queue, we'll free it when the
4964	 * last I/O completes.
4965	 */
4966	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4967		mtx_unlock(&lun->lun_lock);
4968		mtx_lock(&ctl_softc->ctl_lock);
4969		ctl_free_lun(lun);
4970		mtx_unlock(&ctl_softc->ctl_lock);
4971	} else
4972		mtx_unlock(&lun->lun_lock);
4973
4974	return (0);
4975}
4976
4977int
4978ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4979{
4980	struct ctl_softc *ctl_softc;
4981	struct ctl_lun *lun;
4982
4983	ctl_softc = control_softc;
4984	lun = (struct ctl_lun *)be_lun->ctl_lun;
4985
4986	mtx_lock(&lun->lun_lock);
4987	lun->flags |= CTL_LUN_INOPERABLE;
4988	mtx_unlock(&lun->lun_lock);
4989
4990	return (0);
4991}
4992
4993int
4994ctl_lun_operable(struct ctl_be_lun *be_lun)
4995{
4996	struct ctl_softc *ctl_softc;
4997	struct ctl_lun *lun;
4998
4999	ctl_softc = control_softc;
5000	lun = (struct ctl_lun *)be_lun->ctl_lun;
5001
5002	mtx_lock(&lun->lun_lock);
5003	lun->flags &= ~CTL_LUN_INOPERABLE;
5004	mtx_unlock(&lun->lun_lock);
5005
5006	return (0);
5007}
5008
5009int
5010ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5011		   int lock)
5012{
5013	struct ctl_softc *softc;
5014	struct ctl_lun *lun;
5015	struct copan_aps_subpage *current_sp;
5016	struct ctl_page_index *page_index;
5017	int i;
5018
5019	softc = control_softc;
5020
5021	mtx_lock(&softc->ctl_lock);
5022
5023	lun = (struct ctl_lun *)be_lun->ctl_lun;
5024	mtx_lock(&lun->lun_lock);
5025
5026	page_index = NULL;
5027	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5028		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5029		     APS_PAGE_CODE)
5030			continue;
5031
5032		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5033			continue;
5034		page_index = &lun->mode_pages.index[i];
5035	}
5036
5037	if (page_index == NULL) {
5038		mtx_unlock(&lun->lun_lock);
5039		mtx_unlock(&softc->ctl_lock);
5040		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5041		       (uintmax_t)lun->lun);
5042		return (1);
5043	}
5044#if 0
5045	if ((softc->aps_locked_lun != 0)
5046	 && (softc->aps_locked_lun != lun->lun)) {
5047		printf("%s: attempt to lock LUN %llu when %llu is already "
5048		       "locked\n");
5049		mtx_unlock(&lun->lun_lock);
5050		mtx_unlock(&softc->ctl_lock);
5051		return (1);
5052	}
5053#endif
5054
5055	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5056		(page_index->page_len * CTL_PAGE_CURRENT));
5057
5058	if (lock != 0) {
5059		current_sp->lock_active = APS_LOCK_ACTIVE;
5060		softc->aps_locked_lun = lun->lun;
5061	} else {
5062		current_sp->lock_active = 0;
5063		softc->aps_locked_lun = 0;
5064	}
5065
5066
5067	/*
5068	 * If we're in HA mode, try to send the lock message to the other
5069	 * side.
5070	 */
5071	if (ctl_is_single == 0) {
5072		int isc_retval;
5073		union ctl_ha_msg lock_msg;
5074
5075		lock_msg.hdr.nexus = *nexus;
5076		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5077		if (lock != 0)
5078			lock_msg.aps.lock_flag = 1;
5079		else
5080			lock_msg.aps.lock_flag = 0;
5081		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5082					 sizeof(lock_msg), 0);
5083		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5084			printf("%s: APS (lock=%d) error returned from "
5085			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5086			mtx_unlock(&lun->lun_lock);
5087			mtx_unlock(&softc->ctl_lock);
5088			return (1);
5089		}
5090	}
5091
5092	mtx_unlock(&lun->lun_lock);
5093	mtx_unlock(&softc->ctl_lock);
5094
5095	return (0);
5096}
5097
5098void
5099ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5100{
5101	struct ctl_lun *lun;
5102	struct ctl_softc *softc;
5103	int i;
5104
5105	softc = control_softc;
5106
5107	lun = (struct ctl_lun *)be_lun->ctl_lun;
5108
5109	mtx_lock(&lun->lun_lock);
5110
5111	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5112		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
5113
5114	mtx_unlock(&lun->lun_lock);
5115}
5116
5117/*
5118 * Backend "memory move is complete" callback for requests that never
5119 * make it down to say RAIDCore's configuration code.
5120 */
5121int
5122ctl_config_move_done(union ctl_io *io)
5123{
5124	int retval;
5125
5126	retval = CTL_RETVAL_COMPLETE;
5127
5128
5129	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5130	/*
5131	 * XXX KDM this shouldn't happen, but what if it does?
5132	 */
5133	if (io->io_hdr.io_type != CTL_IO_SCSI)
5134		panic("I/O type isn't CTL_IO_SCSI!");
5135
5136	if ((io->io_hdr.port_status == 0)
5137	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5138	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5139		io->io_hdr.status = CTL_SUCCESS;
5140	else if ((io->io_hdr.port_status != 0)
5141	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5142	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5143		/*
5144		 * For hardware error sense keys, the sense key
5145		 * specific value is defined to be a retry count,
5146		 * but we use it to pass back an internal FETD
5147		 * error code.  XXX KDM  Hopefully the FETD is only
5148		 * using 16 bits for an error code, since that's
5149		 * all the space we have in the sks field.
5150		 */
5151		ctl_set_internal_failure(&io->scsiio,
5152					 /*sks_valid*/ 1,
5153					 /*retry_count*/
5154					 io->io_hdr.port_status);
5155		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5156			free(io->scsiio.kern_data_ptr, M_CTL);
5157		ctl_done(io);
5158		goto bailout;
5159	}
5160
5161	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5162	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5163	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5164		/*
5165		 * XXX KDM just assuming a single pointer here, and not a
5166		 * S/G list.  If we start using S/G lists for config data,
5167		 * we'll need to know how to clean them up here as well.
5168		 */
5169		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5170			free(io->scsiio.kern_data_ptr, M_CTL);
5171		/* Hopefully the user has already set the status... */
5172		ctl_done(io);
5173	} else {
5174		/*
5175		 * XXX KDM now we need to continue data movement.  Some
5176		 * options:
5177		 * - call ctl_scsiio() again?  We don't do this for data
5178		 *   writes, because for those at least we know ahead of
5179		 *   time where the write will go and how long it is.  For
5180		 *   config writes, though, that information is largely
5181		 *   contained within the write itself, thus we need to
5182		 *   parse out the data again.
5183		 *
5184		 * - Call some other function once the data is in?
5185		 */
5186
5187		/*
5188		 * XXX KDM call ctl_scsiio() again for now, and check flag
5189		 * bits to see whether we're allocated or not.
5190		 */
5191		retval = ctl_scsiio(&io->scsiio);
5192	}
5193bailout:
5194	return (retval);
5195}
5196
5197/*
5198 * This gets called by a backend driver when it is done with a
5199 * data_submit method.
5200 */
5201void
5202ctl_data_submit_done(union ctl_io *io)
5203{
5204	/*
5205	 * If the IO_CONT flag is set, we need to call the supplied
5206	 * function to continue processing the I/O, instead of completing
5207	 * the I/O just yet.
5208	 *
5209	 * If there is an error, though, we don't want to keep processing.
5210	 * Instead, just send status back to the initiator.
5211	 */
5212	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5213	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5214	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5215	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5216		io->scsiio.io_cont(io);
5217		return;
5218	}
5219	ctl_done(io);
5220}
5221
5222/*
5223 * This gets called by a backend driver when it is done with a
5224 * configuration write.
5225 */
5226void
5227ctl_config_write_done(union ctl_io *io)
5228{
5229	/*
5230	 * If the IO_CONT flag is set, we need to call the supplied
5231	 * function to continue processing the I/O, instead of completing
5232	 * the I/O just yet.
5233	 *
5234	 * If there is an error, though, we don't want to keep processing.
5235	 * Instead, just send status back to the initiator.
5236	 */
5237	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5238	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5239	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5240		io->scsiio.io_cont(io);
5241		return;
5242	}
5243	/*
5244	 * Since a configuration write can be done for commands that actually
5245	 * have data allocated, like write buffer, and commands that have
5246	 * no data, like start/stop unit, we need to check here.
5247	 */
5248	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5249		free(io->scsiio.kern_data_ptr, M_CTL);
5250	ctl_done(io);
5251}
5252
5253/*
5254 * SCSI release command.
5255 */
5256int
5257ctl_scsi_release(struct ctl_scsiio *ctsio)
5258{
5259	int length, longid, thirdparty_id, resv_id;
5260	struct ctl_softc *ctl_softc;
5261	struct ctl_lun *lun;
5262
5263	length = 0;
5264	resv_id = 0;
5265
5266	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5267
5268	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5269	ctl_softc = control_softc;
5270
5271	switch (ctsio->cdb[0]) {
5272	case RELEASE_10: {
5273		struct scsi_release_10 *cdb;
5274
5275		cdb = (struct scsi_release_10 *)ctsio->cdb;
5276
5277		if (cdb->byte2 & SR10_LONGID)
5278			longid = 1;
5279		else
5280			thirdparty_id = cdb->thirdparty_id;
5281
5282		resv_id = cdb->resv_id;
5283		length = scsi_2btoul(cdb->length);
5284		break;
5285	}
5286	}
5287
5288
5289	/*
5290	 * XXX KDM right now, we only support LUN reservation.  We don't
5291	 * support 3rd party reservations, or extent reservations, which
5292	 * might actually need the parameter list.  If we've gotten this
5293	 * far, we've got a LUN reservation.  Anything else got kicked out
5294	 * above.  So, according to SPC, ignore the length.
5295	 */
5296	length = 0;
5297
5298	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5299	 && (length > 0)) {
5300		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5301		ctsio->kern_data_len = length;
5302		ctsio->kern_total_len = length;
5303		ctsio->kern_data_resid = 0;
5304		ctsio->kern_rel_offset = 0;
5305		ctsio->kern_sg_entries = 0;
5306		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5307		ctsio->be_move_done = ctl_config_move_done;
5308		ctl_datamove((union ctl_io *)ctsio);
5309
5310		return (CTL_RETVAL_COMPLETE);
5311	}
5312
5313	if (length > 0)
5314		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5315
5316	mtx_lock(&lun->lun_lock);
5317
5318	/*
5319	 * According to SPC, it is not an error for an intiator to attempt
5320	 * to release a reservation on a LUN that isn't reserved, or that
5321	 * is reserved by another initiator.  The reservation can only be
5322	 * released, though, by the initiator who made it or by one of
5323	 * several reset type events.
5324	 */
5325	if (lun->flags & CTL_LUN_RESERVED) {
5326		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5327		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5328		 && (ctsio->io_hdr.nexus.targ_target.id ==
5329		     lun->rsv_nexus.targ_target.id)) {
5330			lun->flags &= ~CTL_LUN_RESERVED;
5331		}
5332	}
5333
5334	mtx_unlock(&lun->lun_lock);
5335
5336	ctsio->scsi_status = SCSI_STATUS_OK;
5337	ctsio->io_hdr.status = CTL_SUCCESS;
5338
5339	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5340		free(ctsio->kern_data_ptr, M_CTL);
5341		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5342	}
5343
5344	ctl_done((union ctl_io *)ctsio);
5345	return (CTL_RETVAL_COMPLETE);
5346}
5347
5348int
5349ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5350{
5351	int extent, thirdparty, longid;
5352	int resv_id, length;
5353	uint64_t thirdparty_id;
5354	struct ctl_softc *ctl_softc;
5355	struct ctl_lun *lun;
5356
5357	extent = 0;
5358	thirdparty = 0;
5359	longid = 0;
5360	resv_id = 0;
5361	length = 0;
5362	thirdparty_id = 0;
5363
5364	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5365
5366	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5367	ctl_softc = control_softc;
5368
5369	switch (ctsio->cdb[0]) {
5370	case RESERVE_10: {
5371		struct scsi_reserve_10 *cdb;
5372
5373		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5374
5375		if (cdb->byte2 & SR10_LONGID)
5376			longid = 1;
5377		else
5378			thirdparty_id = cdb->thirdparty_id;
5379
5380		resv_id = cdb->resv_id;
5381		length = scsi_2btoul(cdb->length);
5382		break;
5383	}
5384	}
5385
5386	/*
5387	 * XXX KDM right now, we only support LUN reservation.  We don't
5388	 * support 3rd party reservations, or extent reservations, which
5389	 * might actually need the parameter list.  If we've gotten this
5390	 * far, we've got a LUN reservation.  Anything else got kicked out
5391	 * above.  So, according to SPC, ignore the length.
5392	 */
5393	length = 0;
5394
5395	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5396	 && (length > 0)) {
5397		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5398		ctsio->kern_data_len = length;
5399		ctsio->kern_total_len = length;
5400		ctsio->kern_data_resid = 0;
5401		ctsio->kern_rel_offset = 0;
5402		ctsio->kern_sg_entries = 0;
5403		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5404		ctsio->be_move_done = ctl_config_move_done;
5405		ctl_datamove((union ctl_io *)ctsio);
5406
5407		return (CTL_RETVAL_COMPLETE);
5408	}
5409
5410	if (length > 0)
5411		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5412
5413	mtx_lock(&lun->lun_lock);
5414	if (lun->flags & CTL_LUN_RESERVED) {
5415		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5416		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5417		 || (ctsio->io_hdr.nexus.targ_target.id !=
5418		     lun->rsv_nexus.targ_target.id)) {
5419			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5420			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5421			goto bailout;
5422		}
5423	}
5424
5425	lun->flags |= CTL_LUN_RESERVED;
5426	lun->rsv_nexus = ctsio->io_hdr.nexus;
5427
5428	ctsio->scsi_status = SCSI_STATUS_OK;
5429	ctsio->io_hdr.status = CTL_SUCCESS;
5430
5431bailout:
5432	mtx_unlock(&lun->lun_lock);
5433
5434	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5435		free(ctsio->kern_data_ptr, M_CTL);
5436		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5437	}
5438
5439	ctl_done((union ctl_io *)ctsio);
5440	return (CTL_RETVAL_COMPLETE);
5441}
5442
5443int
5444ctl_start_stop(struct ctl_scsiio *ctsio)
5445{
5446	struct scsi_start_stop_unit *cdb;
5447	struct ctl_lun *lun;
5448	struct ctl_softc *ctl_softc;
5449	int retval;
5450
5451	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5452
5453	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5454	ctl_softc = control_softc;
5455	retval = 0;
5456
5457	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5458
5459	/*
5460	 * XXX KDM
5461	 * We don't support the immediate bit on a stop unit.  In order to
5462	 * do that, we would need to code up a way to know that a stop is
5463	 * pending, and hold off any new commands until it completes, one
5464	 * way or another.  Then we could accept or reject those commands
5465	 * depending on its status.  We would almost need to do the reverse
5466	 * of what we do below for an immediate start -- return the copy of
5467	 * the ctl_io to the FETD with status to send to the host (and to
5468	 * free the copy!) and then free the original I/O once the stop
5469	 * actually completes.  That way, the OOA queue mechanism can work
5470	 * to block commands that shouldn't proceed.  Another alternative
5471	 * would be to put the copy in the queue in place of the original,
5472	 * and return the original back to the caller.  That could be
5473	 * slightly safer..
5474	 */
5475	if ((cdb->byte2 & SSS_IMMED)
5476	 && ((cdb->how & SSS_START) == 0)) {
5477		ctl_set_invalid_field(ctsio,
5478				      /*sks_valid*/ 1,
5479				      /*command*/ 1,
5480				      /*field*/ 1,
5481				      /*bit_valid*/ 1,
5482				      /*bit*/ 0);
5483		ctl_done((union ctl_io *)ctsio);
5484		return (CTL_RETVAL_COMPLETE);
5485	}
5486
5487	if ((lun->flags & CTL_LUN_PR_RESERVED)
5488	 && ((cdb->how & SSS_START)==0)) {
5489		uint32_t residx;
5490
5491		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5492		if (!lun->per_res[residx].registered
5493		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5494
5495			ctl_set_reservation_conflict(ctsio);
5496			ctl_done((union ctl_io *)ctsio);
5497			return (CTL_RETVAL_COMPLETE);
5498		}
5499	}
5500
5501	/*
5502	 * If there is no backend on this device, we can't start or stop
5503	 * it.  In theory we shouldn't get any start/stop commands in the
5504	 * first place at this level if the LUN doesn't have a backend.
5505	 * That should get stopped by the command decode code.
5506	 */
5507	if (lun->backend == NULL) {
5508		ctl_set_invalid_opcode(ctsio);
5509		ctl_done((union ctl_io *)ctsio);
5510		return (CTL_RETVAL_COMPLETE);
5511	}
5512
5513	/*
5514	 * XXX KDM Copan-specific offline behavior.
5515	 * Figure out a reasonable way to port this?
5516	 */
5517#ifdef NEEDTOPORT
5518	mtx_lock(&lun->lun_lock);
5519
5520	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5521	 && (lun->flags & CTL_LUN_OFFLINE)) {
5522		/*
5523		 * If the LUN is offline, and the on/offline bit isn't set,
5524		 * reject the start or stop.  Otherwise, let it through.
5525		 */
5526		mtx_unlock(&lun->lun_lock);
5527		ctl_set_lun_not_ready(ctsio);
5528		ctl_done((union ctl_io *)ctsio);
5529	} else {
5530		mtx_unlock(&lun->lun_lock);
5531#endif /* NEEDTOPORT */
5532		/*
5533		 * This could be a start or a stop when we're online,
5534		 * or a stop/offline or start/online.  A start or stop when
5535		 * we're offline is covered in the case above.
5536		 */
5537		/*
5538		 * In the non-immediate case, we send the request to
5539		 * the backend and return status to the user when
5540		 * it is done.
5541		 *
5542		 * In the immediate case, we allocate a new ctl_io
5543		 * to hold a copy of the request, and send that to
5544		 * the backend.  We then set good status on the
5545		 * user's request and return it immediately.
5546		 */
5547		if (cdb->byte2 & SSS_IMMED) {
5548			union ctl_io *new_io;
5549
5550			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5551			if (new_io == NULL) {
5552				ctl_set_busy(ctsio);
5553				ctl_done((union ctl_io *)ctsio);
5554			} else {
5555				ctl_copy_io((union ctl_io *)ctsio,
5556					    new_io);
5557				retval = lun->backend->config_write(new_io);
5558				ctl_set_success(ctsio);
5559				ctl_done((union ctl_io *)ctsio);
5560			}
5561		} else {
5562			retval = lun->backend->config_write(
5563				(union ctl_io *)ctsio);
5564		}
5565#ifdef NEEDTOPORT
5566	}
5567#endif
5568	return (retval);
5569}
5570
5571/*
5572 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5573 * we don't really do anything with the LBA and length fields if the user
5574 * passes them in.  Instead we'll just flush out the cache for the entire
5575 * LUN.
5576 */
5577int
5578ctl_sync_cache(struct ctl_scsiio *ctsio)
5579{
5580	struct ctl_lun *lun;
5581	struct ctl_softc *ctl_softc;
5582	uint64_t starting_lba;
5583	uint32_t block_count;
5584	int retval;
5585
5586	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5587
5588	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5589	ctl_softc = control_softc;
5590	retval = 0;
5591
5592	switch (ctsio->cdb[0]) {
5593	case SYNCHRONIZE_CACHE: {
5594		struct scsi_sync_cache *cdb;
5595		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5596
5597		starting_lba = scsi_4btoul(cdb->begin_lba);
5598		block_count = scsi_2btoul(cdb->lb_count);
5599		break;
5600	}
5601	case SYNCHRONIZE_CACHE_16: {
5602		struct scsi_sync_cache_16 *cdb;
5603		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5604
5605		starting_lba = scsi_8btou64(cdb->begin_lba);
5606		block_count = scsi_4btoul(cdb->lb_count);
5607		break;
5608	}
5609	default:
5610		ctl_set_invalid_opcode(ctsio);
5611		ctl_done((union ctl_io *)ctsio);
5612		goto bailout;
5613		break; /* NOTREACHED */
5614	}
5615
5616	/*
5617	 * We check the LBA and length, but don't do anything with them.
5618	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5619	 * get flushed.  This check will just help satisfy anyone who wants
5620	 * to see an error for an out of range LBA.
5621	 */
5622	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5623		ctl_set_lba_out_of_range(ctsio);
5624		ctl_done((union ctl_io *)ctsio);
5625		goto bailout;
5626	}
5627
5628	/*
5629	 * If this LUN has no backend, we can't flush the cache anyway.
5630	 */
5631	if (lun->backend == NULL) {
5632		ctl_set_invalid_opcode(ctsio);
5633		ctl_done((union ctl_io *)ctsio);
5634		goto bailout;
5635	}
5636
5637	/*
5638	 * Check to see whether we're configured to send the SYNCHRONIZE
5639	 * CACHE command directly to the back end.
5640	 */
5641	mtx_lock(&lun->lun_lock);
5642	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5643	 && (++(lun->sync_count) >= lun->sync_interval)) {
5644		lun->sync_count = 0;
5645		mtx_unlock(&lun->lun_lock);
5646		retval = lun->backend->config_write((union ctl_io *)ctsio);
5647	} else {
5648		mtx_unlock(&lun->lun_lock);
5649		ctl_set_success(ctsio);
5650		ctl_done((union ctl_io *)ctsio);
5651	}
5652
5653bailout:
5654
5655	return (retval);
5656}
5657
5658int
5659ctl_format(struct ctl_scsiio *ctsio)
5660{
5661	struct scsi_format *cdb;
5662	struct ctl_lun *lun;
5663	struct ctl_softc *ctl_softc;
5664	int length, defect_list_len;
5665
5666	CTL_DEBUG_PRINT(("ctl_format\n"));
5667
5668	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5669	ctl_softc = control_softc;
5670
5671	cdb = (struct scsi_format *)ctsio->cdb;
5672
5673	length = 0;
5674	if (cdb->byte2 & SF_FMTDATA) {
5675		if (cdb->byte2 & SF_LONGLIST)
5676			length = sizeof(struct scsi_format_header_long);
5677		else
5678			length = sizeof(struct scsi_format_header_short);
5679	}
5680
5681	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5682	 && (length > 0)) {
5683		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5684		ctsio->kern_data_len = length;
5685		ctsio->kern_total_len = length;
5686		ctsio->kern_data_resid = 0;
5687		ctsio->kern_rel_offset = 0;
5688		ctsio->kern_sg_entries = 0;
5689		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5690		ctsio->be_move_done = ctl_config_move_done;
5691		ctl_datamove((union ctl_io *)ctsio);
5692
5693		return (CTL_RETVAL_COMPLETE);
5694	}
5695
5696	defect_list_len = 0;
5697
5698	if (cdb->byte2 & SF_FMTDATA) {
5699		if (cdb->byte2 & SF_LONGLIST) {
5700			struct scsi_format_header_long *header;
5701
5702			header = (struct scsi_format_header_long *)
5703				ctsio->kern_data_ptr;
5704
5705			defect_list_len = scsi_4btoul(header->defect_list_len);
5706			if (defect_list_len != 0) {
5707				ctl_set_invalid_field(ctsio,
5708						      /*sks_valid*/ 1,
5709						      /*command*/ 0,
5710						      /*field*/ 2,
5711						      /*bit_valid*/ 0,
5712						      /*bit*/ 0);
5713				goto bailout;
5714			}
5715		} else {
5716			struct scsi_format_header_short *header;
5717
5718			header = (struct scsi_format_header_short *)
5719				ctsio->kern_data_ptr;
5720
5721			defect_list_len = scsi_2btoul(header->defect_list_len);
5722			if (defect_list_len != 0) {
5723				ctl_set_invalid_field(ctsio,
5724						      /*sks_valid*/ 1,
5725						      /*command*/ 0,
5726						      /*field*/ 2,
5727						      /*bit_valid*/ 0,
5728						      /*bit*/ 0);
5729				goto bailout;
5730			}
5731		}
5732	}
5733
5734	/*
5735	 * The format command will clear out the "Medium format corrupted"
5736	 * status if set by the configuration code.  That status is really
5737	 * just a way to notify the host that we have lost the media, and
5738	 * get them to issue a command that will basically make them think
5739	 * they're blowing away the media.
5740	 */
5741	mtx_lock(&lun->lun_lock);
5742	lun->flags &= ~CTL_LUN_INOPERABLE;
5743	mtx_unlock(&lun->lun_lock);
5744
5745	ctsio->scsi_status = SCSI_STATUS_OK;
5746	ctsio->io_hdr.status = CTL_SUCCESS;
5747bailout:
5748
5749	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5750		free(ctsio->kern_data_ptr, M_CTL);
5751		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5752	}
5753
5754	ctl_done((union ctl_io *)ctsio);
5755	return (CTL_RETVAL_COMPLETE);
5756}
5757
5758int
5759ctl_read_buffer(struct ctl_scsiio *ctsio)
5760{
5761	struct scsi_read_buffer *cdb;
5762	struct ctl_lun *lun;
5763	int buffer_offset, len;
5764	static uint8_t descr[4];
5765	static uint8_t echo_descr[4] = { 0 };
5766
5767	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5768
5769	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5770	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5771
5772	if (lun->flags & CTL_LUN_PR_RESERVED) {
5773		uint32_t residx;
5774
5775		/*
5776		 * XXX KDM need a lock here.
5777		 */
5778		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5779		if ((lun->res_type == SPR_TYPE_EX_AC
5780		  && residx != lun->pr_res_idx)
5781		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5782		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5783		  && !lun->per_res[residx].registered)) {
5784			ctl_set_reservation_conflict(ctsio);
5785			ctl_done((union ctl_io *)ctsio);
5786			return (CTL_RETVAL_COMPLETE);
5787	        }
5788	}
5789
5790	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5791	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5792	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5793		ctl_set_invalid_field(ctsio,
5794				      /*sks_valid*/ 1,
5795				      /*command*/ 1,
5796				      /*field*/ 1,
5797				      /*bit_valid*/ 1,
5798				      /*bit*/ 4);
5799		ctl_done((union ctl_io *)ctsio);
5800		return (CTL_RETVAL_COMPLETE);
5801	}
5802
5803	len = scsi_3btoul(cdb->length);
5804	buffer_offset = scsi_3btoul(cdb->offset);
5805
5806	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5807		ctl_set_invalid_field(ctsio,
5808				      /*sks_valid*/ 1,
5809				      /*command*/ 1,
5810				      /*field*/ 6,
5811				      /*bit_valid*/ 0,
5812				      /*bit*/ 0);
5813		ctl_done((union ctl_io *)ctsio);
5814		return (CTL_RETVAL_COMPLETE);
5815	}
5816
5817	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5818		descr[0] = 0;
5819		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5820		ctsio->kern_data_ptr = descr;
5821		len = min(len, sizeof(descr));
5822	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5823		ctsio->kern_data_ptr = echo_descr;
5824		len = min(len, sizeof(echo_descr));
5825	} else
5826		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5827	ctsio->kern_data_len = len;
5828	ctsio->kern_total_len = len;
5829	ctsio->kern_data_resid = 0;
5830	ctsio->kern_rel_offset = 0;
5831	ctsio->kern_sg_entries = 0;
5832	ctsio->be_move_done = ctl_config_move_done;
5833	ctl_datamove((union ctl_io *)ctsio);
5834
5835	return (CTL_RETVAL_COMPLETE);
5836}
5837
5838int
5839ctl_write_buffer(struct ctl_scsiio *ctsio)
5840{
5841	struct scsi_write_buffer *cdb;
5842	struct ctl_lun *lun;
5843	int buffer_offset, len;
5844
5845	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5846
5847	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5848	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5849
5850	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5851		ctl_set_invalid_field(ctsio,
5852				      /*sks_valid*/ 1,
5853				      /*command*/ 1,
5854				      /*field*/ 1,
5855				      /*bit_valid*/ 1,
5856				      /*bit*/ 4);
5857		ctl_done((union ctl_io *)ctsio);
5858		return (CTL_RETVAL_COMPLETE);
5859	}
5860
5861	len = scsi_3btoul(cdb->length);
5862	buffer_offset = scsi_3btoul(cdb->offset);
5863
5864	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5865		ctl_set_invalid_field(ctsio,
5866				      /*sks_valid*/ 1,
5867				      /*command*/ 1,
5868				      /*field*/ 6,
5869				      /*bit_valid*/ 0,
5870				      /*bit*/ 0);
5871		ctl_done((union ctl_io *)ctsio);
5872		return (CTL_RETVAL_COMPLETE);
5873	}
5874
5875	/*
5876	 * If we've got a kernel request that hasn't been malloced yet,
5877	 * malloc it and tell the caller the data buffer is here.
5878	 */
5879	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5880		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5881		ctsio->kern_data_len = len;
5882		ctsio->kern_total_len = len;
5883		ctsio->kern_data_resid = 0;
5884		ctsio->kern_rel_offset = 0;
5885		ctsio->kern_sg_entries = 0;
5886		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5887		ctsio->be_move_done = ctl_config_move_done;
5888		ctl_datamove((union ctl_io *)ctsio);
5889
5890		return (CTL_RETVAL_COMPLETE);
5891	}
5892
5893	ctl_done((union ctl_io *)ctsio);
5894
5895	return (CTL_RETVAL_COMPLETE);
5896}
5897
5898int
5899ctl_write_same(struct ctl_scsiio *ctsio)
5900{
5901	struct ctl_lun *lun;
5902	struct ctl_lba_len_flags *lbalen;
5903	uint64_t lba;
5904	uint32_t num_blocks;
5905	int len, retval;
5906	uint8_t byte2;
5907
5908	retval = CTL_RETVAL_COMPLETE;
5909
5910	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5911
5912	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5913
5914	switch (ctsio->cdb[0]) {
5915	case WRITE_SAME_10: {
5916		struct scsi_write_same_10 *cdb;
5917
5918		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5919
5920		lba = scsi_4btoul(cdb->addr);
5921		num_blocks = scsi_2btoul(cdb->length);
5922		byte2 = cdb->byte2;
5923		break;
5924	}
5925	case WRITE_SAME_16: {
5926		struct scsi_write_same_16 *cdb;
5927
5928		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5929
5930		lba = scsi_8btou64(cdb->addr);
5931		num_blocks = scsi_4btoul(cdb->length);
5932		byte2 = cdb->byte2;
5933		break;
5934	}
5935	default:
5936		/*
5937		 * We got a command we don't support.  This shouldn't
5938		 * happen, commands should be filtered out above us.
5939		 */
5940		ctl_set_invalid_opcode(ctsio);
5941		ctl_done((union ctl_io *)ctsio);
5942
5943		return (CTL_RETVAL_COMPLETE);
5944		break; /* NOTREACHED */
5945	}
5946
5947	/*
5948	 * The first check is to make sure we're in bounds, the second
5949	 * check is to catch wrap-around problems.  If the lba + num blocks
5950	 * is less than the lba, then we've wrapped around and the block
5951	 * range is invalid anyway.
5952	 */
5953	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5954	 || ((lba + num_blocks) < lba)) {
5955		ctl_set_lba_out_of_range(ctsio);
5956		ctl_done((union ctl_io *)ctsio);
5957		return (CTL_RETVAL_COMPLETE);
5958	}
5959
5960	/* Zero number of blocks means "to the last logical block" */
5961	if (num_blocks == 0) {
5962		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5963			ctl_set_invalid_field(ctsio,
5964					      /*sks_valid*/ 0,
5965					      /*command*/ 1,
5966					      /*field*/ 0,
5967					      /*bit_valid*/ 0,
5968					      /*bit*/ 0);
5969			ctl_done((union ctl_io *)ctsio);
5970			return (CTL_RETVAL_COMPLETE);
5971		}
5972		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5973	}
5974
5975	len = lun->be_lun->blocksize;
5976
5977	/*
5978	 * If we've got a kernel request that hasn't been malloced yet,
5979	 * malloc it and tell the caller the data buffer is here.
5980	 */
5981	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5982		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5983		ctsio->kern_data_len = len;
5984		ctsio->kern_total_len = len;
5985		ctsio->kern_data_resid = 0;
5986		ctsio->kern_rel_offset = 0;
5987		ctsio->kern_sg_entries = 0;
5988		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5989		ctsio->be_move_done = ctl_config_move_done;
5990		ctl_datamove((union ctl_io *)ctsio);
5991
5992		return (CTL_RETVAL_COMPLETE);
5993	}
5994
5995	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5996	lbalen->lba = lba;
5997	lbalen->len = num_blocks;
5998	lbalen->flags = byte2;
5999	retval = lun->backend->config_write((union ctl_io *)ctsio);
6000
6001	return (retval);
6002}
6003
6004int
6005ctl_unmap(struct ctl_scsiio *ctsio)
6006{
6007	struct ctl_lun *lun;
6008	struct scsi_unmap *cdb;
6009	struct ctl_ptr_len_flags *ptrlen;
6010	struct scsi_unmap_header *hdr;
6011	struct scsi_unmap_desc *buf, *end;
6012	uint64_t lba;
6013	uint32_t num_blocks;
6014	int len, retval;
6015	uint8_t byte2;
6016
6017	retval = CTL_RETVAL_COMPLETE;
6018
6019	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6020
6021	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6022	cdb = (struct scsi_unmap *)ctsio->cdb;
6023
6024	len = scsi_2btoul(cdb->length);
6025	byte2 = cdb->byte2;
6026
6027	/*
6028	 * If we've got a kernel request that hasn't been malloced yet,
6029	 * malloc it and tell the caller the data buffer is here.
6030	 */
6031	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6032		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6033		ctsio->kern_data_len = len;
6034		ctsio->kern_total_len = len;
6035		ctsio->kern_data_resid = 0;
6036		ctsio->kern_rel_offset = 0;
6037		ctsio->kern_sg_entries = 0;
6038		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6039		ctsio->be_move_done = ctl_config_move_done;
6040		ctl_datamove((union ctl_io *)ctsio);
6041
6042		return (CTL_RETVAL_COMPLETE);
6043	}
6044
6045	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6046	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6047	if (len < sizeof (*hdr) ||
6048	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6049	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6050	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6051		ctl_set_invalid_field(ctsio,
6052				      /*sks_valid*/ 0,
6053				      /*command*/ 0,
6054				      /*field*/ 0,
6055				      /*bit_valid*/ 0,
6056				      /*bit*/ 0);
6057		ctl_done((union ctl_io *)ctsio);
6058		return (CTL_RETVAL_COMPLETE);
6059	}
6060	len = scsi_2btoul(hdr->desc_length);
6061	buf = (struct scsi_unmap_desc *)(hdr + 1);
6062	end = buf + len / sizeof(*buf);
6063
6064	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6065	ptrlen->ptr = (void *)buf;
6066	ptrlen->len = len;
6067	ptrlen->flags = byte2;
6068
6069	for (; buf < end; buf++) {
6070		lba = scsi_8btou64(buf->lba);
6071		num_blocks = scsi_4btoul(buf->length);
6072		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6073		 || ((lba + num_blocks) < lba)) {
6074			ctl_set_lba_out_of_range(ctsio);
6075			ctl_done((union ctl_io *)ctsio);
6076			return (CTL_RETVAL_COMPLETE);
6077		}
6078	}
6079
6080	retval = lun->backend->config_write((union ctl_io *)ctsio);
6081
6082	return (retval);
6083}
6084
6085/*
6086 * Note that this function currently doesn't actually do anything inside
6087 * CTL to enforce things if the DQue bit is turned on.
6088 *
6089 * Also note that this function can't be used in the default case, because
6090 * the DQue bit isn't set in the changeable mask for the control mode page
6091 * anyway.  This is just here as an example for how to implement a page
6092 * handler, and a placeholder in case we want to allow the user to turn
6093 * tagged queueing on and off.
6094 *
6095 * The D_SENSE bit handling is functional, however, and will turn
6096 * descriptor sense on and off for a given LUN.
6097 */
6098int
6099ctl_control_page_handler(struct ctl_scsiio *ctsio,
6100			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6101{
6102	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6103	struct ctl_lun *lun;
6104	struct ctl_softc *softc;
6105	int set_ua;
6106	uint32_t initidx;
6107
6108	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6109	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6110	set_ua = 0;
6111
6112	user_cp = (struct scsi_control_page *)page_ptr;
6113	current_cp = (struct scsi_control_page *)
6114		(page_index->page_data + (page_index->page_len *
6115		CTL_PAGE_CURRENT));
6116	saved_cp = (struct scsi_control_page *)
6117		(page_index->page_data + (page_index->page_len *
6118		CTL_PAGE_SAVED));
6119
6120	softc = control_softc;
6121
6122	mtx_lock(&lun->lun_lock);
6123	if (((current_cp->rlec & SCP_DSENSE) == 0)
6124	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6125		/*
6126		 * Descriptor sense is currently turned off and the user
6127		 * wants to turn it on.
6128		 */
6129		current_cp->rlec |= SCP_DSENSE;
6130		saved_cp->rlec |= SCP_DSENSE;
6131		lun->flags |= CTL_LUN_SENSE_DESC;
6132		set_ua = 1;
6133	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6134		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6135		/*
6136		 * Descriptor sense is currently turned on, and the user
6137		 * wants to turn it off.
6138		 */
6139		current_cp->rlec &= ~SCP_DSENSE;
6140		saved_cp->rlec &= ~SCP_DSENSE;
6141		lun->flags &= ~CTL_LUN_SENSE_DESC;
6142		set_ua = 1;
6143	}
6144	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6145		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6146#ifdef NEEDTOPORT
6147			csevent_log(CSC_CTL | CSC_SHELF_SW |
6148				    CTL_UNTAG_TO_UNTAG,
6149				    csevent_LogType_Trace,
6150				    csevent_Severity_Information,
6151				    csevent_AlertLevel_Green,
6152				    csevent_FRU_Firmware,
6153				    csevent_FRU_Unknown,
6154				    "Received untagged to untagged transition");
6155#endif /* NEEDTOPORT */
6156		} else {
6157#ifdef NEEDTOPORT
6158			csevent_log(CSC_CTL | CSC_SHELF_SW |
6159				    CTL_UNTAG_TO_TAG,
6160				    csevent_LogType_ConfigChange,
6161				    csevent_Severity_Information,
6162				    csevent_AlertLevel_Green,
6163				    csevent_FRU_Firmware,
6164				    csevent_FRU_Unknown,
6165				    "Received untagged to tagged "
6166				    "queueing transition");
6167#endif /* NEEDTOPORT */
6168
6169			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6170			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6171			set_ua = 1;
6172		}
6173	} else {
6174		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6175#ifdef NEEDTOPORT
6176			csevent_log(CSC_CTL | CSC_SHELF_SW |
6177				    CTL_TAG_TO_UNTAG,
6178				    csevent_LogType_ConfigChange,
6179				    csevent_Severity_Warning,
6180				    csevent_AlertLevel_Yellow,
6181				    csevent_FRU_Firmware,
6182				    csevent_FRU_Unknown,
6183				    "Received tagged queueing to untagged "
6184				    "transition");
6185#endif /* NEEDTOPORT */
6186
6187			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6188			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6189			set_ua = 1;
6190		} else {
6191#ifdef NEEDTOPORT
6192			csevent_log(CSC_CTL | CSC_SHELF_SW |
6193				    CTL_TAG_TO_TAG,
6194				    csevent_LogType_Trace,
6195				    csevent_Severity_Information,
6196				    csevent_AlertLevel_Green,
6197				    csevent_FRU_Firmware,
6198				    csevent_FRU_Unknown,
6199				    "Received tagged queueing to tagged "
6200				    "queueing transition");
6201#endif /* NEEDTOPORT */
6202		}
6203	}
6204	if (set_ua != 0) {
6205		int i;
6206		/*
6207		 * Let other initiators know that the mode
6208		 * parameters for this LUN have changed.
6209		 */
6210		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6211			if (i == initidx)
6212				continue;
6213
6214			lun->pending_sense[i].ua_pending |=
6215				CTL_UA_MODE_CHANGE;
6216		}
6217	}
6218	mtx_unlock(&lun->lun_lock);
6219
6220	return (0);
6221}
6222
6223int
6224ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6225		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6226{
6227	return (0);
6228}
6229
6230int
6231ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6232			   struct ctl_page_index *page_index, int pc)
6233{
6234	struct copan_power_subpage *page;
6235
6236	page = (struct copan_power_subpage *)page_index->page_data +
6237		(page_index->page_len * pc);
6238
6239	switch (pc) {
6240	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6241		/*
6242		 * We don't update the changable bits for this page.
6243		 */
6244		break;
6245	case SMS_PAGE_CTRL_CURRENT >> 6:
6246	case SMS_PAGE_CTRL_DEFAULT >> 6:
6247	case SMS_PAGE_CTRL_SAVED >> 6:
6248#ifdef NEEDTOPORT
6249		ctl_update_power_subpage(page);
6250#endif
6251		break;
6252	default:
6253#ifdef NEEDTOPORT
6254		EPRINT(0, "Invalid PC %d!!", pc);
6255#endif
6256		break;
6257	}
6258	return (0);
6259}
6260
6261
6262int
6263ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6264		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6265{
6266	struct copan_aps_subpage *user_sp;
6267	struct copan_aps_subpage *current_sp;
6268	union ctl_modepage_info *modepage_info;
6269	struct ctl_softc *softc;
6270	struct ctl_lun *lun;
6271	int retval;
6272
6273	retval = CTL_RETVAL_COMPLETE;
6274	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6275		     (page_index->page_len * CTL_PAGE_CURRENT));
6276	softc = control_softc;
6277	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6278
6279	user_sp = (struct copan_aps_subpage *)page_ptr;
6280
6281	modepage_info = (union ctl_modepage_info *)
6282		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6283
6284	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6285	modepage_info->header.subpage = page_index->subpage;
6286	modepage_info->aps.lock_active = user_sp->lock_active;
6287
6288	mtx_lock(&softc->ctl_lock);
6289
6290	/*
6291	 * If there is a request to lock the LUN and another LUN is locked
6292	 * this is an error. If the requested LUN is already locked ignore
6293	 * the request. If no LUN is locked attempt to lock it.
6294	 * if there is a request to unlock the LUN and the LUN is currently
6295	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6296	 * if another LUN is locked or no LUN is locked.
6297	 */
6298	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6299		if (softc->aps_locked_lun == lun->lun) {
6300			/*
6301			 * This LUN is already locked, so we're done.
6302			 */
6303			retval = CTL_RETVAL_COMPLETE;
6304		} else if (softc->aps_locked_lun == 0) {
6305			/*
6306			 * No one has the lock, pass the request to the
6307			 * backend.
6308			 */
6309			retval = lun->backend->config_write(
6310				(union ctl_io *)ctsio);
6311		} else {
6312			/*
6313			 * Someone else has the lock, throw out the request.
6314			 */
6315			ctl_set_already_locked(ctsio);
6316			free(ctsio->kern_data_ptr, M_CTL);
6317			ctl_done((union ctl_io *)ctsio);
6318
6319			/*
6320			 * Set the return value so that ctl_do_mode_select()
6321			 * won't try to complete the command.  We already
6322			 * completed it here.
6323			 */
6324			retval = CTL_RETVAL_ERROR;
6325		}
6326	} else if (softc->aps_locked_lun == lun->lun) {
6327		/*
6328		 * This LUN is locked, so pass the unlock request to the
6329		 * backend.
6330		 */
6331		retval = lun->backend->config_write((union ctl_io *)ctsio);
6332	}
6333	mtx_unlock(&softc->ctl_lock);
6334
6335	return (retval);
6336}
6337
6338int
6339ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6340				struct ctl_page_index *page_index,
6341				uint8_t *page_ptr)
6342{
6343	uint8_t *c;
6344	int i;
6345
6346	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6347	ctl_time_io_secs =
6348		(c[0] << 8) |
6349		(c[1] << 0) |
6350		0;
6351	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6352	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6353	printf("page data:");
6354	for (i=0; i<8; i++)
6355		printf(" %.2x",page_ptr[i]);
6356	printf("\n");
6357	return (0);
6358}
6359
6360int
6361ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6362			       struct ctl_page_index *page_index,
6363			       int pc)
6364{
6365	struct copan_debugconf_subpage *page;
6366
6367	page = (struct copan_debugconf_subpage *)page_index->page_data +
6368		(page_index->page_len * pc);
6369
6370	switch (pc) {
6371	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6372	case SMS_PAGE_CTRL_DEFAULT >> 6:
6373	case SMS_PAGE_CTRL_SAVED >> 6:
6374		/*
6375		 * We don't update the changable or default bits for this page.
6376		 */
6377		break;
6378	case SMS_PAGE_CTRL_CURRENT >> 6:
6379		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6380		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6381		break;
6382	default:
6383#ifdef NEEDTOPORT
6384		EPRINT(0, "Invalid PC %d!!", pc);
6385#endif /* NEEDTOPORT */
6386		break;
6387	}
6388	return (0);
6389}
6390
6391
6392static int
6393ctl_do_mode_select(union ctl_io *io)
6394{
6395	struct scsi_mode_page_header *page_header;
6396	struct ctl_page_index *page_index;
6397	struct ctl_scsiio *ctsio;
6398	int control_dev, page_len;
6399	int page_len_offset, page_len_size;
6400	union ctl_modepage_info *modepage_info;
6401	struct ctl_lun *lun;
6402	int *len_left, *len_used;
6403	int retval, i;
6404
6405	ctsio = &io->scsiio;
6406	page_index = NULL;
6407	page_len = 0;
6408	retval = CTL_RETVAL_COMPLETE;
6409
6410	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6411
6412	if (lun->be_lun->lun_type != T_DIRECT)
6413		control_dev = 1;
6414	else
6415		control_dev = 0;
6416
6417	modepage_info = (union ctl_modepage_info *)
6418		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6419	len_left = &modepage_info->header.len_left;
6420	len_used = &modepage_info->header.len_used;
6421
6422do_next_page:
6423
6424	page_header = (struct scsi_mode_page_header *)
6425		(ctsio->kern_data_ptr + *len_used);
6426
6427	if (*len_left == 0) {
6428		free(ctsio->kern_data_ptr, M_CTL);
6429		ctl_set_success(ctsio);
6430		ctl_done((union ctl_io *)ctsio);
6431		return (CTL_RETVAL_COMPLETE);
6432	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6433
6434		free(ctsio->kern_data_ptr, M_CTL);
6435		ctl_set_param_len_error(ctsio);
6436		ctl_done((union ctl_io *)ctsio);
6437		return (CTL_RETVAL_COMPLETE);
6438
6439	} else if ((page_header->page_code & SMPH_SPF)
6440		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6441
6442		free(ctsio->kern_data_ptr, M_CTL);
6443		ctl_set_param_len_error(ctsio);
6444		ctl_done((union ctl_io *)ctsio);
6445		return (CTL_RETVAL_COMPLETE);
6446	}
6447
6448
6449	/*
6450	 * XXX KDM should we do something with the block descriptor?
6451	 */
6452	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6453
6454		if ((control_dev != 0)
6455		 && (lun->mode_pages.index[i].page_flags &
6456		     CTL_PAGE_FLAG_DISK_ONLY))
6457			continue;
6458
6459		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6460		    (page_header->page_code & SMPH_PC_MASK))
6461			continue;
6462
6463		/*
6464		 * If neither page has a subpage code, then we've got a
6465		 * match.
6466		 */
6467		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6468		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6469			page_index = &lun->mode_pages.index[i];
6470			page_len = page_header->page_length;
6471			break;
6472		}
6473
6474		/*
6475		 * If both pages have subpages, then the subpage numbers
6476		 * have to match.
6477		 */
6478		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6479		  && (page_header->page_code & SMPH_SPF)) {
6480			struct scsi_mode_page_header_sp *sph;
6481
6482			sph = (struct scsi_mode_page_header_sp *)page_header;
6483
6484			if (lun->mode_pages.index[i].subpage ==
6485			    sph->subpage) {
6486				page_index = &lun->mode_pages.index[i];
6487				page_len = scsi_2btoul(sph->page_length);
6488				break;
6489			}
6490		}
6491	}
6492
6493	/*
6494	 * If we couldn't find the page, or if we don't have a mode select
6495	 * handler for it, send back an error to the user.
6496	 */
6497	if ((page_index == NULL)
6498	 || (page_index->select_handler == NULL)) {
6499		ctl_set_invalid_field(ctsio,
6500				      /*sks_valid*/ 1,
6501				      /*command*/ 0,
6502				      /*field*/ *len_used,
6503				      /*bit_valid*/ 0,
6504				      /*bit*/ 0);
6505		free(ctsio->kern_data_ptr, M_CTL);
6506		ctl_done((union ctl_io *)ctsio);
6507		return (CTL_RETVAL_COMPLETE);
6508	}
6509
6510	if (page_index->page_code & SMPH_SPF) {
6511		page_len_offset = 2;
6512		page_len_size = 2;
6513	} else {
6514		page_len_size = 1;
6515		page_len_offset = 1;
6516	}
6517
6518	/*
6519	 * If the length the initiator gives us isn't the one we specify in
6520	 * the mode page header, or if they didn't specify enough data in
6521	 * the CDB to avoid truncating this page, kick out the request.
6522	 */
6523	if ((page_len != (page_index->page_len - page_len_offset -
6524			  page_len_size))
6525	 || (*len_left < page_index->page_len)) {
6526
6527
6528		ctl_set_invalid_field(ctsio,
6529				      /*sks_valid*/ 1,
6530				      /*command*/ 0,
6531				      /*field*/ *len_used + page_len_offset,
6532				      /*bit_valid*/ 0,
6533				      /*bit*/ 0);
6534		free(ctsio->kern_data_ptr, M_CTL);
6535		ctl_done((union ctl_io *)ctsio);
6536		return (CTL_RETVAL_COMPLETE);
6537	}
6538
6539	/*
6540	 * Run through the mode page, checking to make sure that the bits
6541	 * the user changed are actually legal for him to change.
6542	 */
6543	for (i = 0; i < page_index->page_len; i++) {
6544		uint8_t *user_byte, *change_mask, *current_byte;
6545		int bad_bit;
6546		int j;
6547
6548		user_byte = (uint8_t *)page_header + i;
6549		change_mask = page_index->page_data +
6550			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6551		current_byte = page_index->page_data +
6552			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6553
6554		/*
6555		 * Check to see whether the user set any bits in this byte
6556		 * that he is not allowed to set.
6557		 */
6558		if ((*user_byte & ~(*change_mask)) ==
6559		    (*current_byte & ~(*change_mask)))
6560			continue;
6561
6562		/*
6563		 * Go through bit by bit to determine which one is illegal.
6564		 */
6565		bad_bit = 0;
6566		for (j = 7; j >= 0; j--) {
6567			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6568			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6569				bad_bit = i;
6570				break;
6571			}
6572		}
6573		ctl_set_invalid_field(ctsio,
6574				      /*sks_valid*/ 1,
6575				      /*command*/ 0,
6576				      /*field*/ *len_used + i,
6577				      /*bit_valid*/ 1,
6578				      /*bit*/ bad_bit);
6579		free(ctsio->kern_data_ptr, M_CTL);
6580		ctl_done((union ctl_io *)ctsio);
6581		return (CTL_RETVAL_COMPLETE);
6582	}
6583
6584	/*
6585	 * Decrement these before we call the page handler, since we may
6586	 * end up getting called back one way or another before the handler
6587	 * returns to this context.
6588	 */
6589	*len_left -= page_index->page_len;
6590	*len_used += page_index->page_len;
6591
6592	retval = page_index->select_handler(ctsio, page_index,
6593					    (uint8_t *)page_header);
6594
6595	/*
6596	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6597	 * wait until this queued command completes to finish processing
6598	 * the mode page.  If it returns anything other than
6599	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6600	 * already set the sense information, freed the data pointer, and
6601	 * completed the io for us.
6602	 */
6603	if (retval != CTL_RETVAL_COMPLETE)
6604		goto bailout_no_done;
6605
6606	/*
6607	 * If the initiator sent us more than one page, parse the next one.
6608	 */
6609	if (*len_left > 0)
6610		goto do_next_page;
6611
6612	ctl_set_success(ctsio);
6613	free(ctsio->kern_data_ptr, M_CTL);
6614	ctl_done((union ctl_io *)ctsio);
6615
6616bailout_no_done:
6617
6618	return (CTL_RETVAL_COMPLETE);
6619
6620}
6621
6622int
6623ctl_mode_select(struct ctl_scsiio *ctsio)
6624{
6625	int param_len, pf, sp;
6626	int header_size, bd_len;
6627	int len_left, len_used;
6628	struct ctl_page_index *page_index;
6629	struct ctl_lun *lun;
6630	int control_dev, page_len;
6631	union ctl_modepage_info *modepage_info;
6632	int retval;
6633
6634	pf = 0;
6635	sp = 0;
6636	page_len = 0;
6637	len_used = 0;
6638	len_left = 0;
6639	retval = 0;
6640	bd_len = 0;
6641	page_index = NULL;
6642
6643	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6644
6645	if (lun->be_lun->lun_type != T_DIRECT)
6646		control_dev = 1;
6647	else
6648		control_dev = 0;
6649
6650	switch (ctsio->cdb[0]) {
6651	case MODE_SELECT_6: {
6652		struct scsi_mode_select_6 *cdb;
6653
6654		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6655
6656		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6657		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6658
6659		param_len = cdb->length;
6660		header_size = sizeof(struct scsi_mode_header_6);
6661		break;
6662	}
6663	case MODE_SELECT_10: {
6664		struct scsi_mode_select_10 *cdb;
6665
6666		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6667
6668		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6669		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6670
6671		param_len = scsi_2btoul(cdb->length);
6672		header_size = sizeof(struct scsi_mode_header_10);
6673		break;
6674	}
6675	default:
6676		ctl_set_invalid_opcode(ctsio);
6677		ctl_done((union ctl_io *)ctsio);
6678		return (CTL_RETVAL_COMPLETE);
6679		break; /* NOTREACHED */
6680	}
6681
6682	/*
6683	 * From SPC-3:
6684	 * "A parameter list length of zero indicates that the Data-Out Buffer
6685	 * shall be empty. This condition shall not be considered as an error."
6686	 */
6687	if (param_len == 0) {
6688		ctl_set_success(ctsio);
6689		ctl_done((union ctl_io *)ctsio);
6690		return (CTL_RETVAL_COMPLETE);
6691	}
6692
6693	/*
6694	 * Since we'll hit this the first time through, prior to
6695	 * allocation, we don't need to free a data buffer here.
6696	 */
6697	if (param_len < header_size) {
6698		ctl_set_param_len_error(ctsio);
6699		ctl_done((union ctl_io *)ctsio);
6700		return (CTL_RETVAL_COMPLETE);
6701	}
6702
6703	/*
6704	 * Allocate the data buffer and grab the user's data.  In theory,
6705	 * we shouldn't have to sanity check the parameter list length here
6706	 * because the maximum size is 64K.  We should be able to malloc
6707	 * that much without too many problems.
6708	 */
6709	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6710		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6711		ctsio->kern_data_len = param_len;
6712		ctsio->kern_total_len = param_len;
6713		ctsio->kern_data_resid = 0;
6714		ctsio->kern_rel_offset = 0;
6715		ctsio->kern_sg_entries = 0;
6716		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6717		ctsio->be_move_done = ctl_config_move_done;
6718		ctl_datamove((union ctl_io *)ctsio);
6719
6720		return (CTL_RETVAL_COMPLETE);
6721	}
6722
6723	switch (ctsio->cdb[0]) {
6724	case MODE_SELECT_6: {
6725		struct scsi_mode_header_6 *mh6;
6726
6727		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6728		bd_len = mh6->blk_desc_len;
6729		break;
6730	}
6731	case MODE_SELECT_10: {
6732		struct scsi_mode_header_10 *mh10;
6733
6734		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6735		bd_len = scsi_2btoul(mh10->blk_desc_len);
6736		break;
6737	}
6738	default:
6739		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6740		break;
6741	}
6742
6743	if (param_len < (header_size + bd_len)) {
6744		free(ctsio->kern_data_ptr, M_CTL);
6745		ctl_set_param_len_error(ctsio);
6746		ctl_done((union ctl_io *)ctsio);
6747		return (CTL_RETVAL_COMPLETE);
6748	}
6749
6750	/*
6751	 * Set the IO_CONT flag, so that if this I/O gets passed to
6752	 * ctl_config_write_done(), it'll get passed back to
6753	 * ctl_do_mode_select() for further processing, or completion if
6754	 * we're all done.
6755	 */
6756	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6757	ctsio->io_cont = ctl_do_mode_select;
6758
6759	modepage_info = (union ctl_modepage_info *)
6760		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6761
6762	memset(modepage_info, 0, sizeof(*modepage_info));
6763
6764	len_left = param_len - header_size - bd_len;
6765	len_used = header_size + bd_len;
6766
6767	modepage_info->header.len_left = len_left;
6768	modepage_info->header.len_used = len_used;
6769
6770	return (ctl_do_mode_select((union ctl_io *)ctsio));
6771}
6772
6773int
6774ctl_mode_sense(struct ctl_scsiio *ctsio)
6775{
6776	struct ctl_lun *lun;
6777	int pc, page_code, dbd, llba, subpage;
6778	int alloc_len, page_len, header_len, total_len;
6779	struct scsi_mode_block_descr *block_desc;
6780	struct ctl_page_index *page_index;
6781	int control_dev;
6782
6783	dbd = 0;
6784	llba = 0;
6785	block_desc = NULL;
6786	page_index = NULL;
6787
6788	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6789
6790	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6791
6792	if (lun->be_lun->lun_type != T_DIRECT)
6793		control_dev = 1;
6794	else
6795		control_dev = 0;
6796
6797	if (lun->flags & CTL_LUN_PR_RESERVED) {
6798		uint32_t residx;
6799
6800		/*
6801		 * XXX KDM need a lock here.
6802		 */
6803		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6804		if ((lun->res_type == SPR_TYPE_EX_AC
6805		  && residx != lun->pr_res_idx)
6806		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6807		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6808		  && !lun->per_res[residx].registered)) {
6809			ctl_set_reservation_conflict(ctsio);
6810			ctl_done((union ctl_io *)ctsio);
6811			return (CTL_RETVAL_COMPLETE);
6812		}
6813	}
6814
6815	switch (ctsio->cdb[0]) {
6816	case MODE_SENSE_6: {
6817		struct scsi_mode_sense_6 *cdb;
6818
6819		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6820
6821		header_len = sizeof(struct scsi_mode_hdr_6);
6822		if (cdb->byte2 & SMS_DBD)
6823			dbd = 1;
6824		else
6825			header_len += sizeof(struct scsi_mode_block_descr);
6826
6827		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6828		page_code = cdb->page & SMS_PAGE_CODE;
6829		subpage = cdb->subpage;
6830		alloc_len = cdb->length;
6831		break;
6832	}
6833	case MODE_SENSE_10: {
6834		struct scsi_mode_sense_10 *cdb;
6835
6836		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6837
6838		header_len = sizeof(struct scsi_mode_hdr_10);
6839
6840		if (cdb->byte2 & SMS_DBD)
6841			dbd = 1;
6842		else
6843			header_len += sizeof(struct scsi_mode_block_descr);
6844		if (cdb->byte2 & SMS10_LLBAA)
6845			llba = 1;
6846		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6847		page_code = cdb->page & SMS_PAGE_CODE;
6848		subpage = cdb->subpage;
6849		alloc_len = scsi_2btoul(cdb->length);
6850		break;
6851	}
6852	default:
6853		ctl_set_invalid_opcode(ctsio);
6854		ctl_done((union ctl_io *)ctsio);
6855		return (CTL_RETVAL_COMPLETE);
6856		break; /* NOTREACHED */
6857	}
6858
6859	/*
6860	 * We have to make a first pass through to calculate the size of
6861	 * the pages that match the user's query.  Then we allocate enough
6862	 * memory to hold it, and actually copy the data into the buffer.
6863	 */
6864	switch (page_code) {
6865	case SMS_ALL_PAGES_PAGE: {
6866		int i;
6867
6868		page_len = 0;
6869
6870		/*
6871		 * At the moment, values other than 0 and 0xff here are
6872		 * reserved according to SPC-3.
6873		 */
6874		if ((subpage != SMS_SUBPAGE_PAGE_0)
6875		 && (subpage != SMS_SUBPAGE_ALL)) {
6876			ctl_set_invalid_field(ctsio,
6877					      /*sks_valid*/ 1,
6878					      /*command*/ 1,
6879					      /*field*/ 3,
6880					      /*bit_valid*/ 0,
6881					      /*bit*/ 0);
6882			ctl_done((union ctl_io *)ctsio);
6883			return (CTL_RETVAL_COMPLETE);
6884		}
6885
6886		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6887			if ((control_dev != 0)
6888			 && (lun->mode_pages.index[i].page_flags &
6889			     CTL_PAGE_FLAG_DISK_ONLY))
6890				continue;
6891
6892			/*
6893			 * We don't use this subpage if the user didn't
6894			 * request all subpages.
6895			 */
6896			if ((lun->mode_pages.index[i].subpage != 0)
6897			 && (subpage == SMS_SUBPAGE_PAGE_0))
6898				continue;
6899
6900#if 0
6901			printf("found page %#x len %d\n",
6902			       lun->mode_pages.index[i].page_code &
6903			       SMPH_PC_MASK,
6904			       lun->mode_pages.index[i].page_len);
6905#endif
6906			page_len += lun->mode_pages.index[i].page_len;
6907		}
6908		break;
6909	}
6910	default: {
6911		int i;
6912
6913		page_len = 0;
6914
6915		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6916			/* Look for the right page code */
6917			if ((lun->mode_pages.index[i].page_code &
6918			     SMPH_PC_MASK) != page_code)
6919				continue;
6920
6921			/* Look for the right subpage or the subpage wildcard*/
6922			if ((lun->mode_pages.index[i].subpage != subpage)
6923			 && (subpage != SMS_SUBPAGE_ALL))
6924				continue;
6925
6926			/* Make sure the page is supported for this dev type */
6927			if ((control_dev != 0)
6928			 && (lun->mode_pages.index[i].page_flags &
6929			     CTL_PAGE_FLAG_DISK_ONLY))
6930				continue;
6931
6932#if 0
6933			printf("found page %#x len %d\n",
6934			       lun->mode_pages.index[i].page_code &
6935			       SMPH_PC_MASK,
6936			       lun->mode_pages.index[i].page_len);
6937#endif
6938
6939			page_len += lun->mode_pages.index[i].page_len;
6940		}
6941
6942		if (page_len == 0) {
6943			ctl_set_invalid_field(ctsio,
6944					      /*sks_valid*/ 1,
6945					      /*command*/ 1,
6946					      /*field*/ 2,
6947					      /*bit_valid*/ 1,
6948					      /*bit*/ 5);
6949			ctl_done((union ctl_io *)ctsio);
6950			return (CTL_RETVAL_COMPLETE);
6951		}
6952		break;
6953	}
6954	}
6955
6956	total_len = header_len + page_len;
6957#if 0
6958	printf("header_len = %d, page_len = %d, total_len = %d\n",
6959	       header_len, page_len, total_len);
6960#endif
6961
6962	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6963	ctsio->kern_sg_entries = 0;
6964	ctsio->kern_data_resid = 0;
6965	ctsio->kern_rel_offset = 0;
6966	if (total_len < alloc_len) {
6967		ctsio->residual = alloc_len - total_len;
6968		ctsio->kern_data_len = total_len;
6969		ctsio->kern_total_len = total_len;
6970	} else {
6971		ctsio->residual = 0;
6972		ctsio->kern_data_len = alloc_len;
6973		ctsio->kern_total_len = alloc_len;
6974	}
6975
6976	switch (ctsio->cdb[0]) {
6977	case MODE_SENSE_6: {
6978		struct scsi_mode_hdr_6 *header;
6979
6980		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6981
6982		header->datalen = ctl_min(total_len - 1, 254);
6983
6984		if (dbd)
6985			header->block_descr_len = 0;
6986		else
6987			header->block_descr_len =
6988				sizeof(struct scsi_mode_block_descr);
6989		block_desc = (struct scsi_mode_block_descr *)&header[1];
6990		break;
6991	}
6992	case MODE_SENSE_10: {
6993		struct scsi_mode_hdr_10 *header;
6994		int datalen;
6995
6996		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6997
6998		datalen = ctl_min(total_len - 2, 65533);
6999		scsi_ulto2b(datalen, header->datalen);
7000		if (dbd)
7001			scsi_ulto2b(0, header->block_descr_len);
7002		else
7003			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7004				    header->block_descr_len);
7005		block_desc = (struct scsi_mode_block_descr *)&header[1];
7006		break;
7007	}
7008	default:
7009		panic("invalid CDB type %#x", ctsio->cdb[0]);
7010		break; /* NOTREACHED */
7011	}
7012
7013	/*
7014	 * If we've got a disk, use its blocksize in the block
7015	 * descriptor.  Otherwise, just set it to 0.
7016	 */
7017	if (dbd == 0) {
7018		if (control_dev != 0)
7019			scsi_ulto3b(lun->be_lun->blocksize,
7020				    block_desc->block_len);
7021		else
7022			scsi_ulto3b(0, block_desc->block_len);
7023	}
7024
7025	switch (page_code) {
7026	case SMS_ALL_PAGES_PAGE: {
7027		int i, data_used;
7028
7029		data_used = header_len;
7030		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7031			struct ctl_page_index *page_index;
7032
7033			page_index = &lun->mode_pages.index[i];
7034
7035			if ((control_dev != 0)
7036			 && (page_index->page_flags &
7037			    CTL_PAGE_FLAG_DISK_ONLY))
7038				continue;
7039
7040			/*
7041			 * We don't use this subpage if the user didn't
7042			 * request all subpages.  We already checked (above)
7043			 * to make sure the user only specified a subpage
7044			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7045			 */
7046			if ((page_index->subpage != 0)
7047			 && (subpage == SMS_SUBPAGE_PAGE_0))
7048				continue;
7049
7050			/*
7051			 * Call the handler, if it exists, to update the
7052			 * page to the latest values.
7053			 */
7054			if (page_index->sense_handler != NULL)
7055				page_index->sense_handler(ctsio, page_index,pc);
7056
7057			memcpy(ctsio->kern_data_ptr + data_used,
7058			       page_index->page_data +
7059			       (page_index->page_len * pc),
7060			       page_index->page_len);
7061			data_used += page_index->page_len;
7062		}
7063		break;
7064	}
7065	default: {
7066		int i, data_used;
7067
7068		data_used = header_len;
7069
7070		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7071			struct ctl_page_index *page_index;
7072
7073			page_index = &lun->mode_pages.index[i];
7074
7075			/* Look for the right page code */
7076			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7077				continue;
7078
7079			/* Look for the right subpage or the subpage wildcard*/
7080			if ((page_index->subpage != subpage)
7081			 && (subpage != SMS_SUBPAGE_ALL))
7082				continue;
7083
7084			/* Make sure the page is supported for this dev type */
7085			if ((control_dev != 0)
7086			 && (page_index->page_flags &
7087			     CTL_PAGE_FLAG_DISK_ONLY))
7088				continue;
7089
7090			/*
7091			 * Call the handler, if it exists, to update the
7092			 * page to the latest values.
7093			 */
7094			if (page_index->sense_handler != NULL)
7095				page_index->sense_handler(ctsio, page_index,pc);
7096
7097			memcpy(ctsio->kern_data_ptr + data_used,
7098			       page_index->page_data +
7099			       (page_index->page_len * pc),
7100			       page_index->page_len);
7101			data_used += page_index->page_len;
7102		}
7103		break;
7104	}
7105	}
7106
7107	ctsio->scsi_status = SCSI_STATUS_OK;
7108
7109	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7110	ctsio->be_move_done = ctl_config_move_done;
7111	ctl_datamove((union ctl_io *)ctsio);
7112
7113	return (CTL_RETVAL_COMPLETE);
7114}
7115
7116int
7117ctl_read_capacity(struct ctl_scsiio *ctsio)
7118{
7119	struct scsi_read_capacity *cdb;
7120	struct scsi_read_capacity_data *data;
7121	struct ctl_lun *lun;
7122	uint32_t lba;
7123
7124	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7125
7126	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7127
7128	lba = scsi_4btoul(cdb->addr);
7129	if (((cdb->pmi & SRC_PMI) == 0)
7130	 && (lba != 0)) {
7131		ctl_set_invalid_field(/*ctsio*/ ctsio,
7132				      /*sks_valid*/ 1,
7133				      /*command*/ 1,
7134				      /*field*/ 2,
7135				      /*bit_valid*/ 0,
7136				      /*bit*/ 0);
7137		ctl_done((union ctl_io *)ctsio);
7138		return (CTL_RETVAL_COMPLETE);
7139	}
7140
7141	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7142
7143	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7144	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7145	ctsio->residual = 0;
7146	ctsio->kern_data_len = sizeof(*data);
7147	ctsio->kern_total_len = sizeof(*data);
7148	ctsio->kern_data_resid = 0;
7149	ctsio->kern_rel_offset = 0;
7150	ctsio->kern_sg_entries = 0;
7151
7152	/*
7153	 * If the maximum LBA is greater than 0xfffffffe, the user must
7154	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7155	 * serivce action set.
7156	 */
7157	if (lun->be_lun->maxlba > 0xfffffffe)
7158		scsi_ulto4b(0xffffffff, data->addr);
7159	else
7160		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7161
7162	/*
7163	 * XXX KDM this may not be 512 bytes...
7164	 */
7165	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7166
7167	ctsio->scsi_status = SCSI_STATUS_OK;
7168
7169	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7170	ctsio->be_move_done = ctl_config_move_done;
7171	ctl_datamove((union ctl_io *)ctsio);
7172
7173	return (CTL_RETVAL_COMPLETE);
7174}
7175
7176int
7177ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7178{
7179	struct scsi_read_capacity_16 *cdb;
7180	struct scsi_read_capacity_data_long *data;
7181	struct ctl_lun *lun;
7182	uint64_t lba;
7183	uint32_t alloc_len;
7184
7185	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7186
7187	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7188
7189	alloc_len = scsi_4btoul(cdb->alloc_len);
7190	lba = scsi_8btou64(cdb->addr);
7191
7192	if ((cdb->reladr & SRC16_PMI)
7193	 && (lba != 0)) {
7194		ctl_set_invalid_field(/*ctsio*/ ctsio,
7195				      /*sks_valid*/ 1,
7196				      /*command*/ 1,
7197				      /*field*/ 2,
7198				      /*bit_valid*/ 0,
7199				      /*bit*/ 0);
7200		ctl_done((union ctl_io *)ctsio);
7201		return (CTL_RETVAL_COMPLETE);
7202	}
7203
7204	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7205
7206	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7207	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7208
7209	if (sizeof(*data) < alloc_len) {
7210		ctsio->residual = alloc_len - sizeof(*data);
7211		ctsio->kern_data_len = sizeof(*data);
7212		ctsio->kern_total_len = sizeof(*data);
7213	} else {
7214		ctsio->residual = 0;
7215		ctsio->kern_data_len = alloc_len;
7216		ctsio->kern_total_len = alloc_len;
7217	}
7218	ctsio->kern_data_resid = 0;
7219	ctsio->kern_rel_offset = 0;
7220	ctsio->kern_sg_entries = 0;
7221
7222	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7223	/* XXX KDM this may not be 512 bytes... */
7224	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7225	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7226	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7227	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7228		data->lalba_lbp[0] |= SRC16_LBPME;
7229
7230	ctsio->scsi_status = SCSI_STATUS_OK;
7231
7232	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7233	ctsio->be_move_done = ctl_config_move_done;
7234	ctl_datamove((union ctl_io *)ctsio);
7235
7236	return (CTL_RETVAL_COMPLETE);
7237}
7238
7239int
7240ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7241{
7242	struct scsi_maintenance_in *cdb;
7243	int retval;
7244	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7245	int num_target_port_groups, num_target_ports, single;
7246	struct ctl_lun *lun;
7247	struct ctl_softc *softc;
7248	struct ctl_port *port;
7249	struct scsi_target_group_data *rtg_ptr;
7250	struct scsi_target_group_data_extended *rtg_ext_ptr;
7251	struct scsi_target_port_group_descriptor *tpg_desc;
7252
7253	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7254
7255	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7256	softc = control_softc;
7257	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7258
7259	retval = CTL_RETVAL_COMPLETE;
7260
7261	switch (cdb->byte2 & STG_PDF_MASK) {
7262	case STG_PDF_LENGTH:
7263		ext = 0;
7264		break;
7265	case STG_PDF_EXTENDED:
7266		ext = 1;
7267		break;
7268	default:
7269		ctl_set_invalid_field(/*ctsio*/ ctsio,
7270				      /*sks_valid*/ 1,
7271				      /*command*/ 1,
7272				      /*field*/ 2,
7273				      /*bit_valid*/ 1,
7274				      /*bit*/ 5);
7275		ctl_done((union ctl_io *)ctsio);
7276		return(retval);
7277	}
7278
7279	single = ctl_is_single;
7280	if (single)
7281		num_target_port_groups = 1;
7282	else
7283		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7284	num_target_ports = 0;
7285	mtx_lock(&softc->ctl_lock);
7286	STAILQ_FOREACH(port, &softc->port_list, links) {
7287		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7288			continue;
7289		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7290			continue;
7291		num_target_ports++;
7292	}
7293	mtx_unlock(&softc->ctl_lock);
7294
7295	if (ext)
7296		total_len = sizeof(struct scsi_target_group_data_extended);
7297	else
7298		total_len = sizeof(struct scsi_target_group_data);
7299	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7300		num_target_port_groups +
7301	    sizeof(struct scsi_target_port_descriptor) *
7302		num_target_ports * num_target_port_groups;
7303
7304	alloc_len = scsi_4btoul(cdb->length);
7305
7306	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7307
7308	ctsio->kern_sg_entries = 0;
7309
7310	if (total_len < alloc_len) {
7311		ctsio->residual = alloc_len - total_len;
7312		ctsio->kern_data_len = total_len;
7313		ctsio->kern_total_len = total_len;
7314	} else {
7315		ctsio->residual = 0;
7316		ctsio->kern_data_len = alloc_len;
7317		ctsio->kern_total_len = alloc_len;
7318	}
7319	ctsio->kern_data_resid = 0;
7320	ctsio->kern_rel_offset = 0;
7321
7322	if (ext) {
7323		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7324		    ctsio->kern_data_ptr;
7325		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7326		rtg_ext_ptr->format_type = 0x10;
7327		rtg_ext_ptr->implicit_transition_time = 0;
7328		tpg_desc = &rtg_ext_ptr->groups[0];
7329	} else {
7330		rtg_ptr = (struct scsi_target_group_data *)
7331		    ctsio->kern_data_ptr;
7332		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7333		tpg_desc = &rtg_ptr->groups[0];
7334	}
7335
7336	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7337	mtx_lock(&softc->ctl_lock);
7338	for (g = 0; g < num_target_port_groups; g++) {
7339		if (g == pg)
7340			tpg_desc->pref_state = TPG_PRIMARY |
7341			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7342		else
7343			tpg_desc->pref_state =
7344			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7345		tpg_desc->support = TPG_AO_SUP;
7346		if (!single)
7347			tpg_desc->support |= TPG_AN_SUP;
7348		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7349		tpg_desc->status = TPG_IMPLICIT;
7350		pc = 0;
7351		STAILQ_FOREACH(port, &softc->port_list, links) {
7352			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7353				continue;
7354			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7355			    CTL_MAX_LUNS)
7356				continue;
7357			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7358			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7359			    relative_target_port_identifier);
7360			pc++;
7361		}
7362		tpg_desc->target_port_count = pc;
7363		tpg_desc = (struct scsi_target_port_group_descriptor *)
7364		    &tpg_desc->descriptors[pc];
7365	}
7366	mtx_unlock(&softc->ctl_lock);
7367
7368	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7369	ctsio->be_move_done = ctl_config_move_done;
7370
7371	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7372			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7373			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7374			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7375			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7376
7377	ctl_datamove((union ctl_io *)ctsio);
7378	return(retval);
7379}
7380
7381int
7382ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7383{
7384	struct ctl_lun *lun;
7385	struct scsi_report_supported_opcodes *cdb;
7386	const struct ctl_cmd_entry *entry, *sentry;
7387	struct scsi_report_supported_opcodes_all *all;
7388	struct scsi_report_supported_opcodes_descr *descr;
7389	struct scsi_report_supported_opcodes_one *one;
7390	int retval;
7391	int alloc_len, total_len;
7392	int opcode, service_action, i, j, num;
7393
7394	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7395
7396	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7397	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7398
7399	retval = CTL_RETVAL_COMPLETE;
7400
7401	opcode = cdb->requested_opcode;
7402	service_action = scsi_2btoul(cdb->requested_service_action);
7403	switch (cdb->options & RSO_OPTIONS_MASK) {
7404	case RSO_OPTIONS_ALL:
7405		num = 0;
7406		for (i = 0; i < 256; i++) {
7407			entry = &ctl_cmd_table[i];
7408			if (entry->flags & CTL_CMD_FLAG_SA5) {
7409				for (j = 0; j < 32; j++) {
7410					sentry = &((const struct ctl_cmd_entry *)
7411					    entry->execute)[j];
7412					if (ctl_cmd_applicable(
7413					    lun->be_lun->lun_type, sentry))
7414						num++;
7415				}
7416			} else {
7417				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7418				    entry))
7419					num++;
7420			}
7421		}
7422		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7423		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7424		break;
7425	case RSO_OPTIONS_OC:
7426		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7427			ctl_set_invalid_field(/*ctsio*/ ctsio,
7428					      /*sks_valid*/ 1,
7429					      /*command*/ 1,
7430					      /*field*/ 2,
7431					      /*bit_valid*/ 1,
7432					      /*bit*/ 2);
7433			ctl_done((union ctl_io *)ctsio);
7434			return (CTL_RETVAL_COMPLETE);
7435		}
7436		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7437		break;
7438	case RSO_OPTIONS_OC_SA:
7439		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7440		    service_action >= 32) {
7441			ctl_set_invalid_field(/*ctsio*/ ctsio,
7442					      /*sks_valid*/ 1,
7443					      /*command*/ 1,
7444					      /*field*/ 2,
7445					      /*bit_valid*/ 1,
7446					      /*bit*/ 2);
7447			ctl_done((union ctl_io *)ctsio);
7448			return (CTL_RETVAL_COMPLETE);
7449		}
7450		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7451		break;
7452	default:
7453		ctl_set_invalid_field(/*ctsio*/ ctsio,
7454				      /*sks_valid*/ 1,
7455				      /*command*/ 1,
7456				      /*field*/ 2,
7457				      /*bit_valid*/ 1,
7458				      /*bit*/ 2);
7459		ctl_done((union ctl_io *)ctsio);
7460		return (CTL_RETVAL_COMPLETE);
7461	}
7462
7463	alloc_len = scsi_4btoul(cdb->length);
7464
7465	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7466
7467	ctsio->kern_sg_entries = 0;
7468
7469	if (total_len < alloc_len) {
7470		ctsio->residual = alloc_len - total_len;
7471		ctsio->kern_data_len = total_len;
7472		ctsio->kern_total_len = total_len;
7473	} else {
7474		ctsio->residual = 0;
7475		ctsio->kern_data_len = alloc_len;
7476		ctsio->kern_total_len = alloc_len;
7477	}
7478	ctsio->kern_data_resid = 0;
7479	ctsio->kern_rel_offset = 0;
7480
7481	switch (cdb->options & RSO_OPTIONS_MASK) {
7482	case RSO_OPTIONS_ALL:
7483		all = (struct scsi_report_supported_opcodes_all *)
7484		    ctsio->kern_data_ptr;
7485		num = 0;
7486		for (i = 0; i < 256; i++) {
7487			entry = &ctl_cmd_table[i];
7488			if (entry->flags & CTL_CMD_FLAG_SA5) {
7489				for (j = 0; j < 32; j++) {
7490					sentry = &((const struct ctl_cmd_entry *)
7491					    entry->execute)[j];
7492					if (!ctl_cmd_applicable(
7493					    lun->be_lun->lun_type, sentry))
7494						continue;
7495					descr = &all->descr[num++];
7496					descr->opcode = i;
7497					scsi_ulto2b(j, descr->service_action);
7498					descr->flags = RSO_SERVACTV;
7499					scsi_ulto2b(sentry->length,
7500					    descr->cdb_length);
7501				}
7502			} else {
7503				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7504				    entry))
7505					continue;
7506				descr = &all->descr[num++];
7507				descr->opcode = i;
7508				scsi_ulto2b(0, descr->service_action);
7509				descr->flags = 0;
7510				scsi_ulto2b(entry->length, descr->cdb_length);
7511			}
7512		}
7513		scsi_ulto4b(
7514		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7515		    all->length);
7516		break;
7517	case RSO_OPTIONS_OC:
7518		one = (struct scsi_report_supported_opcodes_one *)
7519		    ctsio->kern_data_ptr;
7520		entry = &ctl_cmd_table[opcode];
7521		goto fill_one;
7522	case RSO_OPTIONS_OC_SA:
7523		one = (struct scsi_report_supported_opcodes_one *)
7524		    ctsio->kern_data_ptr;
7525		entry = &ctl_cmd_table[opcode];
7526		entry = &((const struct ctl_cmd_entry *)
7527		    entry->execute)[service_action];
7528fill_one:
7529		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7530			one->support = 3;
7531			scsi_ulto2b(entry->length, one->cdb_length);
7532			one->cdb_usage[0] = opcode;
7533			memcpy(&one->cdb_usage[1], entry->usage,
7534			    entry->length - 1);
7535		} else
7536			one->support = 1;
7537		break;
7538	}
7539
7540	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7541	ctsio->be_move_done = ctl_config_move_done;
7542
7543	ctl_datamove((union ctl_io *)ctsio);
7544	return(retval);
7545}
7546
7547int
7548ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7549{
7550	struct ctl_lun *lun;
7551	struct scsi_report_supported_tmf *cdb;
7552	struct scsi_report_supported_tmf_data *data;
7553	int retval;
7554	int alloc_len, total_len;
7555
7556	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7557
7558	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7559	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7560
7561	retval = CTL_RETVAL_COMPLETE;
7562
7563	total_len = sizeof(struct scsi_report_supported_tmf_data);
7564	alloc_len = scsi_4btoul(cdb->length);
7565
7566	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7567
7568	ctsio->kern_sg_entries = 0;
7569
7570	if (total_len < alloc_len) {
7571		ctsio->residual = alloc_len - total_len;
7572		ctsio->kern_data_len = total_len;
7573		ctsio->kern_total_len = total_len;
7574	} else {
7575		ctsio->residual = 0;
7576		ctsio->kern_data_len = alloc_len;
7577		ctsio->kern_total_len = alloc_len;
7578	}
7579	ctsio->kern_data_resid = 0;
7580	ctsio->kern_rel_offset = 0;
7581
7582	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7583	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7584	data->byte2 |= RST_ITNRS;
7585
7586	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7587	ctsio->be_move_done = ctl_config_move_done;
7588
7589	ctl_datamove((union ctl_io *)ctsio);
7590	return (retval);
7591}
7592
7593int
7594ctl_report_timestamp(struct ctl_scsiio *ctsio)
7595{
7596	struct ctl_lun *lun;
7597	struct scsi_report_timestamp *cdb;
7598	struct scsi_report_timestamp_data *data;
7599	struct timeval tv;
7600	int64_t timestamp;
7601	int retval;
7602	int alloc_len, total_len;
7603
7604	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7605
7606	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7607	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7608
7609	retval = CTL_RETVAL_COMPLETE;
7610
7611	total_len = sizeof(struct scsi_report_timestamp_data);
7612	alloc_len = scsi_4btoul(cdb->length);
7613
7614	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7615
7616	ctsio->kern_sg_entries = 0;
7617
7618	if (total_len < alloc_len) {
7619		ctsio->residual = alloc_len - total_len;
7620		ctsio->kern_data_len = total_len;
7621		ctsio->kern_total_len = total_len;
7622	} else {
7623		ctsio->residual = 0;
7624		ctsio->kern_data_len = alloc_len;
7625		ctsio->kern_total_len = alloc_len;
7626	}
7627	ctsio->kern_data_resid = 0;
7628	ctsio->kern_rel_offset = 0;
7629
7630	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7631	scsi_ulto2b(sizeof(*data) - 2, data->length);
7632	data->origin = RTS_ORIG_OUTSIDE;
7633	getmicrotime(&tv);
7634	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7635	scsi_ulto4b(timestamp >> 16, data->timestamp);
7636	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7637
7638	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7639	ctsio->be_move_done = ctl_config_move_done;
7640
7641	ctl_datamove((union ctl_io *)ctsio);
7642	return (retval);
7643}
7644
7645int
7646ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7647{
7648	struct scsi_per_res_in *cdb;
7649	int alloc_len, total_len = 0;
7650	/* struct scsi_per_res_in_rsrv in_data; */
7651	struct ctl_lun *lun;
7652	struct ctl_softc *softc;
7653
7654	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7655
7656	softc = control_softc;
7657
7658	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7659
7660	alloc_len = scsi_2btoul(cdb->length);
7661
7662	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7663
7664retry:
7665	mtx_lock(&lun->lun_lock);
7666	switch (cdb->action) {
7667	case SPRI_RK: /* read keys */
7668		total_len = sizeof(struct scsi_per_res_in_keys) +
7669			lun->pr_key_count *
7670			sizeof(struct scsi_per_res_key);
7671		break;
7672	case SPRI_RR: /* read reservation */
7673		if (lun->flags & CTL_LUN_PR_RESERVED)
7674			total_len = sizeof(struct scsi_per_res_in_rsrv);
7675		else
7676			total_len = sizeof(struct scsi_per_res_in_header);
7677		break;
7678	case SPRI_RC: /* report capabilities */
7679		total_len = sizeof(struct scsi_per_res_cap);
7680		break;
7681	case SPRI_RS: /* read full status */
7682		total_len = sizeof(struct scsi_per_res_in_header) +
7683		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7684		    lun->pr_key_count;
7685		break;
7686	default:
7687		panic("Invalid PR type %x", cdb->action);
7688	}
7689	mtx_unlock(&lun->lun_lock);
7690
7691	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7692
7693	if (total_len < alloc_len) {
7694		ctsio->residual = alloc_len - total_len;
7695		ctsio->kern_data_len = total_len;
7696		ctsio->kern_total_len = total_len;
7697	} else {
7698		ctsio->residual = 0;
7699		ctsio->kern_data_len = alloc_len;
7700		ctsio->kern_total_len = alloc_len;
7701	}
7702
7703	ctsio->kern_data_resid = 0;
7704	ctsio->kern_rel_offset = 0;
7705	ctsio->kern_sg_entries = 0;
7706
7707	mtx_lock(&lun->lun_lock);
7708	switch (cdb->action) {
7709	case SPRI_RK: { // read keys
7710        struct scsi_per_res_in_keys *res_keys;
7711		int i, key_count;
7712
7713		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7714
7715		/*
7716		 * We had to drop the lock to allocate our buffer, which
7717		 * leaves time for someone to come in with another
7718		 * persistent reservation.  (That is unlikely, though,
7719		 * since this should be the only persistent reservation
7720		 * command active right now.)
7721		 */
7722		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7723		    (lun->pr_key_count *
7724		     sizeof(struct scsi_per_res_key)))){
7725			mtx_unlock(&lun->lun_lock);
7726			free(ctsio->kern_data_ptr, M_CTL);
7727			printf("%s: reservation length changed, retrying\n",
7728			       __func__);
7729			goto retry;
7730		}
7731
7732		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7733
7734		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7735			     lun->pr_key_count, res_keys->header.length);
7736
7737		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7738			if (!lun->per_res[i].registered)
7739				continue;
7740
7741			/*
7742			 * We used lun->pr_key_count to calculate the
7743			 * size to allocate.  If it turns out the number of
7744			 * initiators with the registered flag set is
7745			 * larger than that (i.e. they haven't been kept in
7746			 * sync), we've got a problem.
7747			 */
7748			if (key_count >= lun->pr_key_count) {
7749#ifdef NEEDTOPORT
7750				csevent_log(CSC_CTL | CSC_SHELF_SW |
7751					    CTL_PR_ERROR,
7752					    csevent_LogType_Fault,
7753					    csevent_AlertLevel_Yellow,
7754					    csevent_FRU_ShelfController,
7755					    csevent_FRU_Firmware,
7756				        csevent_FRU_Unknown,
7757					    "registered keys %d >= key "
7758					    "count %d", key_count,
7759					    lun->pr_key_count);
7760#endif
7761				key_count++;
7762				continue;
7763			}
7764			memcpy(res_keys->keys[key_count].key,
7765			       lun->per_res[i].res_key.key,
7766			       ctl_min(sizeof(res_keys->keys[key_count].key),
7767			       sizeof(lun->per_res[i].res_key)));
7768			key_count++;
7769		}
7770		break;
7771	}
7772	case SPRI_RR: { // read reservation
7773		struct scsi_per_res_in_rsrv *res;
7774		int tmp_len, header_only;
7775
7776		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7777
7778		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7779
7780		if (lun->flags & CTL_LUN_PR_RESERVED)
7781		{
7782			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7783			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7784				    res->header.length);
7785			header_only = 0;
7786		} else {
7787			tmp_len = sizeof(struct scsi_per_res_in_header);
7788			scsi_ulto4b(0, res->header.length);
7789			header_only = 1;
7790		}
7791
7792		/*
7793		 * We had to drop the lock to allocate our buffer, which
7794		 * leaves time for someone to come in with another
7795		 * persistent reservation.  (That is unlikely, though,
7796		 * since this should be the only persistent reservation
7797		 * command active right now.)
7798		 */
7799		if (tmp_len != total_len) {
7800			mtx_unlock(&lun->lun_lock);
7801			free(ctsio->kern_data_ptr, M_CTL);
7802			printf("%s: reservation status changed, retrying\n",
7803			       __func__);
7804			goto retry;
7805		}
7806
7807		/*
7808		 * No reservation held, so we're done.
7809		 */
7810		if (header_only != 0)
7811			break;
7812
7813		/*
7814		 * If the registration is an All Registrants type, the key
7815		 * is 0, since it doesn't really matter.
7816		 */
7817		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7818			memcpy(res->data.reservation,
7819			       &lun->per_res[lun->pr_res_idx].res_key,
7820			       sizeof(struct scsi_per_res_key));
7821		}
7822		res->data.scopetype = lun->res_type;
7823		break;
7824	}
7825	case SPRI_RC:     //report capabilities
7826	{
7827		struct scsi_per_res_cap *res_cap;
7828		uint16_t type_mask;
7829
7830		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7831		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7832		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7833		type_mask = SPRI_TM_WR_EX_AR |
7834			    SPRI_TM_EX_AC_RO |
7835			    SPRI_TM_WR_EX_RO |
7836			    SPRI_TM_EX_AC |
7837			    SPRI_TM_WR_EX |
7838			    SPRI_TM_EX_AC_AR;
7839		scsi_ulto2b(type_mask, res_cap->type_mask);
7840		break;
7841	}
7842	case SPRI_RS: { // read full status
7843		struct scsi_per_res_in_full *res_status;
7844		struct scsi_per_res_in_full_desc *res_desc;
7845		struct ctl_port *port;
7846		int i, len;
7847
7848		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7849
7850		/*
7851		 * We had to drop the lock to allocate our buffer, which
7852		 * leaves time for someone to come in with another
7853		 * persistent reservation.  (That is unlikely, though,
7854		 * since this should be the only persistent reservation
7855		 * command active right now.)
7856		 */
7857		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7858		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7859		     lun->pr_key_count)){
7860			mtx_unlock(&lun->lun_lock);
7861			free(ctsio->kern_data_ptr, M_CTL);
7862			printf("%s: reservation length changed, retrying\n",
7863			       __func__);
7864			goto retry;
7865		}
7866
7867		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7868
7869		res_desc = &res_status->desc[0];
7870		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7871			if (!lun->per_res[i].registered)
7872				continue;
7873
7874			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7875			    sizeof(res_desc->res_key));
7876			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7877			    (lun->pr_res_idx == i ||
7878			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7879				res_desc->flags = SPRI_FULL_R_HOLDER;
7880				res_desc->scopetype = lun->res_type;
7881			}
7882			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7883			    res_desc->rel_trgt_port_id);
7884			len = 0;
7885			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7886			if (port != NULL)
7887				len = ctl_create_iid(port,
7888				    i % CTL_MAX_INIT_PER_PORT,
7889				    res_desc->transport_id);
7890			scsi_ulto4b(len, res_desc->additional_length);
7891			res_desc = (struct scsi_per_res_in_full_desc *)
7892			    &res_desc->transport_id[len];
7893		}
7894		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7895		    res_status->header.length);
7896		break;
7897	}
7898	default:
7899		/*
7900		 * This is a bug, because we just checked for this above,
7901		 * and should have returned an error.
7902		 */
7903		panic("Invalid PR type %x", cdb->action);
7904		break; /* NOTREACHED */
7905	}
7906	mtx_unlock(&lun->lun_lock);
7907
7908	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7909	ctsio->be_move_done = ctl_config_move_done;
7910
7911	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7912			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7913			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7914			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7915			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7916
7917	ctl_datamove((union ctl_io *)ctsio);
7918
7919	return (CTL_RETVAL_COMPLETE);
7920}
7921
7922/*
7923 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7924 * it should return.
7925 */
7926static int
7927ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7928		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7929		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7930		struct scsi_per_res_out_parms* param)
7931{
7932	union ctl_ha_msg persis_io;
7933	int retval, i;
7934	int isc_retval;
7935
7936	retval = 0;
7937
7938	mtx_lock(&lun->lun_lock);
7939	if (sa_res_key == 0) {
7940		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7941			/* validate scope and type */
7942			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7943			     SPR_LU_SCOPE) {
7944				mtx_unlock(&lun->lun_lock);
7945				ctl_set_invalid_field(/*ctsio*/ ctsio,
7946						      /*sks_valid*/ 1,
7947						      /*command*/ 1,
7948						      /*field*/ 2,
7949						      /*bit_valid*/ 1,
7950						      /*bit*/ 4);
7951				ctl_done((union ctl_io *)ctsio);
7952				return (1);
7953			}
7954
7955		        if (type>8 || type==2 || type==4 || type==0) {
7956				mtx_unlock(&lun->lun_lock);
7957				ctl_set_invalid_field(/*ctsio*/ ctsio,
7958       	           				      /*sks_valid*/ 1,
7959						      /*command*/ 1,
7960						      /*field*/ 2,
7961						      /*bit_valid*/ 1,
7962						      /*bit*/ 0);
7963				ctl_done((union ctl_io *)ctsio);
7964				return (1);
7965		        }
7966
7967			/* temporarily unregister this nexus */
7968			lun->per_res[residx].registered = 0;
7969
7970			/*
7971			 * Unregister everybody else and build UA for
7972			 * them
7973			 */
7974			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7975				if (lun->per_res[i].registered == 0)
7976					continue;
7977
7978				if (!persis_offset
7979				 && i <CTL_MAX_INITIATORS)
7980					lun->pending_sense[i].ua_pending |=
7981						CTL_UA_REG_PREEMPT;
7982				else if (persis_offset
7983				      && i >= persis_offset)
7984					lun->pending_sense[i-persis_offset
7985						].ua_pending |=
7986						CTL_UA_REG_PREEMPT;
7987				lun->per_res[i].registered = 0;
7988				memset(&lun->per_res[i].res_key, 0,
7989				       sizeof(struct scsi_per_res_key));
7990			}
7991			lun->per_res[residx].registered = 1;
7992			lun->pr_key_count = 1;
7993			lun->res_type = type;
7994			if (lun->res_type != SPR_TYPE_WR_EX_AR
7995			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7996				lun->pr_res_idx = residx;
7997
7998			/* send msg to other side */
7999			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8000			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8001			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8002			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8003			persis_io.pr.pr_info.res_type = type;
8004			memcpy(persis_io.pr.pr_info.sa_res_key,
8005			       param->serv_act_res_key,
8006			       sizeof(param->serv_act_res_key));
8007			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8008			     &persis_io, sizeof(persis_io), 0)) >
8009			     CTL_HA_STATUS_SUCCESS) {
8010				printf("CTL:Persis Out error returned "
8011				       "from ctl_ha_msg_send %d\n",
8012				       isc_retval);
8013			}
8014		} else {
8015			/* not all registrants */
8016			mtx_unlock(&lun->lun_lock);
8017			free(ctsio->kern_data_ptr, M_CTL);
8018			ctl_set_invalid_field(ctsio,
8019					      /*sks_valid*/ 1,
8020					      /*command*/ 0,
8021					      /*field*/ 8,
8022					      /*bit_valid*/ 0,
8023					      /*bit*/ 0);
8024			ctl_done((union ctl_io *)ctsio);
8025			return (1);
8026		}
8027	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8028		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8029		int found = 0;
8030
8031		if (res_key == sa_res_key) {
8032			/* special case */
8033			/*
8034			 * The spec implies this is not good but doesn't
8035			 * say what to do. There are two choices either
8036			 * generate a res conflict or check condition
8037			 * with illegal field in parameter data. Since
8038			 * that is what is done when the sa_res_key is
8039			 * zero I'll take that approach since this has
8040			 * to do with the sa_res_key.
8041			 */
8042			mtx_unlock(&lun->lun_lock);
8043			free(ctsio->kern_data_ptr, M_CTL);
8044			ctl_set_invalid_field(ctsio,
8045					      /*sks_valid*/ 1,
8046					      /*command*/ 0,
8047					      /*field*/ 8,
8048					      /*bit_valid*/ 0,
8049					      /*bit*/ 0);
8050			ctl_done((union ctl_io *)ctsio);
8051			return (1);
8052		}
8053
8054		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8055			if (lun->per_res[i].registered
8056			 && memcmp(param->serv_act_res_key,
8057			    lun->per_res[i].res_key.key,
8058			    sizeof(struct scsi_per_res_key)) != 0)
8059				continue;
8060
8061			found = 1;
8062			lun->per_res[i].registered = 0;
8063			memset(&lun->per_res[i].res_key, 0,
8064			       sizeof(struct scsi_per_res_key));
8065			lun->pr_key_count--;
8066
8067			if (!persis_offset
8068			 && i < CTL_MAX_INITIATORS)
8069				lun->pending_sense[i].ua_pending |=
8070					CTL_UA_REG_PREEMPT;
8071			else if (persis_offset
8072			      && i >= persis_offset)
8073				lun->pending_sense[i-persis_offset].ua_pending|=
8074					CTL_UA_REG_PREEMPT;
8075		}
8076		if (!found) {
8077			mtx_unlock(&lun->lun_lock);
8078			free(ctsio->kern_data_ptr, M_CTL);
8079			ctl_set_reservation_conflict(ctsio);
8080			ctl_done((union ctl_io *)ctsio);
8081			return (CTL_RETVAL_COMPLETE);
8082		}
8083		/* send msg to other side */
8084		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8085		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8086		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8087		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8088		persis_io.pr.pr_info.res_type = type;
8089		memcpy(persis_io.pr.pr_info.sa_res_key,
8090		       param->serv_act_res_key,
8091		       sizeof(param->serv_act_res_key));
8092		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8093		     &persis_io, sizeof(persis_io), 0)) >
8094		     CTL_HA_STATUS_SUCCESS) {
8095			printf("CTL:Persis Out error returned from "
8096			       "ctl_ha_msg_send %d\n", isc_retval);
8097		}
8098	} else {
8099		/* Reserved but not all registrants */
8100		/* sa_res_key is res holder */
8101		if (memcmp(param->serv_act_res_key,
8102                   lun->per_res[lun->pr_res_idx].res_key.key,
8103                   sizeof(struct scsi_per_res_key)) == 0) {
8104			/* validate scope and type */
8105			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8106			     SPR_LU_SCOPE) {
8107				mtx_unlock(&lun->lun_lock);
8108				ctl_set_invalid_field(/*ctsio*/ ctsio,
8109						      /*sks_valid*/ 1,
8110						      /*command*/ 1,
8111						      /*field*/ 2,
8112						      /*bit_valid*/ 1,
8113						      /*bit*/ 4);
8114				ctl_done((union ctl_io *)ctsio);
8115				return (1);
8116			}
8117
8118			if (type>8 || type==2 || type==4 || type==0) {
8119				mtx_unlock(&lun->lun_lock);
8120				ctl_set_invalid_field(/*ctsio*/ ctsio,
8121						      /*sks_valid*/ 1,
8122						      /*command*/ 1,
8123						      /*field*/ 2,
8124						      /*bit_valid*/ 1,
8125						      /*bit*/ 0);
8126				ctl_done((union ctl_io *)ctsio);
8127				return (1);
8128			}
8129
8130			/*
8131			 * Do the following:
8132			 * if sa_res_key != res_key remove all
8133			 * registrants w/sa_res_key and generate UA
8134			 * for these registrants(Registrations
8135			 * Preempted) if it wasn't an exclusive
8136			 * reservation generate UA(Reservations
8137			 * Preempted) for all other registered nexuses
8138			 * if the type has changed. Establish the new
8139			 * reservation and holder. If res_key and
8140			 * sa_res_key are the same do the above
8141			 * except don't unregister the res holder.
8142			 */
8143
8144			/*
8145			 * Temporarily unregister so it won't get
8146			 * removed or UA generated
8147			 */
8148			lun->per_res[residx].registered = 0;
8149			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8150				if (lun->per_res[i].registered == 0)
8151					continue;
8152
8153				if (memcmp(param->serv_act_res_key,
8154				    lun->per_res[i].res_key.key,
8155				    sizeof(struct scsi_per_res_key)) == 0) {
8156					lun->per_res[i].registered = 0;
8157					memset(&lun->per_res[i].res_key,
8158					       0,
8159					       sizeof(struct scsi_per_res_key));
8160					lun->pr_key_count--;
8161
8162					if (!persis_offset
8163					 && i < CTL_MAX_INITIATORS)
8164						lun->pending_sense[i
8165							].ua_pending |=
8166							CTL_UA_REG_PREEMPT;
8167					else if (persis_offset
8168					      && i >= persis_offset)
8169						lun->pending_sense[
8170						  i-persis_offset].ua_pending |=
8171						  CTL_UA_REG_PREEMPT;
8172				} else if (type != lun->res_type
8173					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8174					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8175						if (!persis_offset
8176						 && i < CTL_MAX_INITIATORS)
8177							lun->pending_sense[i
8178							].ua_pending |=
8179							CTL_UA_RES_RELEASE;
8180						else if (persis_offset
8181						      && i >= persis_offset)
8182							lun->pending_sense[
8183							i-persis_offset
8184							].ua_pending |=
8185							CTL_UA_RES_RELEASE;
8186				}
8187			}
8188			lun->per_res[residx].registered = 1;
8189			lun->res_type = type;
8190			if (lun->res_type != SPR_TYPE_WR_EX_AR
8191			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8192				lun->pr_res_idx = residx;
8193			else
8194				lun->pr_res_idx =
8195					CTL_PR_ALL_REGISTRANTS;
8196
8197			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8198			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8199			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8200			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8201			persis_io.pr.pr_info.res_type = type;
8202			memcpy(persis_io.pr.pr_info.sa_res_key,
8203			       param->serv_act_res_key,
8204			       sizeof(param->serv_act_res_key));
8205			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8206			     &persis_io, sizeof(persis_io), 0)) >
8207			     CTL_HA_STATUS_SUCCESS) {
8208				printf("CTL:Persis Out error returned "
8209				       "from ctl_ha_msg_send %d\n",
8210				       isc_retval);
8211			}
8212		} else {
8213			/*
8214			 * sa_res_key is not the res holder just
8215			 * remove registrants
8216			 */
8217			int found=0;
8218
8219			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8220				if (memcmp(param->serv_act_res_key,
8221				    lun->per_res[i].res_key.key,
8222				    sizeof(struct scsi_per_res_key)) != 0)
8223					continue;
8224
8225				found = 1;
8226				lun->per_res[i].registered = 0;
8227				memset(&lun->per_res[i].res_key, 0,
8228				       sizeof(struct scsi_per_res_key));
8229				lun->pr_key_count--;
8230
8231				if (!persis_offset
8232				 && i < CTL_MAX_INITIATORS)
8233					lun->pending_sense[i].ua_pending |=
8234						CTL_UA_REG_PREEMPT;
8235				else if (persis_offset
8236				      && i >= persis_offset)
8237					lun->pending_sense[
8238						i-persis_offset].ua_pending |=
8239						CTL_UA_REG_PREEMPT;
8240			}
8241
8242			if (!found) {
8243				mtx_unlock(&lun->lun_lock);
8244				free(ctsio->kern_data_ptr, M_CTL);
8245				ctl_set_reservation_conflict(ctsio);
8246				ctl_done((union ctl_io *)ctsio);
8247		        	return (1);
8248			}
8249			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8250			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8251			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8252			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8253			persis_io.pr.pr_info.res_type = type;
8254			memcpy(persis_io.pr.pr_info.sa_res_key,
8255			       param->serv_act_res_key,
8256			       sizeof(param->serv_act_res_key));
8257			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8258			     &persis_io, sizeof(persis_io), 0)) >
8259			     CTL_HA_STATUS_SUCCESS) {
8260				printf("CTL:Persis Out error returned "
8261				       "from ctl_ha_msg_send %d\n",
8262				isc_retval);
8263			}
8264		}
8265	}
8266
8267	lun->PRGeneration++;
8268	mtx_unlock(&lun->lun_lock);
8269
8270	return (retval);
8271}
8272
8273static void
8274ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8275{
8276	int i;
8277
8278	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8279	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8280	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8281		   msg->pr.pr_info.sa_res_key,
8282		   sizeof(struct scsi_per_res_key)) != 0) {
8283		uint64_t sa_res_key;
8284		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8285
8286		if (sa_res_key == 0) {
8287			/* temporarily unregister this nexus */
8288			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8289
8290			/*
8291			 * Unregister everybody else and build UA for
8292			 * them
8293			 */
8294			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8295				if (lun->per_res[i].registered == 0)
8296					continue;
8297
8298				if (!persis_offset
8299				 && i < CTL_MAX_INITIATORS)
8300					lun->pending_sense[i].ua_pending |=
8301						CTL_UA_REG_PREEMPT;
8302				else if (persis_offset && i >= persis_offset)
8303					lun->pending_sense[i -
8304						persis_offset].ua_pending |=
8305						CTL_UA_REG_PREEMPT;
8306				lun->per_res[i].registered = 0;
8307				memset(&lun->per_res[i].res_key, 0,
8308				       sizeof(struct scsi_per_res_key));
8309			}
8310
8311			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8312			lun->pr_key_count = 1;
8313			lun->res_type = msg->pr.pr_info.res_type;
8314			if (lun->res_type != SPR_TYPE_WR_EX_AR
8315			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8316				lun->pr_res_idx = msg->pr.pr_info.residx;
8317		} else {
8318		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8319				if (memcmp(msg->pr.pr_info.sa_res_key,
8320		                   lun->per_res[i].res_key.key,
8321		                   sizeof(struct scsi_per_res_key)) != 0)
8322					continue;
8323
8324				lun->per_res[i].registered = 0;
8325				memset(&lun->per_res[i].res_key, 0,
8326				       sizeof(struct scsi_per_res_key));
8327				lun->pr_key_count--;
8328
8329				if (!persis_offset
8330				 && i < persis_offset)
8331					lun->pending_sense[i].ua_pending |=
8332						CTL_UA_REG_PREEMPT;
8333				else if (persis_offset
8334				      && i >= persis_offset)
8335					lun->pending_sense[i -
8336						persis_offset].ua_pending |=
8337						CTL_UA_REG_PREEMPT;
8338			}
8339		}
8340	} else {
8341		/*
8342		 * Temporarily unregister so it won't get removed
8343		 * or UA generated
8344		 */
8345		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8346		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8347			if (lun->per_res[i].registered == 0)
8348				continue;
8349
8350			if (memcmp(msg->pr.pr_info.sa_res_key,
8351	                   lun->per_res[i].res_key.key,
8352	                   sizeof(struct scsi_per_res_key)) == 0) {
8353				lun->per_res[i].registered = 0;
8354				memset(&lun->per_res[i].res_key, 0,
8355				       sizeof(struct scsi_per_res_key));
8356				lun->pr_key_count--;
8357				if (!persis_offset
8358				 && i < CTL_MAX_INITIATORS)
8359					lun->pending_sense[i].ua_pending |=
8360						CTL_UA_REG_PREEMPT;
8361				else if (persis_offset
8362				      && i >= persis_offset)
8363					lun->pending_sense[i -
8364						persis_offset].ua_pending |=
8365						CTL_UA_REG_PREEMPT;
8366			} else if (msg->pr.pr_info.res_type != lun->res_type
8367				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8368				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8369					if (!persis_offset
8370					 && i < persis_offset)
8371						lun->pending_sense[i
8372							].ua_pending |=
8373							CTL_UA_RES_RELEASE;
8374					else if (persis_offset
8375					      && i >= persis_offset)
8376					lun->pending_sense[i -
8377						persis_offset].ua_pending |=
8378						CTL_UA_RES_RELEASE;
8379			}
8380		}
8381		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8382		lun->res_type = msg->pr.pr_info.res_type;
8383		if (lun->res_type != SPR_TYPE_WR_EX_AR
8384		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8385			lun->pr_res_idx = msg->pr.pr_info.residx;
8386		else
8387			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8388	}
8389	lun->PRGeneration++;
8390
8391}
8392
8393
8394int
8395ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8396{
8397	int retval;
8398	int isc_retval;
8399	u_int32_t param_len;
8400	struct scsi_per_res_out *cdb;
8401	struct ctl_lun *lun;
8402	struct scsi_per_res_out_parms* param;
8403	struct ctl_softc *softc;
8404	uint32_t residx;
8405	uint64_t res_key, sa_res_key;
8406	uint8_t type;
8407	union ctl_ha_msg persis_io;
8408	int    i;
8409
8410	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8411
8412	retval = CTL_RETVAL_COMPLETE;
8413
8414	softc = control_softc;
8415
8416	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8417	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8418
8419	/*
8420	 * We only support whole-LUN scope.  The scope & type are ignored for
8421	 * register, register and ignore existing key and clear.
8422	 * We sometimes ignore scope and type on preempts too!!
8423	 * Verify reservation type here as well.
8424	 */
8425	type = cdb->scope_type & SPR_TYPE_MASK;
8426	if ((cdb->action == SPRO_RESERVE)
8427	 || (cdb->action == SPRO_RELEASE)) {
8428		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8429			ctl_set_invalid_field(/*ctsio*/ ctsio,
8430					      /*sks_valid*/ 1,
8431					      /*command*/ 1,
8432					      /*field*/ 2,
8433					      /*bit_valid*/ 1,
8434					      /*bit*/ 4);
8435			ctl_done((union ctl_io *)ctsio);
8436			return (CTL_RETVAL_COMPLETE);
8437		}
8438
8439		if (type>8 || type==2 || type==4 || type==0) {
8440			ctl_set_invalid_field(/*ctsio*/ ctsio,
8441					      /*sks_valid*/ 1,
8442					      /*command*/ 1,
8443					      /*field*/ 2,
8444					      /*bit_valid*/ 1,
8445					      /*bit*/ 0);
8446			ctl_done((union ctl_io *)ctsio);
8447			return (CTL_RETVAL_COMPLETE);
8448		}
8449	}
8450
8451	param_len = scsi_4btoul(cdb->length);
8452
8453	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8454		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8455		ctsio->kern_data_len = param_len;
8456		ctsio->kern_total_len = param_len;
8457		ctsio->kern_data_resid = 0;
8458		ctsio->kern_rel_offset = 0;
8459		ctsio->kern_sg_entries = 0;
8460		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8461		ctsio->be_move_done = ctl_config_move_done;
8462		ctl_datamove((union ctl_io *)ctsio);
8463
8464		return (CTL_RETVAL_COMPLETE);
8465	}
8466
8467	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8468
8469	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8470	res_key = scsi_8btou64(param->res_key.key);
8471	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8472
8473	/*
8474	 * Validate the reservation key here except for SPRO_REG_IGNO
8475	 * This must be done for all other service actions
8476	 */
8477	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8478		mtx_lock(&lun->lun_lock);
8479		if (lun->per_res[residx].registered) {
8480		    if (memcmp(param->res_key.key,
8481			       lun->per_res[residx].res_key.key,
8482			       ctl_min(sizeof(param->res_key),
8483			       sizeof(lun->per_res[residx].res_key))) != 0) {
8484				/*
8485				 * The current key passed in doesn't match
8486				 * the one the initiator previously
8487				 * registered.
8488				 */
8489				mtx_unlock(&lun->lun_lock);
8490				free(ctsio->kern_data_ptr, M_CTL);
8491				ctl_set_reservation_conflict(ctsio);
8492				ctl_done((union ctl_io *)ctsio);
8493				return (CTL_RETVAL_COMPLETE);
8494			}
8495		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8496			/*
8497			 * We are not registered
8498			 */
8499			mtx_unlock(&lun->lun_lock);
8500			free(ctsio->kern_data_ptr, M_CTL);
8501			ctl_set_reservation_conflict(ctsio);
8502			ctl_done((union ctl_io *)ctsio);
8503			return (CTL_RETVAL_COMPLETE);
8504		} else if (res_key != 0) {
8505			/*
8506			 * We are not registered and trying to register but
8507			 * the register key isn't zero.
8508			 */
8509			mtx_unlock(&lun->lun_lock);
8510			free(ctsio->kern_data_ptr, M_CTL);
8511			ctl_set_reservation_conflict(ctsio);
8512			ctl_done((union ctl_io *)ctsio);
8513			return (CTL_RETVAL_COMPLETE);
8514		}
8515		mtx_unlock(&lun->lun_lock);
8516	}
8517
8518	switch (cdb->action & SPRO_ACTION_MASK) {
8519	case SPRO_REGISTER:
8520	case SPRO_REG_IGNO: {
8521
8522#if 0
8523		printf("Registration received\n");
8524#endif
8525
8526		/*
8527		 * We don't support any of these options, as we report in
8528		 * the read capabilities request (see
8529		 * ctl_persistent_reserve_in(), above).
8530		 */
8531		if ((param->flags & SPR_SPEC_I_PT)
8532		 || (param->flags & SPR_ALL_TG_PT)
8533		 || (param->flags & SPR_APTPL)) {
8534			int bit_ptr;
8535
8536			if (param->flags & SPR_APTPL)
8537				bit_ptr = 0;
8538			else if (param->flags & SPR_ALL_TG_PT)
8539				bit_ptr = 2;
8540			else /* SPR_SPEC_I_PT */
8541				bit_ptr = 3;
8542
8543			free(ctsio->kern_data_ptr, M_CTL);
8544			ctl_set_invalid_field(ctsio,
8545					      /*sks_valid*/ 1,
8546					      /*command*/ 0,
8547					      /*field*/ 20,
8548					      /*bit_valid*/ 1,
8549					      /*bit*/ bit_ptr);
8550			ctl_done((union ctl_io *)ctsio);
8551			return (CTL_RETVAL_COMPLETE);
8552		}
8553
8554		mtx_lock(&lun->lun_lock);
8555
8556		/*
8557		 * The initiator wants to clear the
8558		 * key/unregister.
8559		 */
8560		if (sa_res_key == 0) {
8561			if ((res_key == 0
8562			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8563			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8564			  && !lun->per_res[residx].registered)) {
8565				mtx_unlock(&lun->lun_lock);
8566				goto done;
8567			}
8568
8569			lun->per_res[residx].registered = 0;
8570			memset(&lun->per_res[residx].res_key,
8571			       0, sizeof(lun->per_res[residx].res_key));
8572			lun->pr_key_count--;
8573
8574			if (residx == lun->pr_res_idx) {
8575				lun->flags &= ~CTL_LUN_PR_RESERVED;
8576				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8577
8578				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8579				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8580				 && lun->pr_key_count) {
8581					/*
8582					 * If the reservation is a registrants
8583					 * only type we need to generate a UA
8584					 * for other registered inits.  The
8585					 * sense code should be RESERVATIONS
8586					 * RELEASED
8587					 */
8588
8589					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8590						if (lun->per_res[
8591						    i+persis_offset].registered
8592						    == 0)
8593							continue;
8594						lun->pending_sense[i
8595							].ua_pending |=
8596							CTL_UA_RES_RELEASE;
8597					}
8598				}
8599				lun->res_type = 0;
8600			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8601				if (lun->pr_key_count==0) {
8602					lun->flags &= ~CTL_LUN_PR_RESERVED;
8603					lun->res_type = 0;
8604					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8605				}
8606			}
8607			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8608			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8609			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8610			persis_io.pr.pr_info.residx = residx;
8611			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8612			     &persis_io, sizeof(persis_io), 0 )) >
8613			     CTL_HA_STATUS_SUCCESS) {
8614				printf("CTL:Persis Out error returned from "
8615				       "ctl_ha_msg_send %d\n", isc_retval);
8616			}
8617		} else /* sa_res_key != 0 */ {
8618
8619			/*
8620			 * If we aren't registered currently then increment
8621			 * the key count and set the registered flag.
8622			 */
8623			if (!lun->per_res[residx].registered) {
8624				lun->pr_key_count++;
8625				lun->per_res[residx].registered = 1;
8626			}
8627
8628			memcpy(&lun->per_res[residx].res_key,
8629			       param->serv_act_res_key,
8630			       ctl_min(sizeof(param->serv_act_res_key),
8631			       sizeof(lun->per_res[residx].res_key)));
8632
8633			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8634			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8635			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8636			persis_io.pr.pr_info.residx = residx;
8637			memcpy(persis_io.pr.pr_info.sa_res_key,
8638			       param->serv_act_res_key,
8639			       sizeof(param->serv_act_res_key));
8640			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8641			     &persis_io, sizeof(persis_io), 0)) >
8642			     CTL_HA_STATUS_SUCCESS) {
8643				printf("CTL:Persis Out error returned from "
8644				       "ctl_ha_msg_send %d\n", isc_retval);
8645			}
8646		}
8647		lun->PRGeneration++;
8648		mtx_unlock(&lun->lun_lock);
8649
8650		break;
8651	}
8652	case SPRO_RESERVE:
8653#if 0
8654                printf("Reserve executed type %d\n", type);
8655#endif
8656		mtx_lock(&lun->lun_lock);
8657		if (lun->flags & CTL_LUN_PR_RESERVED) {
8658			/*
8659			 * if this isn't the reservation holder and it's
8660			 * not a "all registrants" type or if the type is
8661			 * different then we have a conflict
8662			 */
8663			if ((lun->pr_res_idx != residx
8664			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8665			 || lun->res_type != type) {
8666				mtx_unlock(&lun->lun_lock);
8667				free(ctsio->kern_data_ptr, M_CTL);
8668				ctl_set_reservation_conflict(ctsio);
8669				ctl_done((union ctl_io *)ctsio);
8670				return (CTL_RETVAL_COMPLETE);
8671			}
8672			mtx_unlock(&lun->lun_lock);
8673		} else /* create a reservation */ {
8674			/*
8675			 * If it's not an "all registrants" type record
8676			 * reservation holder
8677			 */
8678			if (type != SPR_TYPE_WR_EX_AR
8679			 && type != SPR_TYPE_EX_AC_AR)
8680				lun->pr_res_idx = residx; /* Res holder */
8681			else
8682				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8683
8684			lun->flags |= CTL_LUN_PR_RESERVED;
8685			lun->res_type = type;
8686
8687			mtx_unlock(&lun->lun_lock);
8688
8689			/* send msg to other side */
8690			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8691			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8692			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8693			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8694			persis_io.pr.pr_info.res_type = type;
8695			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8696			     &persis_io, sizeof(persis_io), 0)) >
8697			     CTL_HA_STATUS_SUCCESS) {
8698				printf("CTL:Persis Out error returned from "
8699				       "ctl_ha_msg_send %d\n", isc_retval);
8700			}
8701		}
8702		break;
8703
8704	case SPRO_RELEASE:
8705		mtx_lock(&lun->lun_lock);
8706		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8707			/* No reservation exists return good status */
8708			mtx_unlock(&lun->lun_lock);
8709			goto done;
8710		}
8711		/*
8712		 * Is this nexus a reservation holder?
8713		 */
8714		if (lun->pr_res_idx != residx
8715		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8716			/*
8717			 * not a res holder return good status but
8718			 * do nothing
8719			 */
8720			mtx_unlock(&lun->lun_lock);
8721			goto done;
8722		}
8723
8724		if (lun->res_type != type) {
8725			mtx_unlock(&lun->lun_lock);
8726			free(ctsio->kern_data_ptr, M_CTL);
8727			ctl_set_illegal_pr_release(ctsio);
8728			ctl_done((union ctl_io *)ctsio);
8729			return (CTL_RETVAL_COMPLETE);
8730		}
8731
8732		/* okay to release */
8733		lun->flags &= ~CTL_LUN_PR_RESERVED;
8734		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8735		lun->res_type = 0;
8736
8737		/*
8738		 * if this isn't an exclusive access
8739		 * res generate UA for all other
8740		 * registrants.
8741		 */
8742		if (type != SPR_TYPE_EX_AC
8743		 && type != SPR_TYPE_WR_EX) {
8744			/*
8745			 * temporarily unregister so we don't generate UA
8746			 */
8747			lun->per_res[residx].registered = 0;
8748
8749			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8750				if (lun->per_res[i+persis_offset].registered
8751				    == 0)
8752					continue;
8753				lun->pending_sense[i].ua_pending |=
8754					CTL_UA_RES_RELEASE;
8755			}
8756
8757			lun->per_res[residx].registered = 1;
8758		}
8759		mtx_unlock(&lun->lun_lock);
8760		/* Send msg to other side */
8761		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8762		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8763		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8764		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8765		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8766			printf("CTL:Persis Out error returned from "
8767			       "ctl_ha_msg_send %d\n", isc_retval);
8768		}
8769		break;
8770
8771	case SPRO_CLEAR:
8772		/* send msg to other side */
8773
8774		mtx_lock(&lun->lun_lock);
8775		lun->flags &= ~CTL_LUN_PR_RESERVED;
8776		lun->res_type = 0;
8777		lun->pr_key_count = 0;
8778		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8779
8780
8781		memset(&lun->per_res[residx].res_key,
8782		       0, sizeof(lun->per_res[residx].res_key));
8783		lun->per_res[residx].registered = 0;
8784
8785		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8786			if (lun->per_res[i].registered) {
8787				if (!persis_offset && i < CTL_MAX_INITIATORS)
8788					lun->pending_sense[i].ua_pending |=
8789						CTL_UA_RES_PREEMPT;
8790				else if (persis_offset && i >= persis_offset)
8791					lun->pending_sense[i-persis_offset
8792					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8793
8794				memset(&lun->per_res[i].res_key,
8795				       0, sizeof(struct scsi_per_res_key));
8796				lun->per_res[i].registered = 0;
8797			}
8798		lun->PRGeneration++;
8799		mtx_unlock(&lun->lun_lock);
8800		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8801		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8802		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8803		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8804		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8805			printf("CTL:Persis Out error returned from "
8806			       "ctl_ha_msg_send %d\n", isc_retval);
8807		}
8808		break;
8809
8810	case SPRO_PREEMPT: {
8811		int nretval;
8812
8813		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8814					  residx, ctsio, cdb, param);
8815		if (nretval != 0)
8816			return (CTL_RETVAL_COMPLETE);
8817		break;
8818	}
8819	default:
8820		panic("Invalid PR type %x", cdb->action);
8821	}
8822
8823done:
8824	free(ctsio->kern_data_ptr, M_CTL);
8825	ctl_set_success(ctsio);
8826	ctl_done((union ctl_io *)ctsio);
8827
8828	return (retval);
8829}
8830
8831/*
8832 * This routine is for handling a message from the other SC pertaining to
8833 * persistent reserve out. All the error checking will have been done
8834 * so only perorming the action need be done here to keep the two
8835 * in sync.
8836 */
8837static void
8838ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8839{
8840	struct ctl_lun *lun;
8841	struct ctl_softc *softc;
8842	int i;
8843	uint32_t targ_lun;
8844
8845	softc = control_softc;
8846
8847	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8848	lun = softc->ctl_luns[targ_lun];
8849	mtx_lock(&lun->lun_lock);
8850	switch(msg->pr.pr_info.action) {
8851	case CTL_PR_REG_KEY:
8852		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8853			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8854			lun->pr_key_count++;
8855		}
8856		lun->PRGeneration++;
8857		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8858		       msg->pr.pr_info.sa_res_key,
8859		       sizeof(struct scsi_per_res_key));
8860		break;
8861
8862	case CTL_PR_UNREG_KEY:
8863		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8864		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8865		       0, sizeof(struct scsi_per_res_key));
8866		lun->pr_key_count--;
8867
8868		/* XXX Need to see if the reservation has been released */
8869		/* if so do we need to generate UA? */
8870		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8871			lun->flags &= ~CTL_LUN_PR_RESERVED;
8872			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8873
8874			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8875			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8876			 && lun->pr_key_count) {
8877				/*
8878				 * If the reservation is a registrants
8879				 * only type we need to generate a UA
8880				 * for other registered inits.  The
8881				 * sense code should be RESERVATIONS
8882				 * RELEASED
8883				 */
8884
8885				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8886					if (lun->per_res[i+
8887					    persis_offset].registered == 0)
8888						continue;
8889
8890					lun->pending_sense[i
8891						].ua_pending |=
8892						CTL_UA_RES_RELEASE;
8893				}
8894			}
8895			lun->res_type = 0;
8896		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8897			if (lun->pr_key_count==0) {
8898				lun->flags &= ~CTL_LUN_PR_RESERVED;
8899				lun->res_type = 0;
8900				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8901			}
8902		}
8903		lun->PRGeneration++;
8904		break;
8905
8906	case CTL_PR_RESERVE:
8907		lun->flags |= CTL_LUN_PR_RESERVED;
8908		lun->res_type = msg->pr.pr_info.res_type;
8909		lun->pr_res_idx = msg->pr.pr_info.residx;
8910
8911		break;
8912
8913	case CTL_PR_RELEASE:
8914		/*
8915		 * if this isn't an exclusive access res generate UA for all
8916		 * other registrants.
8917		 */
8918		if (lun->res_type != SPR_TYPE_EX_AC
8919		 && lun->res_type != SPR_TYPE_WR_EX) {
8920			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8921				if (lun->per_res[i+persis_offset].registered)
8922					lun->pending_sense[i].ua_pending |=
8923						CTL_UA_RES_RELEASE;
8924		}
8925
8926		lun->flags &= ~CTL_LUN_PR_RESERVED;
8927		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8928		lun->res_type = 0;
8929		break;
8930
8931	case CTL_PR_PREEMPT:
8932		ctl_pro_preempt_other(lun, msg);
8933		break;
8934	case CTL_PR_CLEAR:
8935		lun->flags &= ~CTL_LUN_PR_RESERVED;
8936		lun->res_type = 0;
8937		lun->pr_key_count = 0;
8938		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8939
8940		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8941			if (lun->per_res[i].registered == 0)
8942				continue;
8943			if (!persis_offset
8944			 && i < CTL_MAX_INITIATORS)
8945				lun->pending_sense[i].ua_pending |=
8946					CTL_UA_RES_PREEMPT;
8947			else if (persis_offset
8948			      && i >= persis_offset)
8949   				lun->pending_sense[i-persis_offset].ua_pending|=
8950					CTL_UA_RES_PREEMPT;
8951			memset(&lun->per_res[i].res_key, 0,
8952			       sizeof(struct scsi_per_res_key));
8953			lun->per_res[i].registered = 0;
8954		}
8955		lun->PRGeneration++;
8956		break;
8957	}
8958
8959	mtx_unlock(&lun->lun_lock);
8960}
8961
8962int
8963ctl_read_write(struct ctl_scsiio *ctsio)
8964{
8965	struct ctl_lun *lun;
8966	struct ctl_lba_len_flags *lbalen;
8967	uint64_t lba;
8968	uint32_t num_blocks;
8969	int fua, dpo;
8970	int retval;
8971	int isread;
8972
8973	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8974
8975	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8976
8977	fua = 0;
8978	dpo = 0;
8979
8980	retval = CTL_RETVAL_COMPLETE;
8981
8982	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8983	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8984	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8985		uint32_t residx;
8986
8987		/*
8988		 * XXX KDM need a lock here.
8989		 */
8990		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8991		if ((lun->res_type == SPR_TYPE_EX_AC
8992		  && residx != lun->pr_res_idx)
8993		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8994		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8995		  && !lun->per_res[residx].registered)) {
8996			ctl_set_reservation_conflict(ctsio);
8997			ctl_done((union ctl_io *)ctsio);
8998			return (CTL_RETVAL_COMPLETE);
8999	        }
9000	}
9001
9002	switch (ctsio->cdb[0]) {
9003	case READ_6:
9004	case WRITE_6: {
9005		struct scsi_rw_6 *cdb;
9006
9007		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9008
9009		lba = scsi_3btoul(cdb->addr);
9010		/* only 5 bits are valid in the most significant address byte */
9011		lba &= 0x1fffff;
9012		num_blocks = cdb->length;
9013		/*
9014		 * This is correct according to SBC-2.
9015		 */
9016		if (num_blocks == 0)
9017			num_blocks = 256;
9018		break;
9019	}
9020	case READ_10:
9021	case WRITE_10: {
9022		struct scsi_rw_10 *cdb;
9023
9024		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9025
9026		if (cdb->byte2 & SRW10_FUA)
9027			fua = 1;
9028		if (cdb->byte2 & SRW10_DPO)
9029			dpo = 1;
9030
9031		lba = scsi_4btoul(cdb->addr);
9032		num_blocks = scsi_2btoul(cdb->length);
9033		break;
9034	}
9035	case WRITE_VERIFY_10: {
9036		struct scsi_write_verify_10 *cdb;
9037
9038		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9039
9040		/*
9041		 * XXX KDM we should do actual write verify support at some
9042		 * point.  This is obviously fake, we're just translating
9043		 * things to a write.  So we don't even bother checking the
9044		 * BYTCHK field, since we don't do any verification.  If
9045		 * the user asks for it, we'll just pretend we did it.
9046		 */
9047		if (cdb->byte2 & SWV_DPO)
9048			dpo = 1;
9049
9050		lba = scsi_4btoul(cdb->addr);
9051		num_blocks = scsi_2btoul(cdb->length);
9052		break;
9053	}
9054	case READ_12:
9055	case WRITE_12: {
9056		struct scsi_rw_12 *cdb;
9057
9058		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9059
9060		if (cdb->byte2 & SRW12_FUA)
9061			fua = 1;
9062		if (cdb->byte2 & SRW12_DPO)
9063			dpo = 1;
9064		lba = scsi_4btoul(cdb->addr);
9065		num_blocks = scsi_4btoul(cdb->length);
9066		break;
9067	}
9068	case WRITE_VERIFY_12: {
9069		struct scsi_write_verify_12 *cdb;
9070
9071		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9072
9073		if (cdb->byte2 & SWV_DPO)
9074			dpo = 1;
9075
9076		lba = scsi_4btoul(cdb->addr);
9077		num_blocks = scsi_4btoul(cdb->length);
9078
9079		break;
9080	}
9081	case READ_16:
9082	case WRITE_16: {
9083		struct scsi_rw_16 *cdb;
9084
9085		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9086
9087		if (cdb->byte2 & SRW12_FUA)
9088			fua = 1;
9089		if (cdb->byte2 & SRW12_DPO)
9090			dpo = 1;
9091
9092		lba = scsi_8btou64(cdb->addr);
9093		num_blocks = scsi_4btoul(cdb->length);
9094		break;
9095	}
9096	case WRITE_VERIFY_16: {
9097		struct scsi_write_verify_16 *cdb;
9098
9099		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9100
9101		if (cdb->byte2 & SWV_DPO)
9102			dpo = 1;
9103
9104		lba = scsi_8btou64(cdb->addr);
9105		num_blocks = scsi_4btoul(cdb->length);
9106		break;
9107	}
9108	default:
9109		/*
9110		 * We got a command we don't support.  This shouldn't
9111		 * happen, commands should be filtered out above us.
9112		 */
9113		ctl_set_invalid_opcode(ctsio);
9114		ctl_done((union ctl_io *)ctsio);
9115
9116		return (CTL_RETVAL_COMPLETE);
9117		break; /* NOTREACHED */
9118	}
9119
9120	/*
9121	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9122	 * interesting for us, but if RAIDCore is in write-back mode,
9123	 * getting it to do write-through for a particular transaction may
9124	 * not be possible.
9125	 */
9126
9127	/*
9128	 * The first check is to make sure we're in bounds, the second
9129	 * check is to catch wrap-around problems.  If the lba + num blocks
9130	 * is less than the lba, then we've wrapped around and the block
9131	 * range is invalid anyway.
9132	 */
9133	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9134	 || ((lba + num_blocks) < lba)) {
9135		ctl_set_lba_out_of_range(ctsio);
9136		ctl_done((union ctl_io *)ctsio);
9137		return (CTL_RETVAL_COMPLETE);
9138	}
9139
9140	/*
9141	 * According to SBC-3, a transfer length of 0 is not an error.
9142	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9143	 * translates to 256 blocks for those commands.
9144	 */
9145	if (num_blocks == 0) {
9146		ctl_set_success(ctsio);
9147		ctl_done((union ctl_io *)ctsio);
9148		return (CTL_RETVAL_COMPLETE);
9149	}
9150
9151	lbalen = (struct ctl_lba_len_flags *)
9152	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9153	lbalen->lba = lba;
9154	lbalen->len = num_blocks;
9155	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9156
9157	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9158	ctsio->kern_rel_offset = 0;
9159
9160	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9161
9162	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9163
9164	return (retval);
9165}
9166
9167static int
9168ctl_cnw_cont(union ctl_io *io)
9169{
9170	struct ctl_scsiio *ctsio;
9171	struct ctl_lun *lun;
9172	struct ctl_lba_len_flags *lbalen;
9173	int retval;
9174
9175	ctsio = &io->scsiio;
9176	ctsio->io_hdr.status = CTL_STATUS_NONE;
9177	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9178	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9179	lbalen = (struct ctl_lba_len_flags *)
9180	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9181	lbalen->flags = CTL_LLF_WRITE;
9182
9183	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9184	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9185	return (retval);
9186}
9187
9188int
9189ctl_cnw(struct ctl_scsiio *ctsio)
9190{
9191	struct ctl_lun *lun;
9192	struct ctl_lba_len_flags *lbalen;
9193	uint64_t lba;
9194	uint32_t num_blocks;
9195	int fua, dpo;
9196	int retval;
9197
9198	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9199
9200	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9201
9202	fua = 0;
9203	dpo = 0;
9204
9205	retval = CTL_RETVAL_COMPLETE;
9206
9207	switch (ctsio->cdb[0]) {
9208	case COMPARE_AND_WRITE: {
9209		struct scsi_compare_and_write *cdb;
9210
9211		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9212
9213		if (cdb->byte2 & SRW10_FUA)
9214			fua = 1;
9215		if (cdb->byte2 & SRW10_DPO)
9216			dpo = 1;
9217		lba = scsi_8btou64(cdb->addr);
9218		num_blocks = cdb->length;
9219		break;
9220	}
9221	default:
9222		/*
9223		 * We got a command we don't support.  This shouldn't
9224		 * happen, commands should be filtered out above us.
9225		 */
9226		ctl_set_invalid_opcode(ctsio);
9227		ctl_done((union ctl_io *)ctsio);
9228
9229		return (CTL_RETVAL_COMPLETE);
9230		break; /* NOTREACHED */
9231	}
9232
9233	/*
9234	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9235	 * interesting for us, but if RAIDCore is in write-back mode,
9236	 * getting it to do write-through for a particular transaction may
9237	 * not be possible.
9238	 */
9239
9240	/*
9241	 * The first check is to make sure we're in bounds, the second
9242	 * check is to catch wrap-around problems.  If the lba + num blocks
9243	 * is less than the lba, then we've wrapped around and the block
9244	 * range is invalid anyway.
9245	 */
9246	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9247	 || ((lba + num_blocks) < lba)) {
9248		ctl_set_lba_out_of_range(ctsio);
9249		ctl_done((union ctl_io *)ctsio);
9250		return (CTL_RETVAL_COMPLETE);
9251	}
9252
9253	/*
9254	 * According to SBC-3, a transfer length of 0 is not an error.
9255	 */
9256	if (num_blocks == 0) {
9257		ctl_set_success(ctsio);
9258		ctl_done((union ctl_io *)ctsio);
9259		return (CTL_RETVAL_COMPLETE);
9260	}
9261
9262	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9263	ctsio->kern_rel_offset = 0;
9264
9265	/*
9266	 * Set the IO_CONT flag, so that if this I/O gets passed to
9267	 * ctl_data_submit_done(), it'll get passed back to
9268	 * ctl_ctl_cnw_cont() for further processing.
9269	 */
9270	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9271	ctsio->io_cont = ctl_cnw_cont;
9272
9273	lbalen = (struct ctl_lba_len_flags *)
9274	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9275	lbalen->lba = lba;
9276	lbalen->len = num_blocks;
9277	lbalen->flags = CTL_LLF_COMPARE;
9278
9279	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9280	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9281	return (retval);
9282}
9283
9284int
9285ctl_verify(struct ctl_scsiio *ctsio)
9286{
9287	struct ctl_lun *lun;
9288	struct ctl_lba_len_flags *lbalen;
9289	uint64_t lba;
9290	uint32_t num_blocks;
9291	int bytchk, dpo;
9292	int retval;
9293
9294	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9295
9296	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9297
9298	bytchk = 0;
9299	dpo = 0;
9300	retval = CTL_RETVAL_COMPLETE;
9301
9302	switch (ctsio->cdb[0]) {
9303	case VERIFY_10: {
9304		struct scsi_verify_10 *cdb;
9305
9306		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9307		if (cdb->byte2 & SVFY_BYTCHK)
9308			bytchk = 1;
9309		if (cdb->byte2 & SVFY_DPO)
9310			dpo = 1;
9311		lba = scsi_4btoul(cdb->addr);
9312		num_blocks = scsi_2btoul(cdb->length);
9313		break;
9314	}
9315	case VERIFY_12: {
9316		struct scsi_verify_12 *cdb;
9317
9318		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9319		if (cdb->byte2 & SVFY_BYTCHK)
9320			bytchk = 1;
9321		if (cdb->byte2 & SVFY_DPO)
9322			dpo = 1;
9323		lba = scsi_4btoul(cdb->addr);
9324		num_blocks = scsi_4btoul(cdb->length);
9325		break;
9326	}
9327	case VERIFY_16: {
9328		struct scsi_rw_16 *cdb;
9329
9330		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9331		if (cdb->byte2 & SVFY_BYTCHK)
9332			bytchk = 1;
9333		if (cdb->byte2 & SVFY_DPO)
9334			dpo = 1;
9335		lba = scsi_8btou64(cdb->addr);
9336		num_blocks = scsi_4btoul(cdb->length);
9337		break;
9338	}
9339	default:
9340		/*
9341		 * We got a command we don't support.  This shouldn't
9342		 * happen, commands should be filtered out above us.
9343		 */
9344		ctl_set_invalid_opcode(ctsio);
9345		ctl_done((union ctl_io *)ctsio);
9346		return (CTL_RETVAL_COMPLETE);
9347	}
9348
9349	/*
9350	 * The first check is to make sure we're in bounds, the second
9351	 * check is to catch wrap-around problems.  If the lba + num blocks
9352	 * is less than the lba, then we've wrapped around and the block
9353	 * range is invalid anyway.
9354	 */
9355	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9356	 || ((lba + num_blocks) < lba)) {
9357		ctl_set_lba_out_of_range(ctsio);
9358		ctl_done((union ctl_io *)ctsio);
9359		return (CTL_RETVAL_COMPLETE);
9360	}
9361
9362	/*
9363	 * According to SBC-3, a transfer length of 0 is not an error.
9364	 */
9365	if (num_blocks == 0) {
9366		ctl_set_success(ctsio);
9367		ctl_done((union ctl_io *)ctsio);
9368		return (CTL_RETVAL_COMPLETE);
9369	}
9370
9371	lbalen = (struct ctl_lba_len_flags *)
9372	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9373	lbalen->lba = lba;
9374	lbalen->len = num_blocks;
9375	if (bytchk) {
9376		lbalen->flags = CTL_LLF_COMPARE;
9377		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9378	} else {
9379		lbalen->flags = CTL_LLF_VERIFY;
9380		ctsio->kern_total_len = 0;
9381	}
9382	ctsio->kern_rel_offset = 0;
9383
9384	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9385	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9386	return (retval);
9387}
9388
9389int
9390ctl_report_luns(struct ctl_scsiio *ctsio)
9391{
9392	struct scsi_report_luns *cdb;
9393	struct scsi_report_luns_data *lun_data;
9394	struct ctl_lun *lun, *request_lun;
9395	int num_luns, retval;
9396	uint32_t alloc_len, lun_datalen;
9397	int num_filled, well_known;
9398	uint32_t initidx, targ_lun_id, lun_id;
9399
9400	retval = CTL_RETVAL_COMPLETE;
9401	well_known = 0;
9402
9403	cdb = (struct scsi_report_luns *)ctsio->cdb;
9404
9405	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9406
9407	mtx_lock(&control_softc->ctl_lock);
9408	num_luns = control_softc->num_luns;
9409	mtx_unlock(&control_softc->ctl_lock);
9410
9411	switch (cdb->select_report) {
9412	case RPL_REPORT_DEFAULT:
9413	case RPL_REPORT_ALL:
9414		break;
9415	case RPL_REPORT_WELLKNOWN:
9416		well_known = 1;
9417		num_luns = 0;
9418		break;
9419	default:
9420		ctl_set_invalid_field(ctsio,
9421				      /*sks_valid*/ 1,
9422				      /*command*/ 1,
9423				      /*field*/ 2,
9424				      /*bit_valid*/ 0,
9425				      /*bit*/ 0);
9426		ctl_done((union ctl_io *)ctsio);
9427		return (retval);
9428		break; /* NOTREACHED */
9429	}
9430
9431	alloc_len = scsi_4btoul(cdb->length);
9432	/*
9433	 * The initiator has to allocate at least 16 bytes for this request,
9434	 * so he can at least get the header and the first LUN.  Otherwise
9435	 * we reject the request (per SPC-3 rev 14, section 6.21).
9436	 */
9437	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9438	    sizeof(struct scsi_report_luns_lundata))) {
9439		ctl_set_invalid_field(ctsio,
9440				      /*sks_valid*/ 1,
9441				      /*command*/ 1,
9442				      /*field*/ 6,
9443				      /*bit_valid*/ 0,
9444				      /*bit*/ 0);
9445		ctl_done((union ctl_io *)ctsio);
9446		return (retval);
9447	}
9448
9449	request_lun = (struct ctl_lun *)
9450		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9451
9452	lun_datalen = sizeof(*lun_data) +
9453		(num_luns * sizeof(struct scsi_report_luns_lundata));
9454
9455	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9456	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9457	ctsio->kern_sg_entries = 0;
9458
9459	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9460
9461	mtx_lock(&control_softc->ctl_lock);
9462	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9463		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9464		if (lun_id >= CTL_MAX_LUNS)
9465			continue;
9466		lun = control_softc->ctl_luns[lun_id];
9467		if (lun == NULL)
9468			continue;
9469
9470		if (targ_lun_id <= 0xff) {
9471			/*
9472			 * Peripheral addressing method, bus number 0.
9473			 */
9474			lun_data->luns[num_filled].lundata[0] =
9475				RPL_LUNDATA_ATYP_PERIPH;
9476			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9477			num_filled++;
9478		} else if (targ_lun_id <= 0x3fff) {
9479			/*
9480			 * Flat addressing method.
9481			 */
9482			lun_data->luns[num_filled].lundata[0] =
9483				RPL_LUNDATA_ATYP_FLAT |
9484				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9485#ifdef OLDCTLHEADERS
9486				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9487				(targ_lun_id & SRLD_BUS_LUN_MASK);
9488#endif
9489			lun_data->luns[num_filled].lundata[1] =
9490#ifdef OLDCTLHEADERS
9491				targ_lun_id >> SRLD_BUS_LUN_BITS;
9492#endif
9493				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9494			num_filled++;
9495		} else {
9496			printf("ctl_report_luns: bogus LUN number %jd, "
9497			       "skipping\n", (intmax_t)targ_lun_id);
9498		}
9499		/*
9500		 * According to SPC-3, rev 14 section 6.21:
9501		 *
9502		 * "The execution of a REPORT LUNS command to any valid and
9503		 * installed logical unit shall clear the REPORTED LUNS DATA
9504		 * HAS CHANGED unit attention condition for all logical
9505		 * units of that target with respect to the requesting
9506		 * initiator. A valid and installed logical unit is one
9507		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9508		 * INQUIRY data (see 6.4.2)."
9509		 *
9510		 * If request_lun is NULL, the LUN this report luns command
9511		 * was issued to is either disabled or doesn't exist. In that
9512		 * case, we shouldn't clear any pending lun change unit
9513		 * attention.
9514		 */
9515		if (request_lun != NULL) {
9516			mtx_lock(&lun->lun_lock);
9517			lun->pending_sense[initidx].ua_pending &=
9518				~CTL_UA_LUN_CHANGE;
9519			mtx_unlock(&lun->lun_lock);
9520		}
9521	}
9522	mtx_unlock(&control_softc->ctl_lock);
9523
9524	/*
9525	 * It's quite possible that we've returned fewer LUNs than we allocated
9526	 * space for.  Trim it.
9527	 */
9528	lun_datalen = sizeof(*lun_data) +
9529		(num_filled * sizeof(struct scsi_report_luns_lundata));
9530
9531	if (lun_datalen < alloc_len) {
9532		ctsio->residual = alloc_len - lun_datalen;
9533		ctsio->kern_data_len = lun_datalen;
9534		ctsio->kern_total_len = lun_datalen;
9535	} else {
9536		ctsio->residual = 0;
9537		ctsio->kern_data_len = alloc_len;
9538		ctsio->kern_total_len = alloc_len;
9539	}
9540	ctsio->kern_data_resid = 0;
9541	ctsio->kern_rel_offset = 0;
9542	ctsio->kern_sg_entries = 0;
9543
9544	/*
9545	 * We set this to the actual data length, regardless of how much
9546	 * space we actually have to return results.  If the user looks at
9547	 * this value, he'll know whether or not he allocated enough space
9548	 * and reissue the command if necessary.  We don't support well
9549	 * known logical units, so if the user asks for that, return none.
9550	 */
9551	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9552
9553	/*
9554	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9555	 * this request.
9556	 */
9557	ctsio->scsi_status = SCSI_STATUS_OK;
9558
9559	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9560	ctsio->be_move_done = ctl_config_move_done;
9561	ctl_datamove((union ctl_io *)ctsio);
9562
9563	return (retval);
9564}
9565
9566int
9567ctl_request_sense(struct ctl_scsiio *ctsio)
9568{
9569	struct scsi_request_sense *cdb;
9570	struct scsi_sense_data *sense_ptr;
9571	struct ctl_lun *lun;
9572	uint32_t initidx;
9573	int have_error;
9574	scsi_sense_data_type sense_format;
9575
9576	cdb = (struct scsi_request_sense *)ctsio->cdb;
9577
9578	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9579
9580	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9581
9582	/*
9583	 * Determine which sense format the user wants.
9584	 */
9585	if (cdb->byte2 & SRS_DESC)
9586		sense_format = SSD_TYPE_DESC;
9587	else
9588		sense_format = SSD_TYPE_FIXED;
9589
9590	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9591	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9592	ctsio->kern_sg_entries = 0;
9593
9594	/*
9595	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9596	 * larger than the largest allowed value for the length field in the
9597	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9598	 */
9599	ctsio->residual = 0;
9600	ctsio->kern_data_len = cdb->length;
9601	ctsio->kern_total_len = cdb->length;
9602
9603	ctsio->kern_data_resid = 0;
9604	ctsio->kern_rel_offset = 0;
9605	ctsio->kern_sg_entries = 0;
9606
9607	/*
9608	 * If we don't have a LUN, we don't have any pending sense.
9609	 */
9610	if (lun == NULL)
9611		goto no_sense;
9612
9613	have_error = 0;
9614	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9615	/*
9616	 * Check for pending sense, and then for pending unit attentions.
9617	 * Pending sense gets returned first, then pending unit attentions.
9618	 */
9619	mtx_lock(&lun->lun_lock);
9620	if (ctl_is_set(lun->have_ca, initidx)) {
9621		scsi_sense_data_type stored_format;
9622
9623		/*
9624		 * Check to see which sense format was used for the stored
9625		 * sense data.
9626		 */
9627		stored_format = scsi_sense_type(
9628		    &lun->pending_sense[initidx].sense);
9629
9630		/*
9631		 * If the user requested a different sense format than the
9632		 * one we stored, then we need to convert it to the other
9633		 * format.  If we're going from descriptor to fixed format
9634		 * sense data, we may lose things in translation, depending
9635		 * on what options were used.
9636		 *
9637		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9638		 * for some reason we'll just copy it out as-is.
9639		 */
9640		if ((stored_format == SSD_TYPE_FIXED)
9641		 && (sense_format == SSD_TYPE_DESC))
9642			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9643			    &lun->pending_sense[initidx].sense,
9644			    (struct scsi_sense_data_desc *)sense_ptr);
9645		else if ((stored_format == SSD_TYPE_DESC)
9646		      && (sense_format == SSD_TYPE_FIXED))
9647			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9648			    &lun->pending_sense[initidx].sense,
9649			    (struct scsi_sense_data_fixed *)sense_ptr);
9650		else
9651			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9652			       ctl_min(sizeof(*sense_ptr),
9653			       sizeof(lun->pending_sense[initidx].sense)));
9654
9655		ctl_clear_mask(lun->have_ca, initidx);
9656		have_error = 1;
9657	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9658		ctl_ua_type ua_type;
9659
9660		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9661				       sense_ptr, sense_format);
9662		if (ua_type != CTL_UA_NONE) {
9663			have_error = 1;
9664			/* We're reporting this UA, so clear it */
9665			lun->pending_sense[initidx].ua_pending &= ~ua_type;
9666		}
9667	}
9668	mtx_unlock(&lun->lun_lock);
9669
9670	/*
9671	 * We already have a pending error, return it.
9672	 */
9673	if (have_error != 0) {
9674		/*
9675		 * We report the SCSI status as OK, since the status of the
9676		 * request sense command itself is OK.
9677		 */
9678		ctsio->scsi_status = SCSI_STATUS_OK;
9679
9680		/*
9681		 * We report 0 for the sense length, because we aren't doing
9682		 * autosense in this case.  We're reporting sense as
9683		 * parameter data.
9684		 */
9685		ctsio->sense_len = 0;
9686		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9687		ctsio->be_move_done = ctl_config_move_done;
9688		ctl_datamove((union ctl_io *)ctsio);
9689
9690		return (CTL_RETVAL_COMPLETE);
9691	}
9692
9693no_sense:
9694
9695	/*
9696	 * No sense information to report, so we report that everything is
9697	 * okay.
9698	 */
9699	ctl_set_sense_data(sense_ptr,
9700			   lun,
9701			   sense_format,
9702			   /*current_error*/ 1,
9703			   /*sense_key*/ SSD_KEY_NO_SENSE,
9704			   /*asc*/ 0x00,
9705			   /*ascq*/ 0x00,
9706			   SSD_ELEM_NONE);
9707
9708	ctsio->scsi_status = SCSI_STATUS_OK;
9709
9710	/*
9711	 * We report 0 for the sense length, because we aren't doing
9712	 * autosense in this case.  We're reporting sense as parameter data.
9713	 */
9714	ctsio->sense_len = 0;
9715	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9716	ctsio->be_move_done = ctl_config_move_done;
9717	ctl_datamove((union ctl_io *)ctsio);
9718
9719	return (CTL_RETVAL_COMPLETE);
9720}
9721
9722int
9723ctl_tur(struct ctl_scsiio *ctsio)
9724{
9725	struct ctl_lun *lun;
9726
9727	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9728
9729	CTL_DEBUG_PRINT(("ctl_tur\n"));
9730
9731	if (lun == NULL)
9732		return (EINVAL);
9733
9734	ctsio->scsi_status = SCSI_STATUS_OK;
9735	ctsio->io_hdr.status = CTL_SUCCESS;
9736
9737	ctl_done((union ctl_io *)ctsio);
9738
9739	return (CTL_RETVAL_COMPLETE);
9740}
9741
9742#ifdef notyet
9743static int
9744ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9745{
9746
9747}
9748#endif
9749
9750static int
9751ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9752{
9753	struct scsi_vpd_supported_pages *pages;
9754	int sup_page_size;
9755	struct ctl_lun *lun;
9756
9757	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9758
9759	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9760	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9761	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9762	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9763	ctsio->kern_sg_entries = 0;
9764
9765	if (sup_page_size < alloc_len) {
9766		ctsio->residual = alloc_len - sup_page_size;
9767		ctsio->kern_data_len = sup_page_size;
9768		ctsio->kern_total_len = sup_page_size;
9769	} else {
9770		ctsio->residual = 0;
9771		ctsio->kern_data_len = alloc_len;
9772		ctsio->kern_total_len = alloc_len;
9773	}
9774	ctsio->kern_data_resid = 0;
9775	ctsio->kern_rel_offset = 0;
9776	ctsio->kern_sg_entries = 0;
9777
9778	/*
9779	 * The control device is always connected.  The disk device, on the
9780	 * other hand, may not be online all the time.  Need to change this
9781	 * to figure out whether the disk device is actually online or not.
9782	 */
9783	if (lun != NULL)
9784		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9785				lun->be_lun->lun_type;
9786	else
9787		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9788
9789	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9790	/* Supported VPD pages */
9791	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9792	/* Serial Number */
9793	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9794	/* Device Identification */
9795	pages->page_list[2] = SVPD_DEVICE_ID;
9796	/* SCSI Ports */
9797	pages->page_list[3] = SVPD_SCSI_PORTS;
9798	/* Block limits */
9799	pages->page_list[4] = SVPD_BLOCK_LIMITS;
9800	/* Logical Block Provisioning */
9801	pages->page_list[5] = SVPD_LBP;
9802
9803	ctsio->scsi_status = SCSI_STATUS_OK;
9804
9805	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9806	ctsio->be_move_done = ctl_config_move_done;
9807	ctl_datamove((union ctl_io *)ctsio);
9808
9809	return (CTL_RETVAL_COMPLETE);
9810}
9811
9812static int
9813ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9814{
9815	struct scsi_vpd_unit_serial_number *sn_ptr;
9816	struct ctl_lun *lun;
9817
9818	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9819
9820	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9821	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9822	ctsio->kern_sg_entries = 0;
9823
9824	if (sizeof(*sn_ptr) < alloc_len) {
9825		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9826		ctsio->kern_data_len = sizeof(*sn_ptr);
9827		ctsio->kern_total_len = sizeof(*sn_ptr);
9828	} else {
9829		ctsio->residual = 0;
9830		ctsio->kern_data_len = alloc_len;
9831		ctsio->kern_total_len = alloc_len;
9832	}
9833	ctsio->kern_data_resid = 0;
9834	ctsio->kern_rel_offset = 0;
9835	ctsio->kern_sg_entries = 0;
9836
9837	/*
9838	 * The control device is always connected.  The disk device, on the
9839	 * other hand, may not be online all the time.  Need to change this
9840	 * to figure out whether the disk device is actually online or not.
9841	 */
9842	if (lun != NULL)
9843		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9844				  lun->be_lun->lun_type;
9845	else
9846		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9847
9848	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9849	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9850	/*
9851	 * If we don't have a LUN, we just leave the serial number as
9852	 * all spaces.
9853	 */
9854	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9855	if (lun != NULL) {
9856		strncpy((char *)sn_ptr->serial_num,
9857			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9858	}
9859	ctsio->scsi_status = SCSI_STATUS_OK;
9860
9861	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9862	ctsio->be_move_done = ctl_config_move_done;
9863	ctl_datamove((union ctl_io *)ctsio);
9864
9865	return (CTL_RETVAL_COMPLETE);
9866}
9867
9868
9869static int
9870ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9871{
9872	struct scsi_vpd_device_id *devid_ptr;
9873	struct scsi_vpd_id_descriptor *desc;
9874	struct ctl_softc *ctl_softc;
9875	struct ctl_lun *lun;
9876	struct ctl_port *port;
9877	int data_len;
9878	uint8_t proto;
9879
9880	ctl_softc = control_softc;
9881
9882	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9884
9885	data_len = sizeof(struct scsi_vpd_device_id) +
9886	    sizeof(struct scsi_vpd_id_descriptor) +
9887		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9888	    sizeof(struct scsi_vpd_id_descriptor) +
9889		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9890	if (lun && lun->lun_devid)
9891		data_len += lun->lun_devid->len;
9892	if (port->port_devid)
9893		data_len += port->port_devid->len;
9894	if (port->target_devid)
9895		data_len += port->target_devid->len;
9896
9897	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9898	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9899	ctsio->kern_sg_entries = 0;
9900
9901	if (data_len < alloc_len) {
9902		ctsio->residual = alloc_len - data_len;
9903		ctsio->kern_data_len = data_len;
9904		ctsio->kern_total_len = data_len;
9905	} else {
9906		ctsio->residual = 0;
9907		ctsio->kern_data_len = alloc_len;
9908		ctsio->kern_total_len = alloc_len;
9909	}
9910	ctsio->kern_data_resid = 0;
9911	ctsio->kern_rel_offset = 0;
9912	ctsio->kern_sg_entries = 0;
9913
9914	/*
9915	 * The control device is always connected.  The disk device, on the
9916	 * other hand, may not be online all the time.
9917	 */
9918	if (lun != NULL)
9919		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9920				     lun->be_lun->lun_type;
9921	else
9922		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9923	devid_ptr->page_code = SVPD_DEVICE_ID;
9924	scsi_ulto2b(data_len - 4, devid_ptr->length);
9925
9926	if (port->port_type == CTL_PORT_FC)
9927		proto = SCSI_PROTO_FC << 4;
9928	else if (port->port_type == CTL_PORT_ISCSI)
9929		proto = SCSI_PROTO_ISCSI << 4;
9930	else
9931		proto = SCSI_PROTO_SPI << 4;
9932	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9933
9934	/*
9935	 * We're using a LUN association here.  i.e., this device ID is a
9936	 * per-LUN identifier.
9937	 */
9938	if (lun && lun->lun_devid) {
9939		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9940		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9941		    lun->lun_devid->len);
9942	}
9943
9944	/*
9945	 * This is for the WWPN which is a port association.
9946	 */
9947	if (port->port_devid) {
9948		memcpy(desc, port->port_devid->data, port->port_devid->len);
9949		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9950		    port->port_devid->len);
9951	}
9952
9953	/*
9954	 * This is for the Relative Target Port(type 4h) identifier
9955	 */
9956	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9957	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9958	    SVPD_ID_TYPE_RELTARG;
9959	desc->length = 4;
9960	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9961	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9962	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9963
9964	/*
9965	 * This is for the Target Port Group(type 5h) identifier
9966	 */
9967	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9968	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9969	    SVPD_ID_TYPE_TPORTGRP;
9970	desc->length = 4;
9971	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9972	    &desc->identifier[2]);
9973	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9974	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9975
9976	/*
9977	 * This is for the Target identifier
9978	 */
9979	if (port->target_devid) {
9980		memcpy(desc, port->target_devid->data, port->target_devid->len);
9981	}
9982
9983	ctsio->scsi_status = SCSI_STATUS_OK;
9984	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9985	ctsio->be_move_done = ctl_config_move_done;
9986	ctl_datamove((union ctl_io *)ctsio);
9987
9988	return (CTL_RETVAL_COMPLETE);
9989}
9990
9991static int
9992ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9993{
9994	struct ctl_softc *softc = control_softc;
9995	struct scsi_vpd_scsi_ports *sp;
9996	struct scsi_vpd_port_designation *pd;
9997	struct scsi_vpd_port_designation_cont *pdc;
9998	struct ctl_lun *lun;
9999	struct ctl_port *port;
10000	int data_len, num_target_ports, id_len, g, pg, p;
10001	int num_target_port_groups, single;
10002
10003	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10004
10005	single = ctl_is_single;
10006	if (single)
10007		num_target_port_groups = 1;
10008	else
10009		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10010	num_target_ports = 0;
10011	id_len = 0;
10012	mtx_lock(&softc->ctl_lock);
10013	STAILQ_FOREACH(port, &softc->port_list, links) {
10014		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10015			continue;
10016		if (ctl_map_lun_back(port->targ_port, lun->lun) >=
10017		    CTL_MAX_LUNS)
10018			continue;
10019		num_target_ports++;
10020		if (port->port_devid)
10021			id_len += port->port_devid->len;
10022	}
10023	mtx_unlock(&softc->ctl_lock);
10024
10025	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10026	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10027	     sizeof(struct scsi_vpd_port_designation_cont)) + id_len;
10028	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10029	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10030	ctsio->kern_sg_entries = 0;
10031
10032	if (data_len < alloc_len) {
10033		ctsio->residual = alloc_len - data_len;
10034		ctsio->kern_data_len = data_len;
10035		ctsio->kern_total_len = data_len;
10036	} else {
10037		ctsio->residual = 0;
10038		ctsio->kern_data_len = alloc_len;
10039		ctsio->kern_total_len = alloc_len;
10040	}
10041	ctsio->kern_data_resid = 0;
10042	ctsio->kern_rel_offset = 0;
10043	ctsio->kern_sg_entries = 0;
10044
10045	/*
10046	 * The control device is always connected.  The disk device, on the
10047	 * other hand, may not be online all the time.  Need to change this
10048	 * to figure out whether the disk device is actually online or not.
10049	 */
10050	if (lun != NULL)
10051		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10052				  lun->be_lun->lun_type;
10053	else
10054		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10055
10056	sp->page_code = SVPD_SCSI_PORTS;
10057	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10058	    sp->page_length);
10059	pd = &sp->design[0];
10060
10061	mtx_lock(&softc->ctl_lock);
10062	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10063		pg = 0;
10064	else
10065		pg = 1;
10066	for (g = 0; g < num_target_port_groups; g++) {
10067		STAILQ_FOREACH(port, &softc->port_list, links) {
10068			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10069				continue;
10070			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
10071			    CTL_MAX_LUNS)
10072				continue;
10073			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10074			scsi_ulto2b(p, pd->relative_port_id);
10075			scsi_ulto2b(0, pd->initiator_transportid_length);
10076			pdc = (struct scsi_vpd_port_designation_cont *)
10077			    &pd->initiator_transportid[0];
10078			if (port->port_devid && g == pg) {
10079				id_len = port->port_devid->len;
10080				scsi_ulto2b(port->port_devid->len,
10081				    pdc->target_port_descriptors_length);
10082				memcpy(pdc->target_port_descriptors,
10083				    port->port_devid->data, port->port_devid->len);
10084			} else {
10085				id_len = 0;
10086				scsi_ulto2b(0, pdc->target_port_descriptors_length);
10087			}
10088			pd = (struct scsi_vpd_port_designation *)
10089			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10090		}
10091	}
10092	mtx_unlock(&softc->ctl_lock);
10093
10094	ctsio->scsi_status = SCSI_STATUS_OK;
10095	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10096	ctsio->be_move_done = ctl_config_move_done;
10097	ctl_datamove((union ctl_io *)ctsio);
10098
10099	return (CTL_RETVAL_COMPLETE);
10100}
10101
10102static int
10103ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10104{
10105	struct scsi_vpd_block_limits *bl_ptr;
10106	struct ctl_lun *lun;
10107	int bs;
10108
10109	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10110	bs = lun->be_lun->blocksize;
10111
10112	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10113	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10114	ctsio->kern_sg_entries = 0;
10115
10116	if (sizeof(*bl_ptr) < alloc_len) {
10117		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10118		ctsio->kern_data_len = sizeof(*bl_ptr);
10119		ctsio->kern_total_len = sizeof(*bl_ptr);
10120	} else {
10121		ctsio->residual = 0;
10122		ctsio->kern_data_len = alloc_len;
10123		ctsio->kern_total_len = alloc_len;
10124	}
10125	ctsio->kern_data_resid = 0;
10126	ctsio->kern_rel_offset = 0;
10127	ctsio->kern_sg_entries = 0;
10128
10129	/*
10130	 * The control device is always connected.  The disk device, on the
10131	 * other hand, may not be online all the time.  Need to change this
10132	 * to figure out whether the disk device is actually online or not.
10133	 */
10134	if (lun != NULL)
10135		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10136				  lun->be_lun->lun_type;
10137	else
10138		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10139
10140	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10141	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10142	bl_ptr->max_cmp_write_len = 0xff;
10143	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10144	scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10145	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10146		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10147		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10148	}
10149	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10150
10151	ctsio->scsi_status = SCSI_STATUS_OK;
10152	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10153	ctsio->be_move_done = ctl_config_move_done;
10154	ctl_datamove((union ctl_io *)ctsio);
10155
10156	return (CTL_RETVAL_COMPLETE);
10157}
10158
10159static int
10160ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10161{
10162	struct scsi_vpd_logical_block_prov *lbp_ptr;
10163	struct ctl_lun *lun;
10164	int bs;
10165
10166	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10167	bs = lun->be_lun->blocksize;
10168
10169	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10170	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10171	ctsio->kern_sg_entries = 0;
10172
10173	if (sizeof(*lbp_ptr) < alloc_len) {
10174		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10175		ctsio->kern_data_len = sizeof(*lbp_ptr);
10176		ctsio->kern_total_len = sizeof(*lbp_ptr);
10177	} else {
10178		ctsio->residual = 0;
10179		ctsio->kern_data_len = alloc_len;
10180		ctsio->kern_total_len = alloc_len;
10181	}
10182	ctsio->kern_data_resid = 0;
10183	ctsio->kern_rel_offset = 0;
10184	ctsio->kern_sg_entries = 0;
10185
10186	/*
10187	 * The control device is always connected.  The disk device, on the
10188	 * other hand, may not be online all the time.  Need to change this
10189	 * to figure out whether the disk device is actually online or not.
10190	 */
10191	if (lun != NULL)
10192		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10193				  lun->be_lun->lun_type;
10194	else
10195		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10196
10197	lbp_ptr->page_code = SVPD_LBP;
10198	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10199		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10200
10201	ctsio->scsi_status = SCSI_STATUS_OK;
10202	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10203	ctsio->be_move_done = ctl_config_move_done;
10204	ctl_datamove((union ctl_io *)ctsio);
10205
10206	return (CTL_RETVAL_COMPLETE);
10207}
10208
10209static int
10210ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10211{
10212	struct scsi_inquiry *cdb;
10213	struct ctl_lun *lun;
10214	int alloc_len, retval;
10215
10216	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10217	cdb = (struct scsi_inquiry *)ctsio->cdb;
10218
10219	retval = CTL_RETVAL_COMPLETE;
10220
10221	alloc_len = scsi_2btoul(cdb->length);
10222
10223	switch (cdb->page_code) {
10224	case SVPD_SUPPORTED_PAGES:
10225		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10226		break;
10227	case SVPD_UNIT_SERIAL_NUMBER:
10228		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10229		break;
10230	case SVPD_DEVICE_ID:
10231		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10232		break;
10233	case SVPD_SCSI_PORTS:
10234		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10235		break;
10236	case SVPD_BLOCK_LIMITS:
10237		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10238		break;
10239	case SVPD_LBP:
10240		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10241		break;
10242	default:
10243		ctl_set_invalid_field(ctsio,
10244				      /*sks_valid*/ 1,
10245				      /*command*/ 1,
10246				      /*field*/ 2,
10247				      /*bit_valid*/ 0,
10248				      /*bit*/ 0);
10249		ctl_done((union ctl_io *)ctsio);
10250		retval = CTL_RETVAL_COMPLETE;
10251		break;
10252	}
10253
10254	return (retval);
10255}
10256
10257static int
10258ctl_inquiry_std(struct ctl_scsiio *ctsio)
10259{
10260	struct scsi_inquiry_data *inq_ptr;
10261	struct scsi_inquiry *cdb;
10262	struct ctl_softc *ctl_softc;
10263	struct ctl_lun *lun;
10264	char *val;
10265	uint32_t alloc_len;
10266	int is_fc;
10267
10268	ctl_softc = control_softc;
10269
10270	/*
10271	 * Figure out whether we're talking to a Fibre Channel port or not.
10272	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10273	 * SCSI front ends.
10274	 */
10275	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
10276	    CTL_PORT_FC)
10277		is_fc = 0;
10278	else
10279		is_fc = 1;
10280
10281	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10282	cdb = (struct scsi_inquiry *)ctsio->cdb;
10283	alloc_len = scsi_2btoul(cdb->length);
10284
10285	/*
10286	 * We malloc the full inquiry data size here and fill it
10287	 * in.  If the user only asks for less, we'll give him
10288	 * that much.
10289	 */
10290	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10291	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10292	ctsio->kern_sg_entries = 0;
10293	ctsio->kern_data_resid = 0;
10294	ctsio->kern_rel_offset = 0;
10295
10296	if (sizeof(*inq_ptr) < alloc_len) {
10297		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10298		ctsio->kern_data_len = sizeof(*inq_ptr);
10299		ctsio->kern_total_len = sizeof(*inq_ptr);
10300	} else {
10301		ctsio->residual = 0;
10302		ctsio->kern_data_len = alloc_len;
10303		ctsio->kern_total_len = alloc_len;
10304	}
10305
10306	/*
10307	 * If we have a LUN configured, report it as connected.  Otherwise,
10308	 * report that it is offline or no device is supported, depending
10309	 * on the value of inquiry_pq_no_lun.
10310	 *
10311	 * According to the spec (SPC-4 r34), the peripheral qualifier
10312	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10313	 *
10314	 * "A peripheral device having the specified peripheral device type
10315	 * is not connected to this logical unit. However, the device
10316	 * server is capable of supporting the specified peripheral device
10317	 * type on this logical unit."
10318	 *
10319	 * According to the same spec, the peripheral qualifier
10320	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10321	 *
10322	 * "The device server is not capable of supporting a peripheral
10323	 * device on this logical unit. For this peripheral qualifier the
10324	 * peripheral device type shall be set to 1Fh. All other peripheral
10325	 * device type values are reserved for this peripheral qualifier."
10326	 *
10327	 * Given the text, it would seem that we probably want to report that
10328	 * the LUN is offline here.  There is no LUN connected, but we can
10329	 * support a LUN at the given LUN number.
10330	 *
10331	 * In the real world, though, it sounds like things are a little
10332	 * different:
10333	 *
10334	 * - Linux, when presented with a LUN with the offline peripheral
10335	 *   qualifier, will create an sg driver instance for it.  So when
10336	 *   you attach it to CTL, you wind up with a ton of sg driver
10337	 *   instances.  (One for every LUN that Linux bothered to probe.)
10338	 *   Linux does this despite the fact that it issues a REPORT LUNs
10339	 *   to LUN 0 to get the inventory of supported LUNs.
10340	 *
10341	 * - There is other anecdotal evidence (from Emulex folks) about
10342	 *   arrays that use the offline peripheral qualifier for LUNs that
10343	 *   are on the "passive" path in an active/passive array.
10344	 *
10345	 * So the solution is provide a hopefully reasonable default
10346	 * (return bad/no LUN) and allow the user to change the behavior
10347	 * with a tunable/sysctl variable.
10348	 */
10349	if (lun != NULL)
10350		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10351				  lun->be_lun->lun_type;
10352	else if (ctl_softc->inquiry_pq_no_lun == 0)
10353		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10354	else
10355		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10356
10357	/* RMB in byte 2 is 0 */
10358	inq_ptr->version = SCSI_REV_SPC3;
10359
10360	/*
10361	 * According to SAM-3, even if a device only supports a single
10362	 * level of LUN addressing, it should still set the HISUP bit:
10363	 *
10364	 * 4.9.1 Logical unit numbers overview
10365	 *
10366	 * All logical unit number formats described in this standard are
10367	 * hierarchical in structure even when only a single level in that
10368	 * hierarchy is used. The HISUP bit shall be set to one in the
10369	 * standard INQUIRY data (see SPC-2) when any logical unit number
10370	 * format described in this standard is used.  Non-hierarchical
10371	 * formats are outside the scope of this standard.
10372	 *
10373	 * Therefore we set the HiSup bit here.
10374	 *
10375	 * The reponse format is 2, per SPC-3.
10376	 */
10377	inq_ptr->response_format = SID_HiSup | 2;
10378
10379	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10380	CTL_DEBUG_PRINT(("additional_length = %d\n",
10381			 inq_ptr->additional_length));
10382
10383	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
10384	/* 16 bit addressing */
10385	if (is_fc == 0)
10386		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10387	/* XXX set the SID_MultiP bit here if we're actually going to
10388	   respond on multiple ports */
10389	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10390
10391	/* 16 bit data bus, synchronous transfers */
10392	/* XXX these flags don't apply for FC */
10393	if (is_fc == 0)
10394		inq_ptr->flags = SID_WBus16 | SID_Sync;
10395	/*
10396	 * XXX KDM do we want to support tagged queueing on the control
10397	 * device at all?
10398	 */
10399	if ((lun == NULL)
10400	 || (lun->be_lun->lun_type != T_PROCESSOR))
10401		inq_ptr->flags |= SID_CmdQue;
10402	/*
10403	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10404	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10405	 * name and 4 bytes for the revision.
10406	 */
10407	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10408	    "vendor")) == NULL) {
10409		strcpy(inq_ptr->vendor, CTL_VENDOR);
10410	} else {
10411		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10412		strncpy(inq_ptr->vendor, val,
10413		    min(sizeof(inq_ptr->vendor), strlen(val)));
10414	}
10415	if (lun == NULL) {
10416		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10417	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10418		switch (lun->be_lun->lun_type) {
10419		case T_DIRECT:
10420			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10421			break;
10422		case T_PROCESSOR:
10423			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10424			break;
10425		default:
10426			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10427			break;
10428		}
10429	} else {
10430		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10431		strncpy(inq_ptr->product, val,
10432		    min(sizeof(inq_ptr->product), strlen(val)));
10433	}
10434
10435	/*
10436	 * XXX make this a macro somewhere so it automatically gets
10437	 * incremented when we make changes.
10438	 */
10439	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10440	    "revision")) == NULL) {
10441		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10442	} else {
10443		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10444		strncpy(inq_ptr->revision, val,
10445		    min(sizeof(inq_ptr->revision), strlen(val)));
10446	}
10447
10448	/*
10449	 * For parallel SCSI, we support double transition and single
10450	 * transition clocking.  We also support QAS (Quick Arbitration
10451	 * and Selection) and Information Unit transfers on both the
10452	 * control and array devices.
10453	 */
10454	if (is_fc == 0)
10455		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10456				    SID_SPI_IUS;
10457
10458	/* SAM-3 */
10459	scsi_ulto2b(0x0060, inq_ptr->version1);
10460	/* SPC-3 (no version claimed) XXX should we claim a version? */
10461	scsi_ulto2b(0x0300, inq_ptr->version2);
10462	if (is_fc) {
10463		/* FCP-2 ANSI INCITS.350:2003 */
10464		scsi_ulto2b(0x0917, inq_ptr->version3);
10465	} else {
10466		/* SPI-4 ANSI INCITS.362:200x */
10467		scsi_ulto2b(0x0B56, inq_ptr->version3);
10468	}
10469
10470	if (lun == NULL) {
10471		/* SBC-2 (no version claimed) XXX should we claim a version? */
10472		scsi_ulto2b(0x0320, inq_ptr->version4);
10473	} else {
10474		switch (lun->be_lun->lun_type) {
10475		case T_DIRECT:
10476			/*
10477			 * SBC-2 (no version claimed) XXX should we claim a
10478			 * version?
10479			 */
10480			scsi_ulto2b(0x0320, inq_ptr->version4);
10481			break;
10482		case T_PROCESSOR:
10483		default:
10484			break;
10485		}
10486	}
10487
10488	ctsio->scsi_status = SCSI_STATUS_OK;
10489	if (ctsio->kern_data_len > 0) {
10490		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10491		ctsio->be_move_done = ctl_config_move_done;
10492		ctl_datamove((union ctl_io *)ctsio);
10493	} else {
10494		ctsio->io_hdr.status = CTL_SUCCESS;
10495		ctl_done((union ctl_io *)ctsio);
10496	}
10497
10498	return (CTL_RETVAL_COMPLETE);
10499}
10500
10501int
10502ctl_inquiry(struct ctl_scsiio *ctsio)
10503{
10504	struct scsi_inquiry *cdb;
10505	int retval;
10506
10507	cdb = (struct scsi_inquiry *)ctsio->cdb;
10508
10509	retval = 0;
10510
10511	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10512
10513	/*
10514	 * Right now, we don't support the CmdDt inquiry information.
10515	 * This would be nice to support in the future.  When we do
10516	 * support it, we should change this test so that it checks to make
10517	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10518	 */
10519#ifdef notyet
10520	if (((cdb->byte2 & SI_EVPD)
10521	 && (cdb->byte2 & SI_CMDDT)))
10522#endif
10523	if (cdb->byte2 & SI_CMDDT) {
10524		/*
10525		 * Point to the SI_CMDDT bit.  We might change this
10526		 * when we support SI_CMDDT, but since both bits would be
10527		 * "wrong", this should probably just stay as-is then.
10528		 */
10529		ctl_set_invalid_field(ctsio,
10530				      /*sks_valid*/ 1,
10531				      /*command*/ 1,
10532				      /*field*/ 1,
10533				      /*bit_valid*/ 1,
10534				      /*bit*/ 1);
10535		ctl_done((union ctl_io *)ctsio);
10536		return (CTL_RETVAL_COMPLETE);
10537	}
10538	if (cdb->byte2 & SI_EVPD)
10539		retval = ctl_inquiry_evpd(ctsio);
10540#ifdef notyet
10541	else if (cdb->byte2 & SI_CMDDT)
10542		retval = ctl_inquiry_cmddt(ctsio);
10543#endif
10544	else
10545		retval = ctl_inquiry_std(ctsio);
10546
10547	return (retval);
10548}
10549
10550/*
10551 * For known CDB types, parse the LBA and length.
10552 */
10553static int
10554ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10555{
10556	if (io->io_hdr.io_type != CTL_IO_SCSI)
10557		return (1);
10558
10559	switch (io->scsiio.cdb[0]) {
10560	case COMPARE_AND_WRITE: {
10561		struct scsi_compare_and_write *cdb;
10562
10563		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10564
10565		*lba = scsi_8btou64(cdb->addr);
10566		*len = cdb->length;
10567		break;
10568	}
10569	case READ_6:
10570	case WRITE_6: {
10571		struct scsi_rw_6 *cdb;
10572
10573		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10574
10575		*lba = scsi_3btoul(cdb->addr);
10576		/* only 5 bits are valid in the most significant address byte */
10577		*lba &= 0x1fffff;
10578		*len = cdb->length;
10579		break;
10580	}
10581	case READ_10:
10582	case WRITE_10: {
10583		struct scsi_rw_10 *cdb;
10584
10585		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10586
10587		*lba = scsi_4btoul(cdb->addr);
10588		*len = scsi_2btoul(cdb->length);
10589		break;
10590	}
10591	case WRITE_VERIFY_10: {
10592		struct scsi_write_verify_10 *cdb;
10593
10594		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10595
10596		*lba = scsi_4btoul(cdb->addr);
10597		*len = scsi_2btoul(cdb->length);
10598		break;
10599	}
10600	case READ_12:
10601	case WRITE_12: {
10602		struct scsi_rw_12 *cdb;
10603
10604		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10605
10606		*lba = scsi_4btoul(cdb->addr);
10607		*len = scsi_4btoul(cdb->length);
10608		break;
10609	}
10610	case WRITE_VERIFY_12: {
10611		struct scsi_write_verify_12 *cdb;
10612
10613		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10614
10615		*lba = scsi_4btoul(cdb->addr);
10616		*len = scsi_4btoul(cdb->length);
10617		break;
10618	}
10619	case READ_16:
10620	case WRITE_16: {
10621		struct scsi_rw_16 *cdb;
10622
10623		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10624
10625		*lba = scsi_8btou64(cdb->addr);
10626		*len = scsi_4btoul(cdb->length);
10627		break;
10628	}
10629	case WRITE_VERIFY_16: {
10630		struct scsi_write_verify_16 *cdb;
10631
10632		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10633
10634
10635		*lba = scsi_8btou64(cdb->addr);
10636		*len = scsi_4btoul(cdb->length);
10637		break;
10638	}
10639	case WRITE_SAME_10: {
10640		struct scsi_write_same_10 *cdb;
10641
10642		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10643
10644		*lba = scsi_4btoul(cdb->addr);
10645		*len = scsi_2btoul(cdb->length);
10646		break;
10647	}
10648	case WRITE_SAME_16: {
10649		struct scsi_write_same_16 *cdb;
10650
10651		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10652
10653		*lba = scsi_8btou64(cdb->addr);
10654		*len = scsi_4btoul(cdb->length);
10655		break;
10656	}
10657	case VERIFY_10: {
10658		struct scsi_verify_10 *cdb;
10659
10660		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10661
10662		*lba = scsi_4btoul(cdb->addr);
10663		*len = scsi_2btoul(cdb->length);
10664		break;
10665	}
10666	case VERIFY_12: {
10667		struct scsi_verify_12 *cdb;
10668
10669		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10670
10671		*lba = scsi_4btoul(cdb->addr);
10672		*len = scsi_4btoul(cdb->length);
10673		break;
10674	}
10675	case VERIFY_16: {
10676		struct scsi_verify_16 *cdb;
10677
10678		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10679
10680		*lba = scsi_8btou64(cdb->addr);
10681		*len = scsi_4btoul(cdb->length);
10682		break;
10683	}
10684	default:
10685		return (1);
10686		break; /* NOTREACHED */
10687	}
10688
10689	return (0);
10690}
10691
10692static ctl_action
10693ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10694{
10695	uint64_t endlba1, endlba2;
10696
10697	endlba1 = lba1 + len1 - 1;
10698	endlba2 = lba2 + len2 - 1;
10699
10700	if ((endlba1 < lba2)
10701	 || (endlba2 < lba1))
10702		return (CTL_ACTION_PASS);
10703	else
10704		return (CTL_ACTION_BLOCK);
10705}
10706
10707static ctl_action
10708ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10709{
10710	uint64_t lba1, lba2;
10711	uint32_t len1, len2;
10712	int retval;
10713
10714	retval = ctl_get_lba_len(io1, &lba1, &len1);
10715	if (retval != 0)
10716		return (CTL_ACTION_ERROR);
10717
10718	retval = ctl_get_lba_len(io2, &lba2, &len2);
10719	if (retval != 0)
10720		return (CTL_ACTION_ERROR);
10721
10722	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10723}
10724
10725static ctl_action
10726ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10727{
10728	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10729	ctl_serialize_action *serialize_row;
10730
10731	/*
10732	 * The initiator attempted multiple untagged commands at the same
10733	 * time.  Can't do that.
10734	 */
10735	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10736	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10737	 && ((pending_io->io_hdr.nexus.targ_port ==
10738	      ooa_io->io_hdr.nexus.targ_port)
10739	  && (pending_io->io_hdr.nexus.initid.id ==
10740	      ooa_io->io_hdr.nexus.initid.id))
10741	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10742		return (CTL_ACTION_OVERLAP);
10743
10744	/*
10745	 * The initiator attempted to send multiple tagged commands with
10746	 * the same ID.  (It's fine if different initiators have the same
10747	 * tag ID.)
10748	 *
10749	 * Even if all of those conditions are true, we don't kill the I/O
10750	 * if the command ahead of us has been aborted.  We won't end up
10751	 * sending it to the FETD, and it's perfectly legal to resend a
10752	 * command with the same tag number as long as the previous
10753	 * instance of this tag number has been aborted somehow.
10754	 */
10755	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10756	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10757	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10758	 && ((pending_io->io_hdr.nexus.targ_port ==
10759	      ooa_io->io_hdr.nexus.targ_port)
10760	  && (pending_io->io_hdr.nexus.initid.id ==
10761	      ooa_io->io_hdr.nexus.initid.id))
10762	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10763		return (CTL_ACTION_OVERLAP_TAG);
10764
10765	/*
10766	 * If we get a head of queue tag, SAM-3 says that we should
10767	 * immediately execute it.
10768	 *
10769	 * What happens if this command would normally block for some other
10770	 * reason?  e.g. a request sense with a head of queue tag
10771	 * immediately after a write.  Normally that would block, but this
10772	 * will result in its getting executed immediately...
10773	 *
10774	 * We currently return "pass" instead of "skip", so we'll end up
10775	 * going through the rest of the queue to check for overlapped tags.
10776	 *
10777	 * XXX KDM check for other types of blockage first??
10778	 */
10779	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10780		return (CTL_ACTION_PASS);
10781
10782	/*
10783	 * Ordered tags have to block until all items ahead of them
10784	 * have completed.  If we get called with an ordered tag, we always
10785	 * block, if something else is ahead of us in the queue.
10786	 */
10787	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10788		return (CTL_ACTION_BLOCK);
10789
10790	/*
10791	 * Simple tags get blocked until all head of queue and ordered tags
10792	 * ahead of them have completed.  I'm lumping untagged commands in
10793	 * with simple tags here.  XXX KDM is that the right thing to do?
10794	 */
10795	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10796	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10797	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10798	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10799		return (CTL_ACTION_BLOCK);
10800
10801	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10802	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10803
10804	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10805
10806	switch (serialize_row[pending_entry->seridx]) {
10807	case CTL_SER_BLOCK:
10808		return (CTL_ACTION_BLOCK);
10809		break; /* NOTREACHED */
10810	case CTL_SER_EXTENT:
10811		return (ctl_extent_check(pending_io, ooa_io));
10812		break; /* NOTREACHED */
10813	case CTL_SER_PASS:
10814		return (CTL_ACTION_PASS);
10815		break; /* NOTREACHED */
10816	case CTL_SER_SKIP:
10817		return (CTL_ACTION_SKIP);
10818		break;
10819	default:
10820		panic("invalid serialization value %d",
10821		      serialize_row[pending_entry->seridx]);
10822		break; /* NOTREACHED */
10823	}
10824
10825	return (CTL_ACTION_ERROR);
10826}
10827
10828/*
10829 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10830 * Assumptions:
10831 * - pending_io is generally either incoming, or on the blocked queue
10832 * - starting I/O is the I/O we want to start the check with.
10833 */
10834static ctl_action
10835ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10836	      union ctl_io *starting_io)
10837{
10838	union ctl_io *ooa_io;
10839	ctl_action action;
10840
10841	mtx_assert(&lun->lun_lock, MA_OWNED);
10842
10843	/*
10844	 * Run back along the OOA queue, starting with the current
10845	 * blocked I/O and going through every I/O before it on the
10846	 * queue.  If starting_io is NULL, we'll just end up returning
10847	 * CTL_ACTION_PASS.
10848	 */
10849	for (ooa_io = starting_io; ooa_io != NULL;
10850	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10851	     ooa_links)){
10852
10853		/*
10854		 * This routine just checks to see whether
10855		 * cur_blocked is blocked by ooa_io, which is ahead
10856		 * of it in the queue.  It doesn't queue/dequeue
10857		 * cur_blocked.
10858		 */
10859		action = ctl_check_for_blockage(pending_io, ooa_io);
10860		switch (action) {
10861		case CTL_ACTION_BLOCK:
10862		case CTL_ACTION_OVERLAP:
10863		case CTL_ACTION_OVERLAP_TAG:
10864		case CTL_ACTION_SKIP:
10865		case CTL_ACTION_ERROR:
10866			return (action);
10867			break; /* NOTREACHED */
10868		case CTL_ACTION_PASS:
10869			break;
10870		default:
10871			panic("invalid action %d", action);
10872			break;  /* NOTREACHED */
10873		}
10874	}
10875
10876	return (CTL_ACTION_PASS);
10877}
10878
10879/*
10880 * Assumptions:
10881 * - An I/O has just completed, and has been removed from the per-LUN OOA
10882 *   queue, so some items on the blocked queue may now be unblocked.
10883 */
10884static int
10885ctl_check_blocked(struct ctl_lun *lun)
10886{
10887	union ctl_io *cur_blocked, *next_blocked;
10888
10889	mtx_assert(&lun->lun_lock, MA_OWNED);
10890
10891	/*
10892	 * Run forward from the head of the blocked queue, checking each
10893	 * entry against the I/Os prior to it on the OOA queue to see if
10894	 * there is still any blockage.
10895	 *
10896	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10897	 * with our removing a variable on it while it is traversing the
10898	 * list.
10899	 */
10900	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10901	     cur_blocked != NULL; cur_blocked = next_blocked) {
10902		union ctl_io *prev_ooa;
10903		ctl_action action;
10904
10905		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10906							  blocked_links);
10907
10908		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10909						      ctl_ooaq, ooa_links);
10910
10911		/*
10912		 * If cur_blocked happens to be the first item in the OOA
10913		 * queue now, prev_ooa will be NULL, and the action
10914		 * returned will just be CTL_ACTION_PASS.
10915		 */
10916		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10917
10918		switch (action) {
10919		case CTL_ACTION_BLOCK:
10920			/* Nothing to do here, still blocked */
10921			break;
10922		case CTL_ACTION_OVERLAP:
10923		case CTL_ACTION_OVERLAP_TAG:
10924			/*
10925			 * This shouldn't happen!  In theory we've already
10926			 * checked this command for overlap...
10927			 */
10928			break;
10929		case CTL_ACTION_PASS:
10930		case CTL_ACTION_SKIP: {
10931			struct ctl_softc *softc;
10932			const struct ctl_cmd_entry *entry;
10933			uint32_t initidx;
10934			int isc_retval;
10935
10936			/*
10937			 * The skip case shouldn't happen, this transaction
10938			 * should have never made it onto the blocked queue.
10939			 */
10940			/*
10941			 * This I/O is no longer blocked, we can remove it
10942			 * from the blocked queue.  Since this is a TAILQ
10943			 * (doubly linked list), we can do O(1) removals
10944			 * from any place on the list.
10945			 */
10946			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10947				     blocked_links);
10948			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10949
10950			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10951				/*
10952				 * Need to send IO back to original side to
10953				 * run
10954				 */
10955				union ctl_ha_msg msg_info;
10956
10957				msg_info.hdr.original_sc =
10958					cur_blocked->io_hdr.original_sc;
10959				msg_info.hdr.serializing_sc = cur_blocked;
10960				msg_info.hdr.msg_type = CTL_MSG_R2R;
10961				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10962				     &msg_info, sizeof(msg_info), 0)) >
10963				     CTL_HA_STATUS_SUCCESS) {
10964					printf("CTL:Check Blocked error from "
10965					       "ctl_ha_msg_send %d\n",
10966					       isc_retval);
10967				}
10968				break;
10969			}
10970			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10971			softc = control_softc;
10972
10973			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10974
10975			/*
10976			 * Check this I/O for LUN state changes that may
10977			 * have happened while this command was blocked.
10978			 * The LUN state may have been changed by a command
10979			 * ahead of us in the queue, so we need to re-check
10980			 * for any states that can be caused by SCSI
10981			 * commands.
10982			 */
10983			if (ctl_scsiio_lun_check(softc, lun, entry,
10984						 &cur_blocked->scsiio) == 0) {
10985				cur_blocked->io_hdr.flags |=
10986				                      CTL_FLAG_IS_WAS_ON_RTR;
10987				ctl_enqueue_rtr(cur_blocked);
10988			} else
10989				ctl_done(cur_blocked);
10990			break;
10991		}
10992		default:
10993			/*
10994			 * This probably shouldn't happen -- we shouldn't
10995			 * get CTL_ACTION_ERROR, or anything else.
10996			 */
10997			break;
10998		}
10999	}
11000
11001	return (CTL_RETVAL_COMPLETE);
11002}
11003
11004/*
11005 * This routine (with one exception) checks LUN flags that can be set by
11006 * commands ahead of us in the OOA queue.  These flags have to be checked
11007 * when a command initially comes in, and when we pull a command off the
11008 * blocked queue and are preparing to execute it.  The reason we have to
11009 * check these flags for commands on the blocked queue is that the LUN
11010 * state may have been changed by a command ahead of us while we're on the
11011 * blocked queue.
11012 *
11013 * Ordering is somewhat important with these checks, so please pay
11014 * careful attention to the placement of any new checks.
11015 */
11016static int
11017ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11018    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11019{
11020	int retval;
11021
11022	retval = 0;
11023
11024	mtx_assert(&lun->lun_lock, MA_OWNED);
11025
11026	/*
11027	 * If this shelf is a secondary shelf controller, we have to reject
11028	 * any media access commands.
11029	 */
11030#if 0
11031	/* No longer needed for HA */
11032	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11033	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11034		ctl_set_lun_standby(ctsio);
11035		retval = 1;
11036		goto bailout;
11037	}
11038#endif
11039
11040	/*
11041	 * Check for a reservation conflict.  If this command isn't allowed
11042	 * even on reserved LUNs, and if this initiator isn't the one who
11043	 * reserved us, reject the command with a reservation conflict.
11044	 */
11045	if ((lun->flags & CTL_LUN_RESERVED)
11046	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11047		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11048		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11049		 || (ctsio->io_hdr.nexus.targ_target.id !=
11050		     lun->rsv_nexus.targ_target.id)) {
11051			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11052			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11053			retval = 1;
11054			goto bailout;
11055		}
11056	}
11057
11058	if ( (lun->flags & CTL_LUN_PR_RESERVED)
11059	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11060		uint32_t residx;
11061
11062		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11063		/*
11064		 * if we aren't registered or it's a res holder type
11065		 * reservation and this isn't the res holder then set a
11066		 * conflict.
11067		 * NOTE: Commands which might be allowed on write exclusive
11068		 * type reservations are checked in the particular command
11069		 * for a conflict. Read and SSU are the only ones.
11070		 */
11071		if (!lun->per_res[residx].registered
11072		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11073			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11074			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11075			retval = 1;
11076			goto bailout;
11077		}
11078
11079	}
11080
11081	if ((lun->flags & CTL_LUN_OFFLINE)
11082	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11083		ctl_set_lun_not_ready(ctsio);
11084		retval = 1;
11085		goto bailout;
11086	}
11087
11088	/*
11089	 * If the LUN is stopped, see if this particular command is allowed
11090	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11091	 */
11092	if ((lun->flags & CTL_LUN_STOPPED)
11093	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11094		/* "Logical unit not ready, initializing cmd. required" */
11095		ctl_set_lun_stopped(ctsio);
11096		retval = 1;
11097		goto bailout;
11098	}
11099
11100	if ((lun->flags & CTL_LUN_INOPERABLE)
11101	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11102		/* "Medium format corrupted" */
11103		ctl_set_medium_format_corrupted(ctsio);
11104		retval = 1;
11105		goto bailout;
11106	}
11107
11108bailout:
11109	return (retval);
11110
11111}
11112
11113static void
11114ctl_failover_io(union ctl_io *io, int have_lock)
11115{
11116	ctl_set_busy(&io->scsiio);
11117	ctl_done(io);
11118}
11119
11120static void
11121ctl_failover(void)
11122{
11123	struct ctl_lun *lun;
11124	struct ctl_softc *ctl_softc;
11125	union ctl_io *next_io, *pending_io;
11126	union ctl_io *io;
11127	int lun_idx;
11128	int i;
11129
11130	ctl_softc = control_softc;
11131
11132	mtx_lock(&ctl_softc->ctl_lock);
11133	/*
11134	 * Remove any cmds from the other SC from the rtr queue.  These
11135	 * will obviously only be for LUNs for which we're the primary.
11136	 * We can't send status or get/send data for these commands.
11137	 * Since they haven't been executed yet, we can just remove them.
11138	 * We'll either abort them or delete them below, depending on
11139	 * which HA mode we're in.
11140	 */
11141#ifdef notyet
11142	mtx_lock(&ctl_softc->queue_lock);
11143	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11144	     io != NULL; io = next_io) {
11145		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11146		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11147			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11148				      ctl_io_hdr, links);
11149	}
11150	mtx_unlock(&ctl_softc->queue_lock);
11151#endif
11152
11153	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11154		lun = ctl_softc->ctl_luns[lun_idx];
11155		if (lun==NULL)
11156			continue;
11157
11158		/*
11159		 * Processor LUNs are primary on both sides.
11160		 * XXX will this always be true?
11161		 */
11162		if (lun->be_lun->lun_type == T_PROCESSOR)
11163			continue;
11164
11165		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11166		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11167			printf("FAILOVER: primary lun %d\n", lun_idx);
11168		        /*
11169			 * Remove all commands from the other SC. First from the
11170			 * blocked queue then from the ooa queue. Once we have
11171			 * removed them. Call ctl_check_blocked to see if there
11172			 * is anything that can run.
11173			 */
11174			for (io = (union ctl_io *)TAILQ_FIRST(
11175			     &lun->blocked_queue); io != NULL; io = next_io) {
11176
11177		        	next_io = (union ctl_io *)TAILQ_NEXT(
11178				    &io->io_hdr, blocked_links);
11179
11180				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11181					TAILQ_REMOVE(&lun->blocked_queue,
11182						     &io->io_hdr,blocked_links);
11183					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11184					TAILQ_REMOVE(&lun->ooa_queue,
11185						     &io->io_hdr, ooa_links);
11186
11187					ctl_free_io(io);
11188				}
11189			}
11190
11191			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11192	     		     io != NULL; io = next_io) {
11193
11194		        	next_io = (union ctl_io *)TAILQ_NEXT(
11195				    &io->io_hdr, ooa_links);
11196
11197				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11198
11199					TAILQ_REMOVE(&lun->ooa_queue,
11200						&io->io_hdr,
11201					     	ooa_links);
11202
11203					ctl_free_io(io);
11204				}
11205			}
11206			ctl_check_blocked(lun);
11207		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11208			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11209
11210			printf("FAILOVER: primary lun %d\n", lun_idx);
11211			/*
11212			 * Abort all commands from the other SC.  We can't
11213			 * send status back for them now.  These should get
11214			 * cleaned up when they are completed or come out
11215			 * for a datamove operation.
11216			 */
11217			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11218	     		     io != NULL; io = next_io) {
11219		        	next_io = (union ctl_io *)TAILQ_NEXT(
11220					&io->io_hdr, ooa_links);
11221
11222				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11223					io->io_hdr.flags |= CTL_FLAG_ABORT;
11224			}
11225		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11226			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11227
11228			printf("FAILOVER: secondary lun %d\n", lun_idx);
11229
11230			lun->flags |= CTL_LUN_PRIMARY_SC;
11231
11232			/*
11233			 * We send all I/O that was sent to this controller
11234			 * and redirected to the other side back with
11235			 * busy status, and have the initiator retry it.
11236			 * Figuring out how much data has been transferred,
11237			 * etc. and picking up where we left off would be
11238			 * very tricky.
11239			 *
11240			 * XXX KDM need to remove I/O from the blocked
11241			 * queue as well!
11242			 */
11243			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11244			     &lun->ooa_queue); pending_io != NULL;
11245			     pending_io = next_io) {
11246
11247				next_io =  (union ctl_io *)TAILQ_NEXT(
11248					&pending_io->io_hdr, ooa_links);
11249
11250				pending_io->io_hdr.flags &=
11251					~CTL_FLAG_SENT_2OTHER_SC;
11252
11253				if (pending_io->io_hdr.flags &
11254				    CTL_FLAG_IO_ACTIVE) {
11255					pending_io->io_hdr.flags |=
11256						CTL_FLAG_FAILOVER;
11257				} else {
11258					ctl_set_busy(&pending_io->scsiio);
11259					ctl_done(pending_io);
11260				}
11261			}
11262
11263			/*
11264			 * Build Unit Attention
11265			 */
11266			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11267				lun->pending_sense[i].ua_pending |=
11268				                     CTL_UA_ASYM_ACC_CHANGE;
11269			}
11270		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11271			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11272			printf("FAILOVER: secondary lun %d\n", lun_idx);
11273			/*
11274			 * if the first io on the OOA is not on the RtR queue
11275			 * add it.
11276			 */
11277			lun->flags |= CTL_LUN_PRIMARY_SC;
11278
11279			pending_io = (union ctl_io *)TAILQ_FIRST(
11280			    &lun->ooa_queue);
11281			if (pending_io==NULL) {
11282				printf("Nothing on OOA queue\n");
11283				continue;
11284			}
11285
11286			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11287			if ((pending_io->io_hdr.flags &
11288			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11289				pending_io->io_hdr.flags |=
11290				    CTL_FLAG_IS_WAS_ON_RTR;
11291				ctl_enqueue_rtr(pending_io);
11292			}
11293#if 0
11294			else
11295			{
11296				printf("Tag 0x%04x is running\n",
11297				      pending_io->scsiio.tag_num);
11298			}
11299#endif
11300
11301			next_io = (union ctl_io *)TAILQ_NEXT(
11302			    &pending_io->io_hdr, ooa_links);
11303			for (pending_io=next_io; pending_io != NULL;
11304			     pending_io = next_io) {
11305				pending_io->io_hdr.flags &=
11306				    ~CTL_FLAG_SENT_2OTHER_SC;
11307				next_io = (union ctl_io *)TAILQ_NEXT(
11308					&pending_io->io_hdr, ooa_links);
11309				if (pending_io->io_hdr.flags &
11310				    CTL_FLAG_IS_WAS_ON_RTR) {
11311#if 0
11312				        printf("Tag 0x%04x is running\n",
11313				      		pending_io->scsiio.tag_num);
11314#endif
11315					continue;
11316				}
11317
11318				switch (ctl_check_ooa(lun, pending_io,
11319			            (union ctl_io *)TAILQ_PREV(
11320				    &pending_io->io_hdr, ctl_ooaq,
11321				    ooa_links))) {
11322
11323				case CTL_ACTION_BLOCK:
11324					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11325							  &pending_io->io_hdr,
11326							  blocked_links);
11327					pending_io->io_hdr.flags |=
11328					    CTL_FLAG_BLOCKED;
11329					break;
11330				case CTL_ACTION_PASS:
11331				case CTL_ACTION_SKIP:
11332					pending_io->io_hdr.flags |=
11333					    CTL_FLAG_IS_WAS_ON_RTR;
11334					ctl_enqueue_rtr(pending_io);
11335					break;
11336				case CTL_ACTION_OVERLAP:
11337					ctl_set_overlapped_cmd(
11338					    (struct ctl_scsiio *)pending_io);
11339					ctl_done(pending_io);
11340					break;
11341				case CTL_ACTION_OVERLAP_TAG:
11342					ctl_set_overlapped_tag(
11343					    (struct ctl_scsiio *)pending_io,
11344					    pending_io->scsiio.tag_num & 0xff);
11345					ctl_done(pending_io);
11346					break;
11347				case CTL_ACTION_ERROR:
11348				default:
11349					ctl_set_internal_failure(
11350						(struct ctl_scsiio *)pending_io,
11351						0,  // sks_valid
11352						0); //retry count
11353					ctl_done(pending_io);
11354					break;
11355				}
11356			}
11357
11358			/*
11359			 * Build Unit Attention
11360			 */
11361			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11362				lun->pending_sense[i].ua_pending |=
11363				                     CTL_UA_ASYM_ACC_CHANGE;
11364			}
11365		} else {
11366			panic("Unhandled HA mode failover, LUN flags = %#x, "
11367			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11368		}
11369	}
11370	ctl_pause_rtr = 0;
11371	mtx_unlock(&ctl_softc->ctl_lock);
11372}
11373
11374static int
11375ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11376{
11377	struct ctl_lun *lun;
11378	const struct ctl_cmd_entry *entry;
11379	uint32_t initidx, targ_lun;
11380	int retval;
11381
11382	retval = 0;
11383
11384	lun = NULL;
11385
11386	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11387	if ((targ_lun < CTL_MAX_LUNS)
11388	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11389		lun = ctl_softc->ctl_luns[targ_lun];
11390		/*
11391		 * If the LUN is invalid, pretend that it doesn't exist.
11392		 * It will go away as soon as all pending I/O has been
11393		 * completed.
11394		 */
11395		if (lun->flags & CTL_LUN_DISABLED) {
11396			lun = NULL;
11397		} else {
11398			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11399			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11400				lun->be_lun;
11401			if (lun->be_lun->lun_type == T_PROCESSOR) {
11402				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11403			}
11404
11405			/*
11406			 * Every I/O goes into the OOA queue for a
11407			 * particular LUN, and stays there until completion.
11408			 */
11409			mtx_lock(&lun->lun_lock);
11410			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11411			    ooa_links);
11412		}
11413	} else {
11414		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11415		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11416	}
11417
11418	/* Get command entry and return error if it is unsuppotyed. */
11419	entry = ctl_validate_command(ctsio);
11420	if (entry == NULL) {
11421		if (lun)
11422			mtx_unlock(&lun->lun_lock);
11423		return (retval);
11424	}
11425
11426	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11427	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11428
11429	/*
11430	 * Check to see whether we can send this command to LUNs that don't
11431	 * exist.  This should pretty much only be the case for inquiry
11432	 * and request sense.  Further checks, below, really require having
11433	 * a LUN, so we can't really check the command anymore.  Just put
11434	 * it on the rtr queue.
11435	 */
11436	if (lun == NULL) {
11437		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11438			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11439			ctl_enqueue_rtr((union ctl_io *)ctsio);
11440			return (retval);
11441		}
11442
11443		ctl_set_unsupported_lun(ctsio);
11444		ctl_done((union ctl_io *)ctsio);
11445		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11446		return (retval);
11447	} else {
11448		/*
11449		 * Make sure we support this particular command on this LUN.
11450		 * e.g., we don't support writes to the control LUN.
11451		 */
11452		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11453			mtx_unlock(&lun->lun_lock);
11454			ctl_set_invalid_opcode(ctsio);
11455			ctl_done((union ctl_io *)ctsio);
11456			return (retval);
11457		}
11458	}
11459
11460	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11461
11462	/*
11463	 * If we've got a request sense, it'll clear the contingent
11464	 * allegiance condition.  Otherwise, if we have a CA condition for
11465	 * this initiator, clear it, because it sent down a command other
11466	 * than request sense.
11467	 */
11468	if ((ctsio->cdb[0] != REQUEST_SENSE)
11469	 && (ctl_is_set(lun->have_ca, initidx)))
11470		ctl_clear_mask(lun->have_ca, initidx);
11471
11472	/*
11473	 * If the command has this flag set, it handles its own unit
11474	 * attention reporting, we shouldn't do anything.  Otherwise we
11475	 * check for any pending unit attentions, and send them back to the
11476	 * initiator.  We only do this when a command initially comes in,
11477	 * not when we pull it off the blocked queue.
11478	 *
11479	 * According to SAM-3, section 5.3.2, the order that things get
11480	 * presented back to the host is basically unit attentions caused
11481	 * by some sort of reset event, busy status, reservation conflicts
11482	 * or task set full, and finally any other status.
11483	 *
11484	 * One issue here is that some of the unit attentions we report
11485	 * don't fall into the "reset" category (e.g. "reported luns data
11486	 * has changed").  So reporting it here, before the reservation
11487	 * check, may be technically wrong.  I guess the only thing to do
11488	 * would be to check for and report the reset events here, and then
11489	 * check for the other unit attention types after we check for a
11490	 * reservation conflict.
11491	 *
11492	 * XXX KDM need to fix this
11493	 */
11494	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11495		ctl_ua_type ua_type;
11496
11497		ua_type = lun->pending_sense[initidx].ua_pending;
11498		if (ua_type != CTL_UA_NONE) {
11499			scsi_sense_data_type sense_format;
11500
11501			if (lun != NULL)
11502				sense_format = (lun->flags &
11503				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11504				    SSD_TYPE_FIXED;
11505			else
11506				sense_format = SSD_TYPE_FIXED;
11507
11508			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11509					       sense_format);
11510			if (ua_type != CTL_UA_NONE) {
11511				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11512				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11513						       CTL_AUTOSENSE;
11514				ctsio->sense_len = SSD_FULL_SIZE;
11515				lun->pending_sense[initidx].ua_pending &=
11516					~ua_type;
11517				mtx_unlock(&lun->lun_lock);
11518				ctl_done((union ctl_io *)ctsio);
11519				return (retval);
11520			}
11521		}
11522	}
11523
11524
11525	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11526		mtx_unlock(&lun->lun_lock);
11527		ctl_done((union ctl_io *)ctsio);
11528		return (retval);
11529	}
11530
11531	/*
11532	 * XXX CHD this is where we want to send IO to other side if
11533	 * this LUN is secondary on this SC. We will need to make a copy
11534	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11535	 * the copy we send as FROM_OTHER.
11536	 * We also need to stuff the address of the original IO so we can
11537	 * find it easily. Something similar will need be done on the other
11538	 * side so when we are done we can find the copy.
11539	 */
11540	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11541		union ctl_ha_msg msg_info;
11542		int isc_retval;
11543
11544		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11545
11546		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11547		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11548#if 0
11549		printf("1. ctsio %p\n", ctsio);
11550#endif
11551		msg_info.hdr.serializing_sc = NULL;
11552		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11553		msg_info.scsi.tag_num = ctsio->tag_num;
11554		msg_info.scsi.tag_type = ctsio->tag_type;
11555		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11556
11557		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11558
11559		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11560		    (void *)&msg_info, sizeof(msg_info), 0)) >
11561		    CTL_HA_STATUS_SUCCESS) {
11562			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11563			       isc_retval);
11564			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11565		} else {
11566#if 0
11567			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11568#endif
11569		}
11570
11571		/*
11572		 * XXX KDM this I/O is off the incoming queue, but hasn't
11573		 * been inserted on any other queue.  We may need to come
11574		 * up with a holding queue while we wait for serialization
11575		 * so that we have an idea of what we're waiting for from
11576		 * the other side.
11577		 */
11578		mtx_unlock(&lun->lun_lock);
11579		return (retval);
11580	}
11581
11582	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11583			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11584			      ctl_ooaq, ooa_links))) {
11585	case CTL_ACTION_BLOCK:
11586		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11587		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11588				  blocked_links);
11589		mtx_unlock(&lun->lun_lock);
11590		return (retval);
11591	case CTL_ACTION_PASS:
11592	case CTL_ACTION_SKIP:
11593		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11594		mtx_unlock(&lun->lun_lock);
11595		ctl_enqueue_rtr((union ctl_io *)ctsio);
11596		break;
11597	case CTL_ACTION_OVERLAP:
11598		mtx_unlock(&lun->lun_lock);
11599		ctl_set_overlapped_cmd(ctsio);
11600		ctl_done((union ctl_io *)ctsio);
11601		break;
11602	case CTL_ACTION_OVERLAP_TAG:
11603		mtx_unlock(&lun->lun_lock);
11604		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11605		ctl_done((union ctl_io *)ctsio);
11606		break;
11607	case CTL_ACTION_ERROR:
11608	default:
11609		mtx_unlock(&lun->lun_lock);
11610		ctl_set_internal_failure(ctsio,
11611					 /*sks_valid*/ 0,
11612					 /*retry_count*/ 0);
11613		ctl_done((union ctl_io *)ctsio);
11614		break;
11615	}
11616	return (retval);
11617}
11618
11619const struct ctl_cmd_entry *
11620ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11621{
11622	const struct ctl_cmd_entry *entry;
11623	int service_action;
11624
11625	entry = &ctl_cmd_table[ctsio->cdb[0]];
11626	if (entry->flags & CTL_CMD_FLAG_SA5) {
11627		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11628		entry = &((const struct ctl_cmd_entry *)
11629		    entry->execute)[service_action];
11630	}
11631	return (entry);
11632}
11633
11634const struct ctl_cmd_entry *
11635ctl_validate_command(struct ctl_scsiio *ctsio)
11636{
11637	const struct ctl_cmd_entry *entry;
11638	int i;
11639	uint8_t diff;
11640
11641	entry = ctl_get_cmd_entry(ctsio);
11642	if (entry->execute == NULL) {
11643		ctl_set_invalid_opcode(ctsio);
11644		ctl_done((union ctl_io *)ctsio);
11645		return (NULL);
11646	}
11647	KASSERT(entry->length > 0,
11648	    ("Not defined length for command 0x%02x/0x%02x",
11649	     ctsio->cdb[0], ctsio->cdb[1]));
11650	for (i = 1; i < entry->length; i++) {
11651		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11652		if (diff == 0)
11653			continue;
11654		ctl_set_invalid_field(ctsio,
11655				      /*sks_valid*/ 1,
11656				      /*command*/ 1,
11657				      /*field*/ i,
11658				      /*bit_valid*/ 1,
11659				      /*bit*/ fls(diff) - 1);
11660		ctl_done((union ctl_io *)ctsio);
11661		return (NULL);
11662	}
11663	return (entry);
11664}
11665
11666static int
11667ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11668{
11669
11670	switch (lun_type) {
11671	case T_PROCESSOR:
11672		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11673		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11674			return (0);
11675		break;
11676	case T_DIRECT:
11677		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11678		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11679			return (0);
11680		break;
11681	default:
11682		return (0);
11683	}
11684	return (1);
11685}
11686
11687static int
11688ctl_scsiio(struct ctl_scsiio *ctsio)
11689{
11690	int retval;
11691	const struct ctl_cmd_entry *entry;
11692
11693	retval = CTL_RETVAL_COMPLETE;
11694
11695	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11696
11697	entry = ctl_get_cmd_entry(ctsio);
11698
11699	/*
11700	 * If this I/O has been aborted, just send it straight to
11701	 * ctl_done() without executing it.
11702	 */
11703	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11704		ctl_done((union ctl_io *)ctsio);
11705		goto bailout;
11706	}
11707
11708	/*
11709	 * All the checks should have been handled by ctl_scsiio_precheck().
11710	 * We should be clear now to just execute the I/O.
11711	 */
11712	retval = entry->execute(ctsio);
11713
11714bailout:
11715	return (retval);
11716}
11717
11718/*
11719 * Since we only implement one target right now, a bus reset simply resets
11720 * our single target.
11721 */
11722static int
11723ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11724{
11725	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11726}
11727
11728static int
11729ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11730		 ctl_ua_type ua_type)
11731{
11732	struct ctl_lun *lun;
11733	int retval;
11734
11735	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11736		union ctl_ha_msg msg_info;
11737
11738		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11739		msg_info.hdr.nexus = io->io_hdr.nexus;
11740		if (ua_type==CTL_UA_TARG_RESET)
11741			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11742		else
11743			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11744		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11745		msg_info.hdr.original_sc = NULL;
11746		msg_info.hdr.serializing_sc = NULL;
11747		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11748		    (void *)&msg_info, sizeof(msg_info), 0)) {
11749		}
11750	}
11751	retval = 0;
11752
11753	mtx_lock(&ctl_softc->ctl_lock);
11754	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11755		retval += ctl_lun_reset(lun, io, ua_type);
11756	mtx_unlock(&ctl_softc->ctl_lock);
11757
11758	return (retval);
11759}
11760
11761/*
11762 * The LUN should always be set.  The I/O is optional, and is used to
11763 * distinguish between I/Os sent by this initiator, and by other
11764 * initiators.  We set unit attention for initiators other than this one.
11765 * SAM-3 is vague on this point.  It does say that a unit attention should
11766 * be established for other initiators when a LUN is reset (see section
11767 * 5.7.3), but it doesn't specifically say that the unit attention should
11768 * be established for this particular initiator when a LUN is reset.  Here
11769 * is the relevant text, from SAM-3 rev 8:
11770 *
11771 * 5.7.2 When a SCSI initiator port aborts its own tasks
11772 *
11773 * When a SCSI initiator port causes its own task(s) to be aborted, no
11774 * notification that the task(s) have been aborted shall be returned to
11775 * the SCSI initiator port other than the completion response for the
11776 * command or task management function action that caused the task(s) to
11777 * be aborted and notification(s) associated with related effects of the
11778 * action (e.g., a reset unit attention condition).
11779 *
11780 * XXX KDM for now, we're setting unit attention for all initiators.
11781 */
11782static int
11783ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11784{
11785	union ctl_io *xio;
11786#if 0
11787	uint32_t initindex;
11788#endif
11789	int i;
11790
11791	mtx_lock(&lun->lun_lock);
11792	/*
11793	 * Run through the OOA queue and abort each I/O.
11794	 */
11795#if 0
11796	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11797#endif
11798	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11799	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11800		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11801	}
11802
11803	/*
11804	 * This version sets unit attention for every
11805	 */
11806#if 0
11807	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11808	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11809		if (initindex == i)
11810			continue;
11811		lun->pending_sense[i].ua_pending |= ua_type;
11812	}
11813#endif
11814
11815	/*
11816	 * A reset (any kind, really) clears reservations established with
11817	 * RESERVE/RELEASE.  It does not clear reservations established
11818	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11819	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11820	 * reservations made with the RESERVE/RELEASE commands, because
11821	 * those commands are obsolete in SPC-3.
11822	 */
11823	lun->flags &= ~CTL_LUN_RESERVED;
11824
11825	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11826		ctl_clear_mask(lun->have_ca, i);
11827		lun->pending_sense[i].ua_pending |= ua_type;
11828	}
11829	mtx_unlock(&lun->lun_lock);
11830
11831	return (0);
11832}
11833
11834static int
11835ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11836    int other_sc)
11837{
11838	union ctl_io *xio;
11839	int found;
11840
11841	mtx_assert(&lun->lun_lock, MA_OWNED);
11842
11843	/*
11844	 * Run through the OOA queue and attempt to find the given I/O.
11845	 * The target port, initiator ID, tag type and tag number have to
11846	 * match the values that we got from the initiator.  If we have an
11847	 * untagged command to abort, simply abort the first untagged command
11848	 * we come to.  We only allow one untagged command at a time of course.
11849	 */
11850	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11851	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11852
11853		if ((targ_port == UINT32_MAX ||
11854		     targ_port == xio->io_hdr.nexus.targ_port) &&
11855		    (init_id == UINT32_MAX ||
11856		     init_id == xio->io_hdr.nexus.initid.id)) {
11857			if (targ_port != xio->io_hdr.nexus.targ_port ||
11858			    init_id != xio->io_hdr.nexus.initid.id)
11859				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11860			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11861			found = 1;
11862			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11863				union ctl_ha_msg msg_info;
11864
11865				msg_info.hdr.nexus = xio->io_hdr.nexus;
11866				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11867				msg_info.task.tag_num = xio->scsiio.tag_num;
11868				msg_info.task.tag_type = xio->scsiio.tag_type;
11869				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11870				msg_info.hdr.original_sc = NULL;
11871				msg_info.hdr.serializing_sc = NULL;
11872				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11873				    (void *)&msg_info, sizeof(msg_info), 0);
11874			}
11875		}
11876	}
11877	return (found);
11878}
11879
11880static int
11881ctl_abort_task_set(union ctl_io *io)
11882{
11883	struct ctl_softc *softc = control_softc;
11884	struct ctl_lun *lun;
11885	uint32_t targ_lun;
11886
11887	/*
11888	 * Look up the LUN.
11889	 */
11890	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11891	mtx_lock(&softc->ctl_lock);
11892	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11893		lun = softc->ctl_luns[targ_lun];
11894	else {
11895		mtx_unlock(&softc->ctl_lock);
11896		return (1);
11897	}
11898
11899	mtx_lock(&lun->lun_lock);
11900	mtx_unlock(&softc->ctl_lock);
11901	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11902		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11903		    io->io_hdr.nexus.initid.id,
11904		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11905	} else { /* CTL_TASK_CLEAR_TASK_SET */
11906		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11907		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11908	}
11909	mtx_unlock(&lun->lun_lock);
11910	return (0);
11911}
11912
11913static int
11914ctl_i_t_nexus_reset(union ctl_io *io)
11915{
11916	struct ctl_softc *softc = control_softc;
11917	struct ctl_lun *lun;
11918	uint32_t initindex;
11919
11920	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11921	mtx_lock(&softc->ctl_lock);
11922	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11923		mtx_lock(&lun->lun_lock);
11924		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11925		    io->io_hdr.nexus.initid.id,
11926		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11927		ctl_clear_mask(lun->have_ca, initindex);
11928		lun->pending_sense[initindex].ua_pending |= CTL_UA_I_T_NEXUS_LOSS;
11929		mtx_unlock(&lun->lun_lock);
11930	}
11931	mtx_unlock(&softc->ctl_lock);
11932	return (0);
11933}
11934
11935static int
11936ctl_abort_task(union ctl_io *io)
11937{
11938	union ctl_io *xio;
11939	struct ctl_lun *lun;
11940	struct ctl_softc *ctl_softc;
11941#if 0
11942	struct sbuf sb;
11943	char printbuf[128];
11944#endif
11945	int found;
11946	uint32_t targ_lun;
11947
11948	ctl_softc = control_softc;
11949	found = 0;
11950
11951	/*
11952	 * Look up the LUN.
11953	 */
11954	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11955	mtx_lock(&ctl_softc->ctl_lock);
11956	if ((targ_lun < CTL_MAX_LUNS)
11957	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11958		lun = ctl_softc->ctl_luns[targ_lun];
11959	else {
11960		mtx_unlock(&ctl_softc->ctl_lock);
11961		return (1);
11962	}
11963
11964#if 0
11965	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11966	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11967#endif
11968
11969	mtx_lock(&lun->lun_lock);
11970	mtx_unlock(&ctl_softc->ctl_lock);
11971	/*
11972	 * Run through the OOA queue and attempt to find the given I/O.
11973	 * The target port, initiator ID, tag type and tag number have to
11974	 * match the values that we got from the initiator.  If we have an
11975	 * untagged command to abort, simply abort the first untagged command
11976	 * we come to.  We only allow one untagged command at a time of course.
11977	 */
11978#if 0
11979	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11980#endif
11981	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11982	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11983#if 0
11984		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11985
11986		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11987			    lun->lun, xio->scsiio.tag_num,
11988			    xio->scsiio.tag_type,
11989			    (xio->io_hdr.blocked_links.tqe_prev
11990			    == NULL) ? "" : " BLOCKED",
11991			    (xio->io_hdr.flags &
11992			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11993			    (xio->io_hdr.flags &
11994			    CTL_FLAG_ABORT) ? " ABORT" : "",
11995			    (xio->io_hdr.flags &
11996			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11997		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11998		sbuf_finish(&sb);
11999		printf("%s\n", sbuf_data(&sb));
12000#endif
12001
12002		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12003		 && (xio->io_hdr.nexus.initid.id ==
12004		     io->io_hdr.nexus.initid.id)) {
12005			/*
12006			 * If the abort says that the task is untagged, the
12007			 * task in the queue must be untagged.  Otherwise,
12008			 * we just check to see whether the tag numbers
12009			 * match.  This is because the QLogic firmware
12010			 * doesn't pass back the tag type in an abort
12011			 * request.
12012			 */
12013#if 0
12014			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12015			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12016			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12017#endif
12018			/*
12019			 * XXX KDM we've got problems with FC, because it
12020			 * doesn't send down a tag type with aborts.  So we
12021			 * can only really go by the tag number...
12022			 * This may cause problems with parallel SCSI.
12023			 * Need to figure that out!!
12024			 */
12025			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12026				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12027				found = 1;
12028				if ((io->io_hdr.flags &
12029				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12030				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12031					union ctl_ha_msg msg_info;
12032
12033					io->io_hdr.flags |=
12034					                CTL_FLAG_SENT_2OTHER_SC;
12035					msg_info.hdr.nexus = io->io_hdr.nexus;
12036					msg_info.task.task_action =
12037						CTL_TASK_ABORT_TASK;
12038					msg_info.task.tag_num =
12039						io->taskio.tag_num;
12040					msg_info.task.tag_type =
12041						io->taskio.tag_type;
12042					msg_info.hdr.msg_type =
12043						CTL_MSG_MANAGE_TASKS;
12044					msg_info.hdr.original_sc = NULL;
12045					msg_info.hdr.serializing_sc = NULL;
12046#if 0
12047					printf("Sent Abort to other side\n");
12048#endif
12049					if (CTL_HA_STATUS_SUCCESS !=
12050					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12051		    				(void *)&msg_info,
12052						sizeof(msg_info), 0)) {
12053					}
12054				}
12055#if 0
12056				printf("ctl_abort_task: found I/O to abort\n");
12057#endif
12058				break;
12059			}
12060		}
12061	}
12062	mtx_unlock(&lun->lun_lock);
12063
12064	if (found == 0) {
12065		/*
12066		 * This isn't really an error.  It's entirely possible for
12067		 * the abort and command completion to cross on the wire.
12068		 * This is more of an informative/diagnostic error.
12069		 */
12070#if 0
12071		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12072		       "%d:%d:%d:%d tag %d type %d\n",
12073		       io->io_hdr.nexus.initid.id,
12074		       io->io_hdr.nexus.targ_port,
12075		       io->io_hdr.nexus.targ_target.id,
12076		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12077		       io->taskio.tag_type);
12078#endif
12079	}
12080	return (0);
12081}
12082
12083static void
12084ctl_run_task(union ctl_io *io)
12085{
12086	struct ctl_softc *ctl_softc = control_softc;
12087	int retval = 1;
12088	const char *task_desc;
12089
12090	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12091
12092	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12093	    ("ctl_run_task: Unextected io_type %d\n",
12094	     io->io_hdr.io_type));
12095
12096	task_desc = ctl_scsi_task_string(&io->taskio);
12097	if (task_desc != NULL) {
12098#ifdef NEEDTOPORT
12099		csevent_log(CSC_CTL | CSC_SHELF_SW |
12100			    CTL_TASK_REPORT,
12101			    csevent_LogType_Trace,
12102			    csevent_Severity_Information,
12103			    csevent_AlertLevel_Green,
12104			    csevent_FRU_Firmware,
12105			    csevent_FRU_Unknown,
12106			    "CTL: received task: %s",task_desc);
12107#endif
12108	} else {
12109#ifdef NEEDTOPORT
12110		csevent_log(CSC_CTL | CSC_SHELF_SW |
12111			    CTL_TASK_REPORT,
12112			    csevent_LogType_Trace,
12113			    csevent_Severity_Information,
12114			    csevent_AlertLevel_Green,
12115			    csevent_FRU_Firmware,
12116			    csevent_FRU_Unknown,
12117			    "CTL: received unknown task "
12118			    "type: %d (%#x)",
12119			    io->taskio.task_action,
12120			    io->taskio.task_action);
12121#endif
12122	}
12123	switch (io->taskio.task_action) {
12124	case CTL_TASK_ABORT_TASK:
12125		retval = ctl_abort_task(io);
12126		break;
12127	case CTL_TASK_ABORT_TASK_SET:
12128	case CTL_TASK_CLEAR_TASK_SET:
12129		retval = ctl_abort_task_set(io);
12130		break;
12131	case CTL_TASK_CLEAR_ACA:
12132		break;
12133	case CTL_TASK_I_T_NEXUS_RESET:
12134		retval = ctl_i_t_nexus_reset(io);
12135		break;
12136	case CTL_TASK_LUN_RESET: {
12137		struct ctl_lun *lun;
12138		uint32_t targ_lun;
12139
12140		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12141		mtx_lock(&ctl_softc->ctl_lock);
12142		if ((targ_lun < CTL_MAX_LUNS)
12143		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12144			lun = ctl_softc->ctl_luns[targ_lun];
12145		else {
12146			mtx_unlock(&ctl_softc->ctl_lock);
12147			retval = 1;
12148			break;
12149		}
12150
12151		if (!(io->io_hdr.flags &
12152		    CTL_FLAG_FROM_OTHER_SC)) {
12153			union ctl_ha_msg msg_info;
12154
12155			io->io_hdr.flags |=
12156				CTL_FLAG_SENT_2OTHER_SC;
12157			msg_info.hdr.msg_type =
12158				CTL_MSG_MANAGE_TASKS;
12159			msg_info.hdr.nexus = io->io_hdr.nexus;
12160			msg_info.task.task_action =
12161				CTL_TASK_LUN_RESET;
12162			msg_info.hdr.original_sc = NULL;
12163			msg_info.hdr.serializing_sc = NULL;
12164			if (CTL_HA_STATUS_SUCCESS !=
12165			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12166			    (void *)&msg_info,
12167			    sizeof(msg_info), 0)) {
12168			}
12169		}
12170
12171		retval = ctl_lun_reset(lun, io,
12172				       CTL_UA_LUN_RESET);
12173		mtx_unlock(&ctl_softc->ctl_lock);
12174		break;
12175	}
12176	case CTL_TASK_TARGET_RESET:
12177		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12178		break;
12179	case CTL_TASK_BUS_RESET:
12180		retval = ctl_bus_reset(ctl_softc, io);
12181		break;
12182	case CTL_TASK_PORT_LOGIN:
12183		break;
12184	case CTL_TASK_PORT_LOGOUT:
12185		break;
12186	default:
12187		printf("ctl_run_task: got unknown task management event %d\n",
12188		       io->taskio.task_action);
12189		break;
12190	}
12191	if (retval == 0)
12192		io->io_hdr.status = CTL_SUCCESS;
12193	else
12194		io->io_hdr.status = CTL_ERROR;
12195	ctl_done(io);
12196}
12197
12198/*
12199 * For HA operation.  Handle commands that come in from the other
12200 * controller.
12201 */
12202static void
12203ctl_handle_isc(union ctl_io *io)
12204{
12205	int free_io;
12206	struct ctl_lun *lun;
12207	struct ctl_softc *ctl_softc;
12208	uint32_t targ_lun;
12209
12210	ctl_softc = control_softc;
12211
12212	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12213	lun = ctl_softc->ctl_luns[targ_lun];
12214
12215	switch (io->io_hdr.msg_type) {
12216	case CTL_MSG_SERIALIZE:
12217		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12218		break;
12219	case CTL_MSG_R2R: {
12220		const struct ctl_cmd_entry *entry;
12221
12222		/*
12223		 * This is only used in SER_ONLY mode.
12224		 */
12225		free_io = 0;
12226		entry = ctl_get_cmd_entry(&io->scsiio);
12227		mtx_lock(&lun->lun_lock);
12228		if (ctl_scsiio_lun_check(ctl_softc, lun,
12229		    entry, (struct ctl_scsiio *)io) != 0) {
12230			mtx_unlock(&lun->lun_lock);
12231			ctl_done(io);
12232			break;
12233		}
12234		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12235		mtx_unlock(&lun->lun_lock);
12236		ctl_enqueue_rtr(io);
12237		break;
12238	}
12239	case CTL_MSG_FINISH_IO:
12240		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12241			free_io = 0;
12242			ctl_done(io);
12243		} else {
12244			free_io = 1;
12245			mtx_lock(&lun->lun_lock);
12246			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12247				     ooa_links);
12248			ctl_check_blocked(lun);
12249			mtx_unlock(&lun->lun_lock);
12250		}
12251		break;
12252	case CTL_MSG_PERS_ACTION:
12253		ctl_hndl_per_res_out_on_other_sc(
12254			(union ctl_ha_msg *)&io->presio.pr_msg);
12255		free_io = 1;
12256		break;
12257	case CTL_MSG_BAD_JUJU:
12258		free_io = 0;
12259		ctl_done(io);
12260		break;
12261	case CTL_MSG_DATAMOVE:
12262		/* Only used in XFER mode */
12263		free_io = 0;
12264		ctl_datamove_remote(io);
12265		break;
12266	case CTL_MSG_DATAMOVE_DONE:
12267		/* Only used in XFER mode */
12268		free_io = 0;
12269		io->scsiio.be_move_done(io);
12270		break;
12271	default:
12272		free_io = 1;
12273		printf("%s: Invalid message type %d\n",
12274		       __func__, io->io_hdr.msg_type);
12275		break;
12276	}
12277	if (free_io)
12278		ctl_free_io(io);
12279
12280}
12281
12282
12283/*
12284 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12285 * there is no match.
12286 */
12287static ctl_lun_error_pattern
12288ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12289{
12290	const struct ctl_cmd_entry *entry;
12291	ctl_lun_error_pattern filtered_pattern, pattern;
12292
12293	pattern = desc->error_pattern;
12294
12295	/*
12296	 * XXX KDM we need more data passed into this function to match a
12297	 * custom pattern, and we actually need to implement custom pattern
12298	 * matching.
12299	 */
12300	if (pattern & CTL_LUN_PAT_CMD)
12301		return (CTL_LUN_PAT_CMD);
12302
12303	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12304		return (CTL_LUN_PAT_ANY);
12305
12306	entry = ctl_get_cmd_entry(ctsio);
12307
12308	filtered_pattern = entry->pattern & pattern;
12309
12310	/*
12311	 * If the user requested specific flags in the pattern (e.g.
12312	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12313	 * flags.
12314	 *
12315	 * If the user did not specify any flags, it doesn't matter whether
12316	 * or not the command supports the flags.
12317	 */
12318	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12319	     (pattern & ~CTL_LUN_PAT_MASK))
12320		return (CTL_LUN_PAT_NONE);
12321
12322	/*
12323	 * If the user asked for a range check, see if the requested LBA
12324	 * range overlaps with this command's LBA range.
12325	 */
12326	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12327		uint64_t lba1;
12328		uint32_t len1;
12329		ctl_action action;
12330		int retval;
12331
12332		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12333		if (retval != 0)
12334			return (CTL_LUN_PAT_NONE);
12335
12336		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12337					      desc->lba_range.len);
12338		/*
12339		 * A "pass" means that the LBA ranges don't overlap, so
12340		 * this doesn't match the user's range criteria.
12341		 */
12342		if (action == CTL_ACTION_PASS)
12343			return (CTL_LUN_PAT_NONE);
12344	}
12345
12346	return (filtered_pattern);
12347}
12348
12349static void
12350ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12351{
12352	struct ctl_error_desc *desc, *desc2;
12353
12354	mtx_assert(&lun->lun_lock, MA_OWNED);
12355
12356	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12357		ctl_lun_error_pattern pattern;
12358		/*
12359		 * Check to see whether this particular command matches
12360		 * the pattern in the descriptor.
12361		 */
12362		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12363		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12364			continue;
12365
12366		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12367		case CTL_LUN_INJ_ABORTED:
12368			ctl_set_aborted(&io->scsiio);
12369			break;
12370		case CTL_LUN_INJ_MEDIUM_ERR:
12371			ctl_set_medium_error(&io->scsiio);
12372			break;
12373		case CTL_LUN_INJ_UA:
12374			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12375			 * OCCURRED */
12376			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12377			break;
12378		case CTL_LUN_INJ_CUSTOM:
12379			/*
12380			 * We're assuming the user knows what he is doing.
12381			 * Just copy the sense information without doing
12382			 * checks.
12383			 */
12384			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12385			      ctl_min(sizeof(desc->custom_sense),
12386				      sizeof(io->scsiio.sense_data)));
12387			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12388			io->scsiio.sense_len = SSD_FULL_SIZE;
12389			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12390			break;
12391		case CTL_LUN_INJ_NONE:
12392		default:
12393			/*
12394			 * If this is an error injection type we don't know
12395			 * about, clear the continuous flag (if it is set)
12396			 * so it will get deleted below.
12397			 */
12398			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12399			break;
12400		}
12401		/*
12402		 * By default, each error injection action is a one-shot
12403		 */
12404		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12405			continue;
12406
12407		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12408
12409		free(desc, M_CTL);
12410	}
12411}
12412
12413#ifdef CTL_IO_DELAY
12414static void
12415ctl_datamove_timer_wakeup(void *arg)
12416{
12417	union ctl_io *io;
12418
12419	io = (union ctl_io *)arg;
12420
12421	ctl_datamove(io);
12422}
12423#endif /* CTL_IO_DELAY */
12424
12425void
12426ctl_datamove(union ctl_io *io)
12427{
12428	void (*fe_datamove)(union ctl_io *io);
12429
12430	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12431
12432	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12433
12434#ifdef CTL_TIME_IO
12435	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12436		char str[256];
12437		char path_str[64];
12438		struct sbuf sb;
12439
12440		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12441		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12442
12443		sbuf_cat(&sb, path_str);
12444		switch (io->io_hdr.io_type) {
12445		case CTL_IO_SCSI:
12446			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12447			sbuf_printf(&sb, "\n");
12448			sbuf_cat(&sb, path_str);
12449			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12450				    io->scsiio.tag_num, io->scsiio.tag_type);
12451			break;
12452		case CTL_IO_TASK:
12453			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12454				    "Tag Type: %d\n", io->taskio.task_action,
12455				    io->taskio.tag_num, io->taskio.tag_type);
12456			break;
12457		default:
12458			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12459			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12460			break;
12461		}
12462		sbuf_cat(&sb, path_str);
12463		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12464			    (intmax_t)time_uptime - io->io_hdr.start_time);
12465		sbuf_finish(&sb);
12466		printf("%s", sbuf_data(&sb));
12467	}
12468#endif /* CTL_TIME_IO */
12469
12470#ifdef CTL_IO_DELAY
12471	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12472		struct ctl_lun *lun;
12473
12474		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12475
12476		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12477	} else {
12478		struct ctl_lun *lun;
12479
12480		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12481		if ((lun != NULL)
12482		 && (lun->delay_info.datamove_delay > 0)) {
12483			struct callout *callout;
12484
12485			callout = (struct callout *)&io->io_hdr.timer_bytes;
12486			callout_init(callout, /*mpsafe*/ 1);
12487			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12488			callout_reset(callout,
12489				      lun->delay_info.datamove_delay * hz,
12490				      ctl_datamove_timer_wakeup, io);
12491			if (lun->delay_info.datamove_type ==
12492			    CTL_DELAY_TYPE_ONESHOT)
12493				lun->delay_info.datamove_delay = 0;
12494			return;
12495		}
12496	}
12497#endif
12498
12499	/*
12500	 * This command has been aborted.  Set the port status, so we fail
12501	 * the data move.
12502	 */
12503	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12504		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12505		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12506		       io->io_hdr.nexus.targ_port,
12507		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12508		       io->io_hdr.nexus.targ_lun);
12509		io->io_hdr.port_status = 31337;
12510		/*
12511		 * Note that the backend, in this case, will get the
12512		 * callback in its context.  In other cases it may get
12513		 * called in the frontend's interrupt thread context.
12514		 */
12515		io->scsiio.be_move_done(io);
12516		return;
12517	}
12518
12519	/*
12520	 * If we're in XFER mode and this I/O is from the other shelf
12521	 * controller, we need to send the DMA to the other side to
12522	 * actually transfer the data to/from the host.  In serialize only
12523	 * mode the transfer happens below CTL and ctl_datamove() is only
12524	 * called on the machine that originally received the I/O.
12525	 */
12526	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12527	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12528		union ctl_ha_msg msg;
12529		uint32_t sg_entries_sent;
12530		int do_sg_copy;
12531		int i;
12532
12533		memset(&msg, 0, sizeof(msg));
12534		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12535		msg.hdr.original_sc = io->io_hdr.original_sc;
12536		msg.hdr.serializing_sc = io;
12537		msg.hdr.nexus = io->io_hdr.nexus;
12538		msg.dt.flags = io->io_hdr.flags;
12539		/*
12540		 * We convert everything into a S/G list here.  We can't
12541		 * pass by reference, only by value between controllers.
12542		 * So we can't pass a pointer to the S/G list, only as many
12543		 * S/G entries as we can fit in here.  If it's possible for
12544		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12545		 * then we need to break this up into multiple transfers.
12546		 */
12547		if (io->scsiio.kern_sg_entries == 0) {
12548			msg.dt.kern_sg_entries = 1;
12549			/*
12550			 * If this is in cached memory, flush the cache
12551			 * before we send the DMA request to the other
12552			 * controller.  We want to do this in either the
12553			 * read or the write case.  The read case is
12554			 * straightforward.  In the write case, we want to
12555			 * make sure nothing is in the local cache that
12556			 * could overwrite the DMAed data.
12557			 */
12558			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12559				/*
12560				 * XXX KDM use bus_dmamap_sync() here.
12561				 */
12562			}
12563
12564			/*
12565			 * Convert to a physical address if this is a
12566			 * virtual address.
12567			 */
12568			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12569				msg.dt.sg_list[0].addr =
12570					io->scsiio.kern_data_ptr;
12571			} else {
12572				/*
12573				 * XXX KDM use busdma here!
12574				 */
12575#if 0
12576				msg.dt.sg_list[0].addr = (void *)
12577					vtophys(io->scsiio.kern_data_ptr);
12578#endif
12579			}
12580
12581			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12582			do_sg_copy = 0;
12583		} else {
12584			struct ctl_sg_entry *sgl;
12585
12586			do_sg_copy = 1;
12587			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12588			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12589			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12590				/*
12591				 * XXX KDM use bus_dmamap_sync() here.
12592				 */
12593			}
12594		}
12595
12596		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12597		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12598		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12599		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12600		msg.dt.sg_sequence = 0;
12601
12602		/*
12603		 * Loop until we've sent all of the S/G entries.  On the
12604		 * other end, we'll recompose these S/G entries into one
12605		 * contiguous list before passing it to the
12606		 */
12607		for (sg_entries_sent = 0; sg_entries_sent <
12608		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12609			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12610				sizeof(msg.dt.sg_list[0])),
12611				msg.dt.kern_sg_entries - sg_entries_sent);
12612
12613			if (do_sg_copy != 0) {
12614				struct ctl_sg_entry *sgl;
12615				int j;
12616
12617				sgl = (struct ctl_sg_entry *)
12618					io->scsiio.kern_data_ptr;
12619				/*
12620				 * If this is in cached memory, flush the cache
12621				 * before we send the DMA request to the other
12622				 * controller.  We want to do this in either
12623				 * the * read or the write case.  The read
12624				 * case is straightforward.  In the write
12625				 * case, we want to make sure nothing is
12626				 * in the local cache that could overwrite
12627				 * the DMAed data.
12628				 */
12629
12630				for (i = sg_entries_sent, j = 0;
12631				     i < msg.dt.cur_sg_entries; i++, j++) {
12632					if ((io->io_hdr.flags &
12633					     CTL_FLAG_NO_DATASYNC) == 0) {
12634						/*
12635						 * XXX KDM use bus_dmamap_sync()
12636						 */
12637					}
12638					if ((io->io_hdr.flags &
12639					     CTL_FLAG_BUS_ADDR) == 0) {
12640						/*
12641						 * XXX KDM use busdma.
12642						 */
12643#if 0
12644						msg.dt.sg_list[j].addr =(void *)
12645						       vtophys(sgl[i].addr);
12646#endif
12647					} else {
12648						msg.dt.sg_list[j].addr =
12649							sgl[i].addr;
12650					}
12651					msg.dt.sg_list[j].len = sgl[i].len;
12652				}
12653			}
12654
12655			sg_entries_sent += msg.dt.cur_sg_entries;
12656			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12657				msg.dt.sg_last = 1;
12658			else
12659				msg.dt.sg_last = 0;
12660
12661			/*
12662			 * XXX KDM drop and reacquire the lock here?
12663			 */
12664			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12665			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12666				/*
12667				 * XXX do something here.
12668				 */
12669			}
12670
12671			msg.dt.sent_sg_entries = sg_entries_sent;
12672		}
12673		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12674		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12675			ctl_failover_io(io, /*have_lock*/ 0);
12676
12677	} else {
12678
12679		/*
12680		 * Lookup the fe_datamove() function for this particular
12681		 * front end.
12682		 */
12683		fe_datamove =
12684		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12685
12686		fe_datamove(io);
12687	}
12688}
12689
12690static void
12691ctl_send_datamove_done(union ctl_io *io, int have_lock)
12692{
12693	union ctl_ha_msg msg;
12694	int isc_status;
12695
12696	memset(&msg, 0, sizeof(msg));
12697
12698	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12699	msg.hdr.original_sc = io;
12700	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12701	msg.hdr.nexus = io->io_hdr.nexus;
12702	msg.hdr.status = io->io_hdr.status;
12703	msg.scsi.tag_num = io->scsiio.tag_num;
12704	msg.scsi.tag_type = io->scsiio.tag_type;
12705	msg.scsi.scsi_status = io->scsiio.scsi_status;
12706	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12707	       sizeof(io->scsiio.sense_data));
12708	msg.scsi.sense_len = io->scsiio.sense_len;
12709	msg.scsi.sense_residual = io->scsiio.sense_residual;
12710	msg.scsi.fetd_status = io->io_hdr.port_status;
12711	msg.scsi.residual = io->scsiio.residual;
12712	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12713
12714	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12715		ctl_failover_io(io, /*have_lock*/ have_lock);
12716		return;
12717	}
12718
12719	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12720	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12721		/* XXX do something if this fails */
12722	}
12723
12724}
12725
12726/*
12727 * The DMA to the remote side is done, now we need to tell the other side
12728 * we're done so it can continue with its data movement.
12729 */
12730static void
12731ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12732{
12733	union ctl_io *io;
12734
12735	io = rq->context;
12736
12737	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12738		printf("%s: ISC DMA write failed with error %d", __func__,
12739		       rq->ret);
12740		ctl_set_internal_failure(&io->scsiio,
12741					 /*sks_valid*/ 1,
12742					 /*retry_count*/ rq->ret);
12743	}
12744
12745	ctl_dt_req_free(rq);
12746
12747	/*
12748	 * In this case, we had to malloc the memory locally.  Free it.
12749	 */
12750	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12751		int i;
12752		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12753			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12754	}
12755	/*
12756	 * The data is in local and remote memory, so now we need to send
12757	 * status (good or back) back to the other side.
12758	 */
12759	ctl_send_datamove_done(io, /*have_lock*/ 0);
12760}
12761
12762/*
12763 * We've moved the data from the host/controller into local memory.  Now we
12764 * need to push it over to the remote controller's memory.
12765 */
12766static int
12767ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12768{
12769	int retval;
12770
12771	retval = 0;
12772
12773	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12774					  ctl_datamove_remote_write_cb);
12775
12776	return (retval);
12777}
12778
12779static void
12780ctl_datamove_remote_write(union ctl_io *io)
12781{
12782	int retval;
12783	void (*fe_datamove)(union ctl_io *io);
12784
12785	/*
12786	 * - Get the data from the host/HBA into local memory.
12787	 * - DMA memory from the local controller to the remote controller.
12788	 * - Send status back to the remote controller.
12789	 */
12790
12791	retval = ctl_datamove_remote_sgl_setup(io);
12792	if (retval != 0)
12793		return;
12794
12795	/* Switch the pointer over so the FETD knows what to do */
12796	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12797
12798	/*
12799	 * Use a custom move done callback, since we need to send completion
12800	 * back to the other controller, not to the backend on this side.
12801	 */
12802	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12803
12804	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12805
12806	fe_datamove(io);
12807
12808	return;
12809
12810}
12811
12812static int
12813ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12814{
12815#if 0
12816	char str[256];
12817	char path_str[64];
12818	struct sbuf sb;
12819#endif
12820
12821	/*
12822	 * In this case, we had to malloc the memory locally.  Free it.
12823	 */
12824	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12825		int i;
12826		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12827			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12828	}
12829
12830#if 0
12831	scsi_path_string(io, path_str, sizeof(path_str));
12832	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12833	sbuf_cat(&sb, path_str);
12834	scsi_command_string(&io->scsiio, NULL, &sb);
12835	sbuf_printf(&sb, "\n");
12836	sbuf_cat(&sb, path_str);
12837	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12838		    io->scsiio.tag_num, io->scsiio.tag_type);
12839	sbuf_cat(&sb, path_str);
12840	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12841		    io->io_hdr.flags, io->io_hdr.status);
12842	sbuf_finish(&sb);
12843	printk("%s", sbuf_data(&sb));
12844#endif
12845
12846
12847	/*
12848	 * The read is done, now we need to send status (good or bad) back
12849	 * to the other side.
12850	 */
12851	ctl_send_datamove_done(io, /*have_lock*/ 0);
12852
12853	return (0);
12854}
12855
12856static void
12857ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12858{
12859	union ctl_io *io;
12860	void (*fe_datamove)(union ctl_io *io);
12861
12862	io = rq->context;
12863
12864	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12865		printf("%s: ISC DMA read failed with error %d", __func__,
12866		       rq->ret);
12867		ctl_set_internal_failure(&io->scsiio,
12868					 /*sks_valid*/ 1,
12869					 /*retry_count*/ rq->ret);
12870	}
12871
12872	ctl_dt_req_free(rq);
12873
12874	/* Switch the pointer over so the FETD knows what to do */
12875	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12876
12877	/*
12878	 * Use a custom move done callback, since we need to send completion
12879	 * back to the other controller, not to the backend on this side.
12880	 */
12881	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12882
12883	/* XXX KDM add checks like the ones in ctl_datamove? */
12884
12885	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12886
12887	fe_datamove(io);
12888}
12889
12890static int
12891ctl_datamove_remote_sgl_setup(union ctl_io *io)
12892{
12893	struct ctl_sg_entry *local_sglist, *remote_sglist;
12894	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12895	struct ctl_softc *softc;
12896	int retval;
12897	int i;
12898
12899	retval = 0;
12900	softc = control_softc;
12901
12902	local_sglist = io->io_hdr.local_sglist;
12903	local_dma_sglist = io->io_hdr.local_dma_sglist;
12904	remote_sglist = io->io_hdr.remote_sglist;
12905	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12906
12907	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12908		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12909			local_sglist[i].len = remote_sglist[i].len;
12910
12911			/*
12912			 * XXX Detect the situation where the RS-level I/O
12913			 * redirector on the other side has already read the
12914			 * data off of the AOR RS on this side, and
12915			 * transferred it to remote (mirror) memory on the
12916			 * other side.  Since we already have the data in
12917			 * memory here, we just need to use it.
12918			 *
12919			 * XXX KDM this can probably be removed once we
12920			 * get the cache device code in and take the
12921			 * current AOR implementation out.
12922			 */
12923#ifdef NEEDTOPORT
12924			if ((remote_sglist[i].addr >=
12925			     (void *)vtophys(softc->mirr->addr))
12926			 && (remote_sglist[i].addr <
12927			     ((void *)vtophys(softc->mirr->addr) +
12928			     CacheMirrorOffset))) {
12929				local_sglist[i].addr = remote_sglist[i].addr -
12930					CacheMirrorOffset;
12931				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12932				     CTL_FLAG_DATA_IN)
12933					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12934			} else {
12935				local_sglist[i].addr = remote_sglist[i].addr +
12936					CacheMirrorOffset;
12937			}
12938#endif
12939#if 0
12940			printf("%s: local %p, remote %p, len %d\n",
12941			       __func__, local_sglist[i].addr,
12942			       remote_sglist[i].addr, local_sglist[i].len);
12943#endif
12944		}
12945	} else {
12946		uint32_t len_to_go;
12947
12948		/*
12949		 * In this case, we don't have automatically allocated
12950		 * memory for this I/O on this controller.  This typically
12951		 * happens with internal CTL I/O -- e.g. inquiry, mode
12952		 * sense, etc.  Anything coming from RAIDCore will have
12953		 * a mirror area available.
12954		 */
12955		len_to_go = io->scsiio.kern_data_len;
12956
12957		/*
12958		 * Clear the no datasync flag, we have to use malloced
12959		 * buffers.
12960		 */
12961		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12962
12963		/*
12964		 * The difficult thing here is that the size of the various
12965		 * S/G segments may be different than the size from the
12966		 * remote controller.  That'll make it harder when DMAing
12967		 * the data back to the other side.
12968		 */
12969		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12970		     sizeof(io->io_hdr.remote_sglist[0])) &&
12971		     (len_to_go > 0); i++) {
12972			local_sglist[i].len = ctl_min(len_to_go, 131072);
12973			CTL_SIZE_8B(local_dma_sglist[i].len,
12974				    local_sglist[i].len);
12975			local_sglist[i].addr =
12976				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12977
12978			local_dma_sglist[i].addr = local_sglist[i].addr;
12979
12980			if (local_sglist[i].addr == NULL) {
12981				int j;
12982
12983				printf("malloc failed for %zd bytes!",
12984				       local_dma_sglist[i].len);
12985				for (j = 0; j < i; j++) {
12986					free(local_sglist[j].addr, M_CTL);
12987				}
12988				ctl_set_internal_failure(&io->scsiio,
12989							 /*sks_valid*/ 1,
12990							 /*retry_count*/ 4857);
12991				retval = 1;
12992				goto bailout_error;
12993
12994			}
12995			/* XXX KDM do we need a sync here? */
12996
12997			len_to_go -= local_sglist[i].len;
12998		}
12999		/*
13000		 * Reset the number of S/G entries accordingly.  The
13001		 * original number of S/G entries is available in
13002		 * rem_sg_entries.
13003		 */
13004		io->scsiio.kern_sg_entries = i;
13005
13006#if 0
13007		printf("%s: kern_sg_entries = %d\n", __func__,
13008		       io->scsiio.kern_sg_entries);
13009		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13010			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13011			       local_sglist[i].addr, local_sglist[i].len,
13012			       local_dma_sglist[i].len);
13013#endif
13014	}
13015
13016
13017	return (retval);
13018
13019bailout_error:
13020
13021	ctl_send_datamove_done(io, /*have_lock*/ 0);
13022
13023	return (retval);
13024}
13025
13026static int
13027ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13028			 ctl_ha_dt_cb callback)
13029{
13030	struct ctl_ha_dt_req *rq;
13031	struct ctl_sg_entry *remote_sglist, *local_sglist;
13032	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13033	uint32_t local_used, remote_used, total_used;
13034	int retval;
13035	int i, j;
13036
13037	retval = 0;
13038
13039	rq = ctl_dt_req_alloc();
13040
13041	/*
13042	 * If we failed to allocate the request, and if the DMA didn't fail
13043	 * anyway, set busy status.  This is just a resource allocation
13044	 * failure.
13045	 */
13046	if ((rq == NULL)
13047	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13048		ctl_set_busy(&io->scsiio);
13049
13050	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13051
13052		if (rq != NULL)
13053			ctl_dt_req_free(rq);
13054
13055		/*
13056		 * The data move failed.  We need to return status back
13057		 * to the other controller.  No point in trying to DMA
13058		 * data to the remote controller.
13059		 */
13060
13061		ctl_send_datamove_done(io, /*have_lock*/ 0);
13062
13063		retval = 1;
13064
13065		goto bailout;
13066	}
13067
13068	local_sglist = io->io_hdr.local_sglist;
13069	local_dma_sglist = io->io_hdr.local_dma_sglist;
13070	remote_sglist = io->io_hdr.remote_sglist;
13071	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13072	local_used = 0;
13073	remote_used = 0;
13074	total_used = 0;
13075
13076	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13077		rq->ret = CTL_HA_STATUS_SUCCESS;
13078		rq->context = io;
13079		callback(rq);
13080		goto bailout;
13081	}
13082
13083	/*
13084	 * Pull/push the data over the wire from/to the other controller.
13085	 * This takes into account the possibility that the local and
13086	 * remote sglists may not be identical in terms of the size of
13087	 * the elements and the number of elements.
13088	 *
13089	 * One fundamental assumption here is that the length allocated for
13090	 * both the local and remote sglists is identical.  Otherwise, we've
13091	 * essentially got a coding error of some sort.
13092	 */
13093	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13094		int isc_ret;
13095		uint32_t cur_len, dma_length;
13096		uint8_t *tmp_ptr;
13097
13098		rq->id = CTL_HA_DATA_CTL;
13099		rq->command = command;
13100		rq->context = io;
13101
13102		/*
13103		 * Both pointers should be aligned.  But it is possible
13104		 * that the allocation length is not.  They should both
13105		 * also have enough slack left over at the end, though,
13106		 * to round up to the next 8 byte boundary.
13107		 */
13108		cur_len = ctl_min(local_sglist[i].len - local_used,
13109				  remote_sglist[j].len - remote_used);
13110
13111		/*
13112		 * In this case, we have a size issue and need to decrease
13113		 * the size, except in the case where we actually have less
13114		 * than 8 bytes left.  In that case, we need to increase
13115		 * the DMA length to get the last bit.
13116		 */
13117		if ((cur_len & 0x7) != 0) {
13118			if (cur_len > 0x7) {
13119				cur_len = cur_len - (cur_len & 0x7);
13120				dma_length = cur_len;
13121			} else {
13122				CTL_SIZE_8B(dma_length, cur_len);
13123			}
13124
13125		} else
13126			dma_length = cur_len;
13127
13128		/*
13129		 * If we had to allocate memory for this I/O, instead of using
13130		 * the non-cached mirror memory, we'll need to flush the cache
13131		 * before trying to DMA to the other controller.
13132		 *
13133		 * We could end up doing this multiple times for the same
13134		 * segment if we have a larger local segment than remote
13135		 * segment.  That shouldn't be an issue.
13136		 */
13137		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13138			/*
13139			 * XXX KDM use bus_dmamap_sync() here.
13140			 */
13141		}
13142
13143		rq->size = dma_length;
13144
13145		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13146		tmp_ptr += local_used;
13147
13148		/* Use physical addresses when talking to ISC hardware */
13149		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13150			/* XXX KDM use busdma */
13151#if 0
13152			rq->local = vtophys(tmp_ptr);
13153#endif
13154		} else
13155			rq->local = tmp_ptr;
13156
13157		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13158		tmp_ptr += remote_used;
13159		rq->remote = tmp_ptr;
13160
13161		rq->callback = NULL;
13162
13163		local_used += cur_len;
13164		if (local_used >= local_sglist[i].len) {
13165			i++;
13166			local_used = 0;
13167		}
13168
13169		remote_used += cur_len;
13170		if (remote_used >= remote_sglist[j].len) {
13171			j++;
13172			remote_used = 0;
13173		}
13174		total_used += cur_len;
13175
13176		if (total_used >= io->scsiio.kern_data_len)
13177			rq->callback = callback;
13178
13179		if ((rq->size & 0x7) != 0) {
13180			printf("%s: warning: size %d is not on 8b boundary\n",
13181			       __func__, rq->size);
13182		}
13183		if (((uintptr_t)rq->local & 0x7) != 0) {
13184			printf("%s: warning: local %p not on 8b boundary\n",
13185			       __func__, rq->local);
13186		}
13187		if (((uintptr_t)rq->remote & 0x7) != 0) {
13188			printf("%s: warning: remote %p not on 8b boundary\n",
13189			       __func__, rq->local);
13190		}
13191#if 0
13192		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13193		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13194		       rq->local, rq->remote, rq->size);
13195#endif
13196
13197		isc_ret = ctl_dt_single(rq);
13198		if (isc_ret == CTL_HA_STATUS_WAIT)
13199			continue;
13200
13201		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13202			rq->ret = CTL_HA_STATUS_SUCCESS;
13203		} else {
13204			rq->ret = isc_ret;
13205		}
13206		callback(rq);
13207		goto bailout;
13208	}
13209
13210bailout:
13211	return (retval);
13212
13213}
13214
13215static void
13216ctl_datamove_remote_read(union ctl_io *io)
13217{
13218	int retval;
13219	int i;
13220
13221	/*
13222	 * This will send an error to the other controller in the case of a
13223	 * failure.
13224	 */
13225	retval = ctl_datamove_remote_sgl_setup(io);
13226	if (retval != 0)
13227		return;
13228
13229	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13230					  ctl_datamove_remote_read_cb);
13231	if ((retval != 0)
13232	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13233		/*
13234		 * Make sure we free memory if there was an error..  The
13235		 * ctl_datamove_remote_xfer() function will send the
13236		 * datamove done message, or call the callback with an
13237		 * error if there is a problem.
13238		 */
13239		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13240			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13241	}
13242
13243	return;
13244}
13245
13246/*
13247 * Process a datamove request from the other controller.  This is used for
13248 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13249 * first.  Once that is complete, the data gets DMAed into the remote
13250 * controller's memory.  For reads, we DMA from the remote controller's
13251 * memory into our memory first, and then move it out to the FETD.
13252 */
13253static void
13254ctl_datamove_remote(union ctl_io *io)
13255{
13256	struct ctl_softc *softc;
13257
13258	softc = control_softc;
13259
13260	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13261
13262	/*
13263	 * Note that we look for an aborted I/O here, but don't do some of
13264	 * the other checks that ctl_datamove() normally does.
13265	 * We don't need to run the datamove delay code, since that should
13266	 * have been done if need be on the other controller.
13267	 */
13268	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13269		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13270		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13271		       io->io_hdr.nexus.targ_port,
13272		       io->io_hdr.nexus.targ_target.id,
13273		       io->io_hdr.nexus.targ_lun);
13274		io->io_hdr.port_status = 31338;
13275		ctl_send_datamove_done(io, /*have_lock*/ 0);
13276		return;
13277	}
13278
13279	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13280		ctl_datamove_remote_write(io);
13281	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13282		ctl_datamove_remote_read(io);
13283	} else {
13284		union ctl_ha_msg msg;
13285		struct scsi_sense_data *sense;
13286		uint8_t sks[3];
13287		int retry_count;
13288
13289		memset(&msg, 0, sizeof(msg));
13290
13291		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13292		msg.hdr.status = CTL_SCSI_ERROR;
13293		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13294
13295		retry_count = 4243;
13296
13297		sense = &msg.scsi.sense_data;
13298		sks[0] = SSD_SCS_VALID;
13299		sks[1] = (retry_count >> 8) & 0xff;
13300		sks[2] = retry_count & 0xff;
13301
13302		/* "Internal target failure" */
13303		scsi_set_sense_data(sense,
13304				    /*sense_format*/ SSD_TYPE_NONE,
13305				    /*current_error*/ 1,
13306				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13307				    /*asc*/ 0x44,
13308				    /*ascq*/ 0x00,
13309				    /*type*/ SSD_ELEM_SKS,
13310				    /*size*/ sizeof(sks),
13311				    /*data*/ sks,
13312				    SSD_ELEM_NONE);
13313
13314		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13315		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13316			ctl_failover_io(io, /*have_lock*/ 1);
13317			return;
13318		}
13319
13320		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13321		    CTL_HA_STATUS_SUCCESS) {
13322			/* XXX KDM what to do if this fails? */
13323		}
13324		return;
13325	}
13326
13327}
13328
13329static int
13330ctl_process_done(union ctl_io *io)
13331{
13332	struct ctl_lun *lun;
13333	struct ctl_softc *ctl_softc;
13334	void (*fe_done)(union ctl_io *io);
13335	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13336
13337	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13338
13339	fe_done =
13340	    control_softc->ctl_ports[targ_port]->fe_done;
13341
13342#ifdef CTL_TIME_IO
13343	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13344		char str[256];
13345		char path_str[64];
13346		struct sbuf sb;
13347
13348		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13349		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13350
13351		sbuf_cat(&sb, path_str);
13352		switch (io->io_hdr.io_type) {
13353		case CTL_IO_SCSI:
13354			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13355			sbuf_printf(&sb, "\n");
13356			sbuf_cat(&sb, path_str);
13357			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13358				    io->scsiio.tag_num, io->scsiio.tag_type);
13359			break;
13360		case CTL_IO_TASK:
13361			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13362				    "Tag Type: %d\n", io->taskio.task_action,
13363				    io->taskio.tag_num, io->taskio.tag_type);
13364			break;
13365		default:
13366			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13367			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13368			break;
13369		}
13370		sbuf_cat(&sb, path_str);
13371		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13372			    (intmax_t)time_uptime - io->io_hdr.start_time);
13373		sbuf_finish(&sb);
13374		printf("%s", sbuf_data(&sb));
13375	}
13376#endif /* CTL_TIME_IO */
13377
13378	switch (io->io_hdr.io_type) {
13379	case CTL_IO_SCSI:
13380		break;
13381	case CTL_IO_TASK:
13382		if (bootverbose || verbose > 0)
13383			ctl_io_error_print(io, NULL);
13384		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13385			ctl_free_io(io);
13386		else
13387			fe_done(io);
13388		return (CTL_RETVAL_COMPLETE);
13389		break;
13390	default:
13391		printf("ctl_process_done: invalid io type %d\n",
13392		       io->io_hdr.io_type);
13393		panic("ctl_process_done: invalid io type %d\n",
13394		      io->io_hdr.io_type);
13395		break; /* NOTREACHED */
13396	}
13397
13398	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13399	if (lun == NULL) {
13400		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13401				 io->io_hdr.nexus.targ_mapped_lun));
13402		fe_done(io);
13403		goto bailout;
13404	}
13405	ctl_softc = lun->ctl_softc;
13406
13407	mtx_lock(&lun->lun_lock);
13408
13409	/*
13410	 * Check to see if we have any errors to inject here.  We only
13411	 * inject errors for commands that don't already have errors set.
13412	 */
13413	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13414	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13415		ctl_inject_error(lun, io);
13416
13417	/*
13418	 * XXX KDM how do we treat commands that aren't completed
13419	 * successfully?
13420	 *
13421	 * XXX KDM should we also track I/O latency?
13422	 */
13423	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13424	    io->io_hdr.io_type == CTL_IO_SCSI) {
13425#ifdef CTL_TIME_IO
13426		struct bintime cur_bt;
13427#endif
13428		int type;
13429
13430		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13431		    CTL_FLAG_DATA_IN)
13432			type = CTL_STATS_READ;
13433		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13434		    CTL_FLAG_DATA_OUT)
13435			type = CTL_STATS_WRITE;
13436		else
13437			type = CTL_STATS_NO_IO;
13438
13439		lun->stats.ports[targ_port].bytes[type] +=
13440		    io->scsiio.kern_total_len;
13441		lun->stats.ports[targ_port].operations[type]++;
13442#ifdef CTL_TIME_IO
13443		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13444		   &io->io_hdr.dma_bt);
13445		lun->stats.ports[targ_port].num_dmas[type] +=
13446		    io->io_hdr.num_dmas;
13447		getbintime(&cur_bt);
13448		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13449		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13450#endif
13451	}
13452
13453	/*
13454	 * Remove this from the OOA queue.
13455	 */
13456	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13457
13458	/*
13459	 * Run through the blocked queue on this LUN and see if anything
13460	 * has become unblocked, now that this transaction is done.
13461	 */
13462	ctl_check_blocked(lun);
13463
13464	/*
13465	 * If the LUN has been invalidated, free it if there is nothing
13466	 * left on its OOA queue.
13467	 */
13468	if ((lun->flags & CTL_LUN_INVALID)
13469	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13470		mtx_unlock(&lun->lun_lock);
13471		mtx_lock(&ctl_softc->ctl_lock);
13472		ctl_free_lun(lun);
13473		mtx_unlock(&ctl_softc->ctl_lock);
13474	} else
13475		mtx_unlock(&lun->lun_lock);
13476
13477	/*
13478	 * If this command has been aborted, make sure we set the status
13479	 * properly.  The FETD is responsible for freeing the I/O and doing
13480	 * whatever it needs to do to clean up its state.
13481	 */
13482	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13483		ctl_set_task_aborted(&io->scsiio);
13484
13485	/*
13486	 * We print out status for every task management command.  For SCSI
13487	 * commands, we filter out any unit attention errors; they happen
13488	 * on every boot, and would clutter up the log.  Note:  task
13489	 * management commands aren't printed here, they are printed above,
13490	 * since they should never even make it down here.
13491	 */
13492	switch (io->io_hdr.io_type) {
13493	case CTL_IO_SCSI: {
13494		int error_code, sense_key, asc, ascq;
13495
13496		sense_key = 0;
13497
13498		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13499		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13500			/*
13501			 * Since this is just for printing, no need to
13502			 * show errors here.
13503			 */
13504			scsi_extract_sense_len(&io->scsiio.sense_data,
13505					       io->scsiio.sense_len,
13506					       &error_code,
13507					       &sense_key,
13508					       &asc,
13509					       &ascq,
13510					       /*show_errors*/ 0);
13511		}
13512
13513		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13514		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13515		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13516		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13517
13518			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13519				ctl_softc->skipped_prints++;
13520			} else {
13521				uint32_t skipped_prints;
13522
13523				skipped_prints = ctl_softc->skipped_prints;
13524
13525				ctl_softc->skipped_prints = 0;
13526				ctl_softc->last_print_jiffies = time_uptime;
13527
13528				if (skipped_prints > 0) {
13529#ifdef NEEDTOPORT
13530					csevent_log(CSC_CTL | CSC_SHELF_SW |
13531					    CTL_ERROR_REPORT,
13532					    csevent_LogType_Trace,
13533					    csevent_Severity_Information,
13534					    csevent_AlertLevel_Green,
13535					    csevent_FRU_Firmware,
13536					    csevent_FRU_Unknown,
13537					    "High CTL error volume, %d prints "
13538					    "skipped", skipped_prints);
13539#endif
13540				}
13541				if (bootverbose || verbose > 0)
13542					ctl_io_error_print(io, NULL);
13543			}
13544		}
13545		break;
13546	}
13547	case CTL_IO_TASK:
13548		if (bootverbose || verbose > 0)
13549			ctl_io_error_print(io, NULL);
13550		break;
13551	default:
13552		break;
13553	}
13554
13555	/*
13556	 * Tell the FETD or the other shelf controller we're done with this
13557	 * command.  Note that only SCSI commands get to this point.  Task
13558	 * management commands are completed above.
13559	 *
13560	 * We only send status to the other controller if we're in XFER
13561	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13562	 * received the I/O (from CTL's perspective), and so the status is
13563	 * generated there.
13564	 *
13565	 * XXX KDM if we hold the lock here, we could cause a deadlock
13566	 * if the frontend comes back in in this context to queue
13567	 * something.
13568	 */
13569	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13570	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13571		union ctl_ha_msg msg;
13572
13573		memset(&msg, 0, sizeof(msg));
13574		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13575		msg.hdr.original_sc = io->io_hdr.original_sc;
13576		msg.hdr.nexus = io->io_hdr.nexus;
13577		msg.hdr.status = io->io_hdr.status;
13578		msg.scsi.scsi_status = io->scsiio.scsi_status;
13579		msg.scsi.tag_num = io->scsiio.tag_num;
13580		msg.scsi.tag_type = io->scsiio.tag_type;
13581		msg.scsi.sense_len = io->scsiio.sense_len;
13582		msg.scsi.sense_residual = io->scsiio.sense_residual;
13583		msg.scsi.residual = io->scsiio.residual;
13584		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13585		       sizeof(io->scsiio.sense_data));
13586		/*
13587		 * We copy this whether or not this is an I/O-related
13588		 * command.  Otherwise, we'd have to go and check to see
13589		 * whether it's a read/write command, and it really isn't
13590		 * worth it.
13591		 */
13592		memcpy(&msg.scsi.lbalen,
13593		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13594		       sizeof(msg.scsi.lbalen));
13595
13596		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13597				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13598			/* XXX do something here */
13599		}
13600
13601		ctl_free_io(io);
13602	} else
13603		fe_done(io);
13604
13605bailout:
13606
13607	return (CTL_RETVAL_COMPLETE);
13608}
13609
13610/*
13611 * Front end should call this if it doesn't do autosense.  When the request
13612 * sense comes back in from the initiator, we'll dequeue this and send it.
13613 */
13614int
13615ctl_queue_sense(union ctl_io *io)
13616{
13617	struct ctl_lun *lun;
13618	struct ctl_softc *ctl_softc;
13619	uint32_t initidx, targ_lun;
13620
13621	ctl_softc = control_softc;
13622
13623	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13624
13625	/*
13626	 * LUN lookup will likely move to the ctl_work_thread() once we
13627	 * have our new queueing infrastructure (that doesn't put things on
13628	 * a per-LUN queue initially).  That is so that we can handle
13629	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13630	 * can't deal with that right now.
13631	 */
13632	mtx_lock(&ctl_softc->ctl_lock);
13633
13634	/*
13635	 * If we don't have a LUN for this, just toss the sense
13636	 * information.
13637	 */
13638	targ_lun = io->io_hdr.nexus.targ_lun;
13639	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13640	if ((targ_lun < CTL_MAX_LUNS)
13641	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13642		lun = ctl_softc->ctl_luns[targ_lun];
13643	else
13644		goto bailout;
13645
13646	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13647
13648	mtx_lock(&lun->lun_lock);
13649	/*
13650	 * Already have CA set for this LUN...toss the sense information.
13651	 */
13652	if (ctl_is_set(lun->have_ca, initidx)) {
13653		mtx_unlock(&lun->lun_lock);
13654		goto bailout;
13655	}
13656
13657	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13658	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
13659	       sizeof(io->scsiio.sense_data)));
13660	ctl_set_mask(lun->have_ca, initidx);
13661	mtx_unlock(&lun->lun_lock);
13662
13663bailout:
13664	mtx_unlock(&ctl_softc->ctl_lock);
13665
13666	ctl_free_io(io);
13667
13668	return (CTL_RETVAL_COMPLETE);
13669}
13670
13671/*
13672 * Primary command inlet from frontend ports.  All SCSI and task I/O
13673 * requests must go through this function.
13674 */
13675int
13676ctl_queue(union ctl_io *io)
13677{
13678	struct ctl_softc *ctl_softc;
13679
13680	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13681
13682	ctl_softc = control_softc;
13683
13684#ifdef CTL_TIME_IO
13685	io->io_hdr.start_time = time_uptime;
13686	getbintime(&io->io_hdr.start_bt);
13687#endif /* CTL_TIME_IO */
13688
13689	/* Map FE-specific LUN ID into global one. */
13690	io->io_hdr.nexus.targ_mapped_lun =
13691	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13692
13693	switch (io->io_hdr.io_type) {
13694	case CTL_IO_SCSI:
13695	case CTL_IO_TASK:
13696		ctl_enqueue_incoming(io);
13697		break;
13698	default:
13699		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13700		return (EINVAL);
13701	}
13702
13703	return (CTL_RETVAL_COMPLETE);
13704}
13705
13706#ifdef CTL_IO_DELAY
13707static void
13708ctl_done_timer_wakeup(void *arg)
13709{
13710	union ctl_io *io;
13711
13712	io = (union ctl_io *)arg;
13713	ctl_done(io);
13714}
13715#endif /* CTL_IO_DELAY */
13716
13717void
13718ctl_done(union ctl_io *io)
13719{
13720	struct ctl_softc *ctl_softc;
13721
13722	ctl_softc = control_softc;
13723
13724	/*
13725	 * Enable this to catch duplicate completion issues.
13726	 */
13727#if 0
13728	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13729		printf("%s: type %d msg %d cdb %x iptl: "
13730		       "%d:%d:%d:%d tag 0x%04x "
13731		       "flag %#x status %x\n",
13732			__func__,
13733			io->io_hdr.io_type,
13734			io->io_hdr.msg_type,
13735			io->scsiio.cdb[0],
13736			io->io_hdr.nexus.initid.id,
13737			io->io_hdr.nexus.targ_port,
13738			io->io_hdr.nexus.targ_target.id,
13739			io->io_hdr.nexus.targ_lun,
13740			(io->io_hdr.io_type ==
13741			CTL_IO_TASK) ?
13742			io->taskio.tag_num :
13743			io->scsiio.tag_num,
13744		        io->io_hdr.flags,
13745			io->io_hdr.status);
13746	} else
13747		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13748#endif
13749
13750	/*
13751	 * This is an internal copy of an I/O, and should not go through
13752	 * the normal done processing logic.
13753	 */
13754	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13755		return;
13756
13757	/*
13758	 * We need to send a msg to the serializing shelf to finish the IO
13759	 * as well.  We don't send a finish message to the other shelf if
13760	 * this is a task management command.  Task management commands
13761	 * aren't serialized in the OOA queue, but rather just executed on
13762	 * both shelf controllers for commands that originated on that
13763	 * controller.
13764	 */
13765	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13766	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13767		union ctl_ha_msg msg_io;
13768
13769		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13770		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13771		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13772		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13773		}
13774		/* continue on to finish IO */
13775	}
13776#ifdef CTL_IO_DELAY
13777	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13778		struct ctl_lun *lun;
13779
13780		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13781
13782		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13783	} else {
13784		struct ctl_lun *lun;
13785
13786		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13787
13788		if ((lun != NULL)
13789		 && (lun->delay_info.done_delay > 0)) {
13790			struct callout *callout;
13791
13792			callout = (struct callout *)&io->io_hdr.timer_bytes;
13793			callout_init(callout, /*mpsafe*/ 1);
13794			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13795			callout_reset(callout,
13796				      lun->delay_info.done_delay * hz,
13797				      ctl_done_timer_wakeup, io);
13798			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13799				lun->delay_info.done_delay = 0;
13800			return;
13801		}
13802	}
13803#endif /* CTL_IO_DELAY */
13804
13805	ctl_enqueue_done(io);
13806}
13807
13808int
13809ctl_isc(struct ctl_scsiio *ctsio)
13810{
13811	struct ctl_lun *lun;
13812	int retval;
13813
13814	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13815
13816	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13817
13818	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13819
13820	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13821
13822	return (retval);
13823}
13824
13825
13826static void
13827ctl_work_thread(void *arg)
13828{
13829	struct ctl_thread *thr = (struct ctl_thread *)arg;
13830	struct ctl_softc *softc = thr->ctl_softc;
13831	union ctl_io *io;
13832	int retval;
13833
13834	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13835
13836	for (;;) {
13837		retval = 0;
13838
13839		/*
13840		 * We handle the queues in this order:
13841		 * - ISC
13842		 * - done queue (to free up resources, unblock other commands)
13843		 * - RtR queue
13844		 * - incoming queue
13845		 *
13846		 * If those queues are empty, we break out of the loop and
13847		 * go to sleep.
13848		 */
13849		mtx_lock(&thr->queue_lock);
13850		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13851		if (io != NULL) {
13852			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13853			mtx_unlock(&thr->queue_lock);
13854			ctl_handle_isc(io);
13855			continue;
13856		}
13857		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13858		if (io != NULL) {
13859			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13860			/* clear any blocked commands, call fe_done */
13861			mtx_unlock(&thr->queue_lock);
13862			retval = ctl_process_done(io);
13863			continue;
13864		}
13865		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13866		if (io != NULL) {
13867			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13868			mtx_unlock(&thr->queue_lock);
13869			if (io->io_hdr.io_type == CTL_IO_TASK)
13870				ctl_run_task(io);
13871			else
13872				ctl_scsiio_precheck(softc, &io->scsiio);
13873			continue;
13874		}
13875		if (!ctl_pause_rtr) {
13876			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13877			if (io != NULL) {
13878				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13879				mtx_unlock(&thr->queue_lock);
13880				retval = ctl_scsiio(&io->scsiio);
13881				if (retval != CTL_RETVAL_COMPLETE)
13882					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13883				continue;
13884			}
13885		}
13886
13887		/* Sleep until we have something to do. */
13888		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13889	}
13890}
13891
13892static void
13893ctl_lun_thread(void *arg)
13894{
13895	struct ctl_softc *softc = (struct ctl_softc *)arg;
13896	struct ctl_be_lun *be_lun;
13897	int retval;
13898
13899	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13900
13901	for (;;) {
13902		retval = 0;
13903		mtx_lock(&softc->ctl_lock);
13904		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13905		if (be_lun != NULL) {
13906			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13907			mtx_unlock(&softc->ctl_lock);
13908			ctl_create_lun(be_lun);
13909			continue;
13910		}
13911
13912		/* Sleep until we have something to do. */
13913		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13914		    PDROP | PRIBIO, "-", 0);
13915	}
13916}
13917
13918static void
13919ctl_enqueue_incoming(union ctl_io *io)
13920{
13921	struct ctl_softc *softc = control_softc;
13922	struct ctl_thread *thr;
13923	u_int idx;
13924
13925	idx = (io->io_hdr.nexus.targ_port * 127 +
13926	       io->io_hdr.nexus.initid.id) % worker_threads;
13927	thr = &softc->threads[idx];
13928	mtx_lock(&thr->queue_lock);
13929	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13930	mtx_unlock(&thr->queue_lock);
13931	wakeup(thr);
13932}
13933
13934static void
13935ctl_enqueue_rtr(union ctl_io *io)
13936{
13937	struct ctl_softc *softc = control_softc;
13938	struct ctl_thread *thr;
13939
13940	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13941	mtx_lock(&thr->queue_lock);
13942	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13943	mtx_unlock(&thr->queue_lock);
13944	wakeup(thr);
13945}
13946
13947static void
13948ctl_enqueue_done(union ctl_io *io)
13949{
13950	struct ctl_softc *softc = control_softc;
13951	struct ctl_thread *thr;
13952
13953	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13954	mtx_lock(&thr->queue_lock);
13955	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13956	mtx_unlock(&thr->queue_lock);
13957	wakeup(thr);
13958}
13959
13960static void
13961ctl_enqueue_isc(union ctl_io *io)
13962{
13963	struct ctl_softc *softc = control_softc;
13964	struct ctl_thread *thr;
13965
13966	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13967	mtx_lock(&thr->queue_lock);
13968	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13969	mtx_unlock(&thr->queue_lock);
13970	wakeup(thr);
13971}
13972
13973/* Initialization and failover */
13974
13975void
13976ctl_init_isc_msg(void)
13977{
13978	printf("CTL: Still calling this thing\n");
13979}
13980
13981/*
13982 * Init component
13983 * 	Initializes component into configuration defined by bootMode
13984 *	(see hasc-sv.c)
13985 *  	returns hasc_Status:
13986 * 		OK
13987 *		ERROR - fatal error
13988 */
13989static ctl_ha_comp_status
13990ctl_isc_init(struct ctl_ha_component *c)
13991{
13992	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13993
13994	c->status = ret;
13995	return ret;
13996}
13997
13998/* Start component
13999 * 	Starts component in state requested. If component starts successfully,
14000 *	it must set its own state to the requestrd state
14001 *	When requested state is HASC_STATE_HA, the component may refine it
14002 * 	by adding _SLAVE or _MASTER flags.
14003 *	Currently allowed state transitions are:
14004 *	UNKNOWN->HA		- initial startup
14005 *	UNKNOWN->SINGLE - initial startup when no parter detected
14006 *	HA->SINGLE		- failover
14007 * returns ctl_ha_comp_status:
14008 * 		OK	- component successfully started in requested state
14009 *		FAILED  - could not start the requested state, failover may
14010 * 			  be possible
14011 *		ERROR	- fatal error detected, no future startup possible
14012 */
14013static ctl_ha_comp_status
14014ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14015{
14016	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14017
14018	printf("%s: go\n", __func__);
14019
14020	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14021	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14022		ctl_is_single = 0;
14023		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14024		    != CTL_HA_STATUS_SUCCESS) {
14025			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14026			ret = CTL_HA_COMP_STATUS_ERROR;
14027		}
14028	} else if (CTL_HA_STATE_IS_HA(c->state)
14029		&& CTL_HA_STATE_IS_SINGLE(state)){
14030		// HA->SINGLE transition
14031	        ctl_failover();
14032		ctl_is_single = 1;
14033	} else {
14034		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14035		       c->state, state);
14036		ret = CTL_HA_COMP_STATUS_ERROR;
14037	}
14038	if (CTL_HA_STATE_IS_SINGLE(state))
14039		ctl_is_single = 1;
14040
14041	c->state = state;
14042	c->status = ret;
14043	return ret;
14044}
14045
14046/*
14047 * Quiesce component
14048 * The component must clear any error conditions (set status to OK) and
14049 * prepare itself to another Start call
14050 * returns ctl_ha_comp_status:
14051 * 	OK
14052 *	ERROR
14053 */
14054static ctl_ha_comp_status
14055ctl_isc_quiesce(struct ctl_ha_component *c)
14056{
14057	int ret = CTL_HA_COMP_STATUS_OK;
14058
14059	ctl_pause_rtr = 1;
14060	c->status = ret;
14061	return ret;
14062}
14063
14064struct ctl_ha_component ctl_ha_component_ctlisc =
14065{
14066	.name = "CTL ISC",
14067	.state = CTL_HA_STATE_UNKNOWN,
14068	.init = ctl_isc_init,
14069	.start = ctl_isc_start,
14070	.quiesce = ctl_isc_quiesce
14071};
14072
14073/*
14074 *  vim: ts=8
14075 */
14076